id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_bad_4258_1 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#define DEBUG_TYPE "vm"
#include "JSLib/JSLibInternal.h"
#include "hermes/VM/Casting.h"
#include "hermes/VM/Interpreter.h"
#include "hermes/VM/StringPrimitive.h"
#include "Interpreter-internal.h"
using namespace hermes::inst;
namespace hermes {
namespace vm {
ExecutionStatus Interpreter::caseDirectEval(
Runtime *runtime,
PinnedHermesValue *frameRegs,
const Inst *ip) {
auto *result = &O1REG(DirectEval);
auto *input = &O2REG(DirectEval);
GCScopeMarkerRAII gcMarker{runtime};
// Check to see if global eval() has been overriden, in which case call it as
// as normal function.
auto global = runtime->getGlobal();
auto existingEval = global->getNamed_RJS(
global, runtime, Predefined::getSymbolID(Predefined::eval));
if (LLVM_UNLIKELY(existingEval == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto *nativeExistingEval = dyn_vmcast<NativeFunction>(existingEval->get());
if (LLVM_UNLIKELY(
!nativeExistingEval ||
nativeExistingEval->getFunctionPtr() != hermes::vm::eval)) {
if (auto *existingEvalCallable =
dyn_vmcast<Callable>(existingEval->get())) {
auto evalRes = existingEvalCallable->executeCall1(
runtime->makeHandle<Callable>(existingEvalCallable),
runtime,
Runtime::getUndefinedValue(),
*input);
if (LLVM_UNLIKELY(evalRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
*result = evalRes->get();
evalRes->invalidate();
return ExecutionStatus::RETURNED;
}
return runtime->raiseTypeErrorForValue(
runtime->makeHandle(std::move(*existingEval)), " is not a function");
}
if (!input->isString()) {
*result = *input;
return ExecutionStatus::RETURNED;
}
// Create a dummy scope, so that the local eval executes in its own scope
// (as per the spec for strict callers, which is the only thing we support).
ScopeChain scopeChain{};
scopeChain.functions.emplace_back();
auto cr = vm::directEval(
runtime, Handle<StringPrimitive>::vmcast(input), scopeChain, false);
if (cr == ExecutionStatus::EXCEPTION)
return ExecutionStatus::EXCEPTION;
*result = *cr;
return ExecutionStatus::RETURNED;
}
ExecutionStatus Interpreter::casePutOwnByVal(
Runtime *runtime,
PinnedHermesValue *frameRegs,
const Inst *ip) {
return JSObject::defineOwnComputed(
Handle<JSObject>::vmcast(&O1REG(PutOwnByVal)),
runtime,
Handle<>(&O3REG(PutOwnByVal)),
ip->iPutOwnByVal.op4
? DefinePropertyFlags::getDefaultNewPropertyFlags()
: DefinePropertyFlags::getNewNonEnumerableFlags(),
Handle<>(&O2REG(PutOwnByVal)))
.getStatus();
}
ExecutionStatus Interpreter::casePutOwnGetterSetterByVal(
Runtime *runtime,
PinnedHermesValue *frameRegs,
const inst::Inst *ip) {
DefinePropertyFlags dpFlags{};
dpFlags.setConfigurable = 1;
dpFlags.configurable = 1;
dpFlags.setEnumerable = 1;
dpFlags.enumerable = ip->iPutOwnGetterSetterByVal.op5;
MutableHandle<Callable> getter(runtime);
MutableHandle<Callable> setter(runtime);
if (LLVM_LIKELY(!O3REG(PutOwnGetterSetterByVal).isUndefined())) {
dpFlags.setGetter = 1;
getter = vmcast<Callable>(O3REG(PutOwnGetterSetterByVal));
}
if (LLVM_LIKELY(!O4REG(PutOwnGetterSetterByVal).isUndefined())) {
dpFlags.setSetter = 1;
setter = vmcast<Callable>(O4REG(PutOwnGetterSetterByVal));
}
assert(
(dpFlags.setSetter || dpFlags.setGetter) &&
"No accessor set in PutOwnGetterSetterByVal");
auto res = PropertyAccessor::create(runtime, getter, setter);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
return ExecutionStatus::EXCEPTION;
auto accessor = runtime->makeHandle<PropertyAccessor>(*res);
return JSObject::defineOwnComputed(
Handle<JSObject>::vmcast(&O1REG(PutOwnGetterSetterByVal)),
runtime,
Handle<>(&O2REG(PutOwnGetterSetterByVal)),
dpFlags,
accessor)
.getStatus();
}
ExecutionStatus Interpreter::caseIteratorBegin(
Runtime *runtime,
PinnedHermesValue *frameRegs,
const inst::Inst *ip) {
if (LLVM_LIKELY(vmisa<JSArray>(O2REG(IteratorBegin)))) {
// Attempt to get the fast path for array iteration.
NamedPropertyDescriptor desc;
JSObject *propObj = JSObject::getNamedDescriptor(
Handle<JSArray>::vmcast(&O2REG(IteratorBegin)),
runtime,
Predefined::getSymbolID(Predefined::SymbolIterator),
desc);
if (propObj) {
HermesValue slotValue =
JSObject::getNamedSlotValue(propObj, runtime, desc);
if (slotValue.getRaw() == runtime->arrayPrototypeValues.getRaw()) {
O1REG(IteratorBegin) = HermesValue::encodeNumberValue(0);
return ExecutionStatus::RETURNED;
}
}
}
GCScopeMarkerRAII marker{runtime};
CallResult<IteratorRecord> iterRecord =
getIterator(runtime, Handle<>(&O2REG(IteratorBegin)));
if (LLVM_UNLIKELY(iterRecord == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
O1REG(IteratorBegin) = iterRecord->iterator.getHermesValue();
O2REG(IteratorBegin) = iterRecord->nextMethod.getHermesValue();
return ExecutionStatus::RETURNED;
}
ExecutionStatus Interpreter::caseIteratorNext(
Runtime *runtime,
PinnedHermesValue *frameRegs,
const inst::Inst *ip) {
if (LLVM_LIKELY(O2REG(IteratorNext).isNumber())) {
JSArray::size_type i =
O2REG(IteratorNext).getNumberAs<JSArray::size_type>();
if (i >= JSArray::getLength(vmcast<JSArray>(O3REG(IteratorNext)))) {
// Finished iterating the array, stop.
O2REG(IteratorNext) = HermesValue::encodeUndefinedValue();
O1REG(IteratorNext) = HermesValue::encodeUndefinedValue();
return ExecutionStatus::RETURNED;
}
Handle<JSArray> arr = Handle<JSArray>::vmcast(&O3REG(IteratorNext));
{
// Fast path: look up the property in indexed storage.
// Runs when there is no hole and a regular non-accessor property exists
// at the current index, because those are the only properties stored
// in indexed storage.
// If there is another kind of property we have to call getComputed_RJS.
// No need to check the fastIndexProperties flag because the indexed
// storage would be deleted and at() would return empty in that case.
NoAllocScope noAlloc{runtime};
HermesValue value = arr->at(runtime, i);
if (LLVM_LIKELY(!value.isEmpty())) {
O1REG(IteratorNext) = value;
O2REG(IteratorNext) = HermesValue::encodeNumberValue(i + 1);
return ExecutionStatus::RETURNED;
}
}
// Slow path, just run the full getComputedPropertyValue_RJS path.
GCScopeMarkerRAII marker{runtime};
Handle<> idxHandle{&O2REG(IteratorNext)};
CallResult<PseudoHandle<>> valueRes =
JSObject::getComputed_RJS(arr, runtime, idxHandle);
if (LLVM_UNLIKELY(valueRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
O1REG(IteratorNext) = valueRes->get();
O2REG(IteratorNext) = HermesValue::encodeNumberValue(i + 1);
return ExecutionStatus::RETURNED;
}
if (LLVM_UNLIKELY(O2REG(IteratorNext).isUndefined())) {
// In all current use cases of IteratorNext, we check and branch away
// from IteratorNext in the case that iterStorage was set to undefined
// (which indicates completion of iteration).
// If we introduce a use case which allows calling IteratorNext,
// then this assert can be removed. For now, this branch just returned
// undefined in NDEBUG mode.
assert(false && "IteratorNext called on completed iterator");
O1REG(IteratorNext) = HermesValue::encodeUndefinedValue();
return ExecutionStatus::RETURNED;
}
GCScopeMarkerRAII marker{runtime};
IteratorRecord iterRecord{Handle<JSObject>::vmcast(&O2REG(IteratorNext)),
Handle<Callable>::vmcast(&O3REG(IteratorNext))};
CallResult<PseudoHandle<JSObject>> resultObjRes =
iteratorNext(runtime, iterRecord, llvh::None);
if (LLVM_UNLIKELY(resultObjRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
Handle<JSObject> resultObj = runtime->makeHandle(std::move(*resultObjRes));
CallResult<PseudoHandle<>> doneRes = JSObject::getNamed_RJS(
resultObj, runtime, Predefined::getSymbolID(Predefined::done));
if (LLVM_UNLIKELY(doneRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
if (toBoolean(doneRes->get())) {
// Done with iteration. Clear the iterator so that subsequent
// instructions do not call next() or return().
O2REG(IteratorNext) = HermesValue::encodeUndefinedValue();
O1REG(IteratorNext) = HermesValue::encodeUndefinedValue();
} else {
// Not done iterating, so get the `value` property and store it
// as the result.
CallResult<PseudoHandle<>> propRes = JSObject::getNamed_RJS(
resultObj, runtime, Predefined::getSymbolID(Predefined::value));
if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
O1REG(IteratorNext) = propRes->get();
propRes->invalidate();
}
return ExecutionStatus::RETURNED;
}
} // namespace vm
} // namespace hermes
| ./CrossVul/dataset_final_sorted/CWE-670/cpp/bad_4258_1 |
crossvul-cpp_data_good_4258_1 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#define DEBUG_TYPE "vm"
#include "JSLib/JSLibInternal.h"
#include "hermes/VM/Casting.h"
#include "hermes/VM/Interpreter.h"
#include "hermes/VM/StackFrame-inline.h"
#include "hermes/VM/StringPrimitive.h"
#include "Interpreter-internal.h"
using namespace hermes::inst;
namespace hermes {
namespace vm {
void Interpreter::saveGenerator(
Runtime *runtime,
PinnedHermesValue *frameRegs,
const Inst *resumeIP) {
auto *innerFn = vmcast<GeneratorInnerFunction>(FRAME.getCalleeClosure());
innerFn->saveStack(runtime);
innerFn->setNextIP(resumeIP);
innerFn->setState(GeneratorInnerFunction::State::SuspendedYield);
}
ExecutionStatus Interpreter::caseDirectEval(
Runtime *runtime,
PinnedHermesValue *frameRegs,
const Inst *ip) {
auto *result = &O1REG(DirectEval);
auto *input = &O2REG(DirectEval);
GCScopeMarkerRAII gcMarker{runtime};
// Check to see if global eval() has been overriden, in which case call it as
// as normal function.
auto global = runtime->getGlobal();
auto existingEval = global->getNamed_RJS(
global, runtime, Predefined::getSymbolID(Predefined::eval));
if (LLVM_UNLIKELY(existingEval == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto *nativeExistingEval = dyn_vmcast<NativeFunction>(existingEval->get());
if (LLVM_UNLIKELY(
!nativeExistingEval ||
nativeExistingEval->getFunctionPtr() != hermes::vm::eval)) {
if (auto *existingEvalCallable =
dyn_vmcast<Callable>(existingEval->get())) {
auto evalRes = existingEvalCallable->executeCall1(
runtime->makeHandle<Callable>(existingEvalCallable),
runtime,
Runtime::getUndefinedValue(),
*input);
if (LLVM_UNLIKELY(evalRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
*result = evalRes->get();
evalRes->invalidate();
return ExecutionStatus::RETURNED;
}
return runtime->raiseTypeErrorForValue(
runtime->makeHandle(std::move(*existingEval)), " is not a function");
}
if (!input->isString()) {
*result = *input;
return ExecutionStatus::RETURNED;
}
// Create a dummy scope, so that the local eval executes in its own scope
// (as per the spec for strict callers, which is the only thing we support).
ScopeChain scopeChain{};
scopeChain.functions.emplace_back();
auto cr = vm::directEval(
runtime, Handle<StringPrimitive>::vmcast(input), scopeChain, false);
if (cr == ExecutionStatus::EXCEPTION)
return ExecutionStatus::EXCEPTION;
*result = *cr;
return ExecutionStatus::RETURNED;
}
ExecutionStatus Interpreter::casePutOwnByVal(
Runtime *runtime,
PinnedHermesValue *frameRegs,
const Inst *ip) {
return JSObject::defineOwnComputed(
Handle<JSObject>::vmcast(&O1REG(PutOwnByVal)),
runtime,
Handle<>(&O3REG(PutOwnByVal)),
ip->iPutOwnByVal.op4
? DefinePropertyFlags::getDefaultNewPropertyFlags()
: DefinePropertyFlags::getNewNonEnumerableFlags(),
Handle<>(&O2REG(PutOwnByVal)))
.getStatus();
}
ExecutionStatus Interpreter::casePutOwnGetterSetterByVal(
Runtime *runtime,
PinnedHermesValue *frameRegs,
const inst::Inst *ip) {
DefinePropertyFlags dpFlags{};
dpFlags.setConfigurable = 1;
dpFlags.configurable = 1;
dpFlags.setEnumerable = 1;
dpFlags.enumerable = ip->iPutOwnGetterSetterByVal.op5;
MutableHandle<Callable> getter(runtime);
MutableHandle<Callable> setter(runtime);
if (LLVM_LIKELY(!O3REG(PutOwnGetterSetterByVal).isUndefined())) {
dpFlags.setGetter = 1;
getter = vmcast<Callable>(O3REG(PutOwnGetterSetterByVal));
}
if (LLVM_LIKELY(!O4REG(PutOwnGetterSetterByVal).isUndefined())) {
dpFlags.setSetter = 1;
setter = vmcast<Callable>(O4REG(PutOwnGetterSetterByVal));
}
assert(
(dpFlags.setSetter || dpFlags.setGetter) &&
"No accessor set in PutOwnGetterSetterByVal");
auto res = PropertyAccessor::create(runtime, getter, setter);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
return ExecutionStatus::EXCEPTION;
auto accessor = runtime->makeHandle<PropertyAccessor>(*res);
return JSObject::defineOwnComputed(
Handle<JSObject>::vmcast(&O1REG(PutOwnGetterSetterByVal)),
runtime,
Handle<>(&O2REG(PutOwnGetterSetterByVal)),
dpFlags,
accessor)
.getStatus();
}
ExecutionStatus Interpreter::caseIteratorBegin(
Runtime *runtime,
PinnedHermesValue *frameRegs,
const inst::Inst *ip) {
if (LLVM_LIKELY(vmisa<JSArray>(O2REG(IteratorBegin)))) {
// Attempt to get the fast path for array iteration.
NamedPropertyDescriptor desc;
JSObject *propObj = JSObject::getNamedDescriptor(
Handle<JSArray>::vmcast(&O2REG(IteratorBegin)),
runtime,
Predefined::getSymbolID(Predefined::SymbolIterator),
desc);
if (propObj) {
HermesValue slotValue =
JSObject::getNamedSlotValue(propObj, runtime, desc);
if (slotValue.getRaw() == runtime->arrayPrototypeValues.getRaw()) {
O1REG(IteratorBegin) = HermesValue::encodeNumberValue(0);
return ExecutionStatus::RETURNED;
}
}
}
GCScopeMarkerRAII marker{runtime};
CallResult<IteratorRecord> iterRecord =
getIterator(runtime, Handle<>(&O2REG(IteratorBegin)));
if (LLVM_UNLIKELY(iterRecord == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
O1REG(IteratorBegin) = iterRecord->iterator.getHermesValue();
O2REG(IteratorBegin) = iterRecord->nextMethod.getHermesValue();
return ExecutionStatus::RETURNED;
}
ExecutionStatus Interpreter::caseIteratorNext(
Runtime *runtime,
PinnedHermesValue *frameRegs,
const inst::Inst *ip) {
if (LLVM_LIKELY(O2REG(IteratorNext).isNumber())) {
JSArray::size_type i =
O2REG(IteratorNext).getNumberAs<JSArray::size_type>();
if (i >= JSArray::getLength(vmcast<JSArray>(O3REG(IteratorNext)))) {
// Finished iterating the array, stop.
O2REG(IteratorNext) = HermesValue::encodeUndefinedValue();
O1REG(IteratorNext) = HermesValue::encodeUndefinedValue();
return ExecutionStatus::RETURNED;
}
Handle<JSArray> arr = Handle<JSArray>::vmcast(&O3REG(IteratorNext));
{
// Fast path: look up the property in indexed storage.
// Runs when there is no hole and a regular non-accessor property exists
// at the current index, because those are the only properties stored
// in indexed storage.
// If there is another kind of property we have to call getComputed_RJS.
// No need to check the fastIndexProperties flag because the indexed
// storage would be deleted and at() would return empty in that case.
NoAllocScope noAlloc{runtime};
HermesValue value = arr->at(runtime, i);
if (LLVM_LIKELY(!value.isEmpty())) {
O1REG(IteratorNext) = value;
O2REG(IteratorNext) = HermesValue::encodeNumberValue(i + 1);
return ExecutionStatus::RETURNED;
}
}
// Slow path, just run the full getComputedPropertyValue_RJS path.
GCScopeMarkerRAII marker{runtime};
Handle<> idxHandle{&O2REG(IteratorNext)};
CallResult<PseudoHandle<>> valueRes =
JSObject::getComputed_RJS(arr, runtime, idxHandle);
if (LLVM_UNLIKELY(valueRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
O1REG(IteratorNext) = valueRes->get();
O2REG(IteratorNext) = HermesValue::encodeNumberValue(i + 1);
return ExecutionStatus::RETURNED;
}
if (LLVM_UNLIKELY(O2REG(IteratorNext).isUndefined())) {
// In all current use cases of IteratorNext, we check and branch away
// from IteratorNext in the case that iterStorage was set to undefined
// (which indicates completion of iteration).
// If we introduce a use case which allows calling IteratorNext,
// then this assert can be removed. For now, this branch just returned
// undefined in NDEBUG mode.
assert(false && "IteratorNext called on completed iterator");
O1REG(IteratorNext) = HermesValue::encodeUndefinedValue();
return ExecutionStatus::RETURNED;
}
GCScopeMarkerRAII marker{runtime};
IteratorRecord iterRecord{Handle<JSObject>::vmcast(&O2REG(IteratorNext)),
Handle<Callable>::vmcast(&O3REG(IteratorNext))};
CallResult<PseudoHandle<JSObject>> resultObjRes =
iteratorNext(runtime, iterRecord, llvh::None);
if (LLVM_UNLIKELY(resultObjRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
Handle<JSObject> resultObj = runtime->makeHandle(std::move(*resultObjRes));
CallResult<PseudoHandle<>> doneRes = JSObject::getNamed_RJS(
resultObj, runtime, Predefined::getSymbolID(Predefined::done));
if (LLVM_UNLIKELY(doneRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
if (toBoolean(doneRes->get())) {
// Done with iteration. Clear the iterator so that subsequent
// instructions do not call next() or return().
O2REG(IteratorNext) = HermesValue::encodeUndefinedValue();
O1REG(IteratorNext) = HermesValue::encodeUndefinedValue();
} else {
// Not done iterating, so get the `value` property and store it
// as the result.
CallResult<PseudoHandle<>> propRes = JSObject::getNamed_RJS(
resultObj, runtime, Predefined::getSymbolID(Predefined::value));
if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
O1REG(IteratorNext) = propRes->get();
propRes->invalidate();
}
return ExecutionStatus::RETURNED;
}
} // namespace vm
} // namespace hermes
| ./CrossVul/dataset_final_sorted/CWE-670/cpp/good_4258_1 |
crossvul-cpp_data_bad_4258_2 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#define DEBUG_TYPE "vm"
#include "hermes/VM/Interpreter.h"
#include "hermes/VM/Runtime.h"
#include "hermes/Inst/InstDecode.h"
#include "hermes/Support/Conversions.h"
#include "hermes/Support/SlowAssert.h"
#include "hermes/Support/Statistic.h"
#include "hermes/VM/Callable.h"
#include "hermes/VM/CodeBlock.h"
#include "hermes/VM/HandleRootOwner-inline.h"
#include "hermes/VM/JIT/JIT.h"
#include "hermes/VM/JSArray.h"
#include "hermes/VM/JSError.h"
#include "hermes/VM/JSGenerator.h"
#include "hermes/VM/JSProxy.h"
#include "hermes/VM/JSRegExp.h"
#include "hermes/VM/Operations.h"
#include "hermes/VM/Profiler.h"
#include "hermes/VM/Profiler/CodeCoverageProfiler.h"
#include "hermes/VM/Runtime-inline.h"
#include "hermes/VM/RuntimeModule-inline.h"
#include "hermes/VM/StackFrame-inline.h"
#include "hermes/VM/StringPrimitive.h"
#include "hermes/VM/StringView.h"
#include "llvh/ADT/SmallSet.h"
#include "llvh/Support/Debug.h"
#include "llvh/Support/Format.h"
#include "llvh/Support/raw_ostream.h"
#include "Interpreter-internal.h"
using llvh::dbgs;
using namespace hermes::inst;
HERMES_SLOW_STATISTIC(
NumGetById,
"NumGetById: Number of property 'read by id' accesses");
HERMES_SLOW_STATISTIC(
NumGetByIdCacheHits,
"NumGetByIdCacheHits: Number of property 'read by id' cache hits");
HERMES_SLOW_STATISTIC(
NumGetByIdProtoHits,
"NumGetByIdProtoHits: Number of property 'read by id' cache hits for the prototype");
HERMES_SLOW_STATISTIC(
NumGetByIdCacheEvicts,
"NumGetByIdCacheEvicts: Number of property 'read by id' cache evictions");
HERMES_SLOW_STATISTIC(
NumGetByIdFastPaths,
"NumGetByIdFastPaths: Number of property 'read by id' fast paths");
HERMES_SLOW_STATISTIC(
NumGetByIdAccessor,
"NumGetByIdAccessor: Number of property 'read by id' accessors");
HERMES_SLOW_STATISTIC(
NumGetByIdProto,
"NumGetByIdProto: Number of property 'read by id' in the prototype chain");
HERMES_SLOW_STATISTIC(
NumGetByIdNotFound,
"NumGetByIdNotFound: Number of property 'read by id' not found");
HERMES_SLOW_STATISTIC(
NumGetByIdTransient,
"NumGetByIdTransient: Number of property 'read by id' of non-objects");
HERMES_SLOW_STATISTIC(
NumGetByIdDict,
"NumGetByIdDict: Number of property 'read by id' of dictionaries");
HERMES_SLOW_STATISTIC(
NumGetByIdSlow,
"NumGetByIdSlow: Number of property 'read by id' slow path");
HERMES_SLOW_STATISTIC(
NumPutById,
"NumPutById: Number of property 'write by id' accesses");
HERMES_SLOW_STATISTIC(
NumPutByIdCacheHits,
"NumPutByIdCacheHits: Number of property 'write by id' cache hits");
HERMES_SLOW_STATISTIC(
NumPutByIdCacheEvicts,
"NumPutByIdCacheEvicts: Number of property 'write by id' cache evictions");
HERMES_SLOW_STATISTIC(
NumPutByIdFastPaths,
"NumPutByIdFastPaths: Number of property 'write by id' fast paths");
HERMES_SLOW_STATISTIC(
NumPutByIdTransient,
"NumPutByIdTransient: Number of property 'write by id' to non-objects");
HERMES_SLOW_STATISTIC(
NumNativeFunctionCalls,
"NumNativeFunctionCalls: Number of native function calls");
HERMES_SLOW_STATISTIC(
NumBoundFunctionCalls,
"NumBoundCalls: Number of bound function calls");
// Ensure that instructions declared as having matching layouts actually do.
#include "InstLayout.inc"
#if defined(HERMESVM_PROFILER_EXTERN)
// External profiler mode wraps calls to each JS function with a unique native
// function that recusively calls the interpreter. See Profiler.{h,cpp} for how
// these symbols are subsequently patched with JS function names.
#define INTERP_WRAPPER(name) \
__attribute__((__noinline__)) static llvh::CallResult<llvh::HermesValue> \
name(hermes::vm::Runtime *runtime, hermes::vm::CodeBlock *newCodeBlock) { \
return runtime->interpretFunctionImpl(newCodeBlock); \
}
PROFILER_SYMBOLS(INTERP_WRAPPER)
#endif
namespace hermes {
namespace vm {
#if defined(HERMESVM_PROFILER_EXTERN)
typedef CallResult<HermesValue> (*WrapperFunc)(Runtime *, CodeBlock *);
#define LIST_ITEM(name) name,
static const WrapperFunc interpWrappers[] = {PROFILER_SYMBOLS(LIST_ITEM)};
#endif
/// Initialize the state of some internal variables based on the current
/// code block.
#define INIT_STATE_FOR_CODEBLOCK(codeBlock) \
do { \
strictMode = (codeBlock)->isStrictMode(); \
defaultPropOpFlags = DEFAULT_PROP_OP_FLAGS(strictMode); \
} while (0)
CallResult<PseudoHandle<JSGeneratorFunction>>
Interpreter::createGeneratorClosure(
Runtime *runtime,
RuntimeModule *runtimeModule,
unsigned funcIndex,
Handle<Environment> envHandle) {
return JSGeneratorFunction::create(
runtime,
runtimeModule->getDomain(runtime),
Handle<JSObject>::vmcast(&runtime->generatorFunctionPrototype),
envHandle,
runtimeModule->getCodeBlockMayAllocate(funcIndex));
}
CallResult<PseudoHandle<JSGenerator>> Interpreter::createGenerator_RJS(
Runtime *runtime,
RuntimeModule *runtimeModule,
unsigned funcIndex,
Handle<Environment> envHandle,
NativeArgs args) {
auto gifRes = GeneratorInnerFunction::create(
runtime,
runtimeModule->getDomain(runtime),
Handle<JSObject>::vmcast(&runtime->functionPrototype),
envHandle,
runtimeModule->getCodeBlockMayAllocate(funcIndex),
args);
if (LLVM_UNLIKELY(gifRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto generatorFunction = runtime->makeHandle(vmcast<JSGeneratorFunction>(
runtime->getCurrentFrame().getCalleeClosure()));
auto prototypeProp = JSObject::getNamed_RJS(
generatorFunction,
runtime,
Predefined::getSymbolID(Predefined::prototype));
if (LLVM_UNLIKELY(prototypeProp == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
Handle<JSObject> prototype = vmisa<JSObject>(prototypeProp->get())
? runtime->makeHandle<JSObject>(prototypeProp->get())
: Handle<JSObject>::vmcast(&runtime->generatorPrototype);
return JSGenerator::create(runtime, *gifRes, prototype);
}
CallResult<Handle<Arguments>> Interpreter::reifyArgumentsSlowPath(
Runtime *runtime,
Handle<Callable> curFunction,
bool strictMode) {
auto frame = runtime->getCurrentFrame();
uint32_t argCount = frame.getArgCount();
// Define each JavaScript argument.
auto argRes = Arguments::create(runtime, argCount, curFunction, strictMode);
if (LLVM_UNLIKELY(argRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
Handle<Arguments> args = *argRes;
for (uint32_t argIndex = 0; argIndex < argCount; ++argIndex) {
Arguments::unsafeSetExistingElementAt(
*args, runtime, argIndex, frame.getArgRef(argIndex));
}
// The returned value should already be set from the create call.
return args;
}
CallResult<PseudoHandle<>> Interpreter::getArgumentsPropByValSlowPath_RJS(
Runtime *runtime,
PinnedHermesValue *lazyReg,
PinnedHermesValue *valueReg,
Handle<Callable> curFunction,
bool strictMode) {
auto frame = runtime->getCurrentFrame();
// If the arguments object has already been created.
if (!lazyReg->isUndefined()) {
// The arguments object has been created, so this is a regular property
// get.
assert(lazyReg->isObject() && "arguments lazy register is not an object");
return JSObject::getComputed_RJS(
Handle<JSObject>::vmcast(lazyReg), runtime, Handle<>(valueReg));
}
if (!valueReg->isSymbol()) {
// Attempt a fast path in the case that the key is not a symbol.
// If it is a symbol, force reification for now.
// Convert the value to a string.
auto strRes = toString_RJS(runtime, Handle<>(valueReg));
if (strRes == ExecutionStatus::EXCEPTION)
return ExecutionStatus::EXCEPTION;
auto strPrim = runtime->makeHandle(std::move(*strRes));
// Check if the string is a valid argument index.
if (auto index = toArrayIndex(runtime, strPrim)) {
if (*index < frame.getArgCount()) {
return createPseudoHandle(frame.getArgRef(*index));
}
auto objectPrototype =
Handle<JSObject>::vmcast(&runtime->objectPrototype);
// OK, they are requesting an index that either doesn't exist or is
// somewhere up in the prototype chain. Since we want to avoid reifying,
// check which it is:
MutableHandle<JSObject> inObject{runtime};
ComputedPropertyDescriptor desc;
JSObject::getComputedPrimitiveDescriptor(
objectPrototype, runtime, strPrim, inObject, desc);
// If we couldn't find the property, just return 'undefined'.
if (!inObject)
return createPseudoHandle(HermesValue::encodeUndefinedValue());
// If the property isn't an accessor, we can just return it without
// reifying.
if (!desc.flags.accessor) {
return createPseudoHandle(
JSObject::getComputedSlotValue(inObject.get(), runtime, desc));
}
}
// Are they requesting "arguments.length"?
if (runtime->symbolEqualsToStringPrim(
Predefined::getSymbolID(Predefined::length), *strPrim)) {
return createPseudoHandle(
HermesValue::encodeDoubleValue(frame.getArgCount()));
}
}
// Looking for an accessor or a property that needs reification.
auto argRes = reifyArgumentsSlowPath(runtime, curFunction, strictMode);
if (argRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// Update the register with the reified value.
*lazyReg = argRes->getHermesValue();
// For simplicity, call ourselves again.
return getArgumentsPropByValSlowPath_RJS(
runtime, lazyReg, valueReg, curFunction, strictMode);
}
ExecutionStatus Interpreter::handleGetPNameList(
Runtime *runtime,
PinnedHermesValue *frameRegs,
const Inst *ip) {
if (O2REG(GetPNameList).isUndefined() || O2REG(GetPNameList).isNull()) {
// Set the iterator to be undefined value.
O1REG(GetPNameList) = HermesValue::encodeUndefinedValue();
return ExecutionStatus::RETURNED;
}
// Convert to object and store it back to the register.
auto res = toObject(runtime, Handle<>(&O2REG(GetPNameList)));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
O2REG(GetPNameList) = res.getValue();
auto obj = runtime->makeMutableHandle(vmcast<JSObject>(res.getValue()));
uint32_t beginIndex;
uint32_t endIndex;
auto cr = getForInPropertyNames(runtime, obj, beginIndex, endIndex);
if (cr == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto arr = *cr;
O1REG(GetPNameList) = arr.getHermesValue();
O3REG(GetPNameList) = HermesValue::encodeNumberValue(beginIndex);
O4REG(GetPNameList) = HermesValue::encodeNumberValue(endIndex);
return ExecutionStatus::RETURNED;
}
CallResult<PseudoHandle<>> Interpreter::handleCallSlowPath(
Runtime *runtime,
PinnedHermesValue *callTarget) {
if (auto *native = dyn_vmcast<NativeFunction>(*callTarget)) {
++NumNativeFunctionCalls;
// Call the native function directly
return NativeFunction::_nativeCall(native, runtime);
} else if (auto *bound = dyn_vmcast<BoundFunction>(*callTarget)) {
++NumBoundFunctionCalls;
// Call the bound function.
return BoundFunction::_boundCall(bound, runtime->getCurrentIP(), runtime);
} else {
return runtime->raiseTypeErrorForValue(
Handle<>(callTarget), " is not a function");
}
}
inline PseudoHandle<> Interpreter::tryGetPrimitiveOwnPropertyById(
Runtime *runtime,
Handle<> base,
SymbolID id) {
if (base->isString() && id == Predefined::getSymbolID(Predefined::length)) {
return createPseudoHandle(
HermesValue::encodeNumberValue(base->getString()->getStringLength()));
}
return createPseudoHandle(HermesValue::encodeEmptyValue());
}
CallResult<PseudoHandle<>> Interpreter::getByIdTransient_RJS(
Runtime *runtime,
Handle<> base,
SymbolID id) {
// This is similar to what ES5.1 8.7.1 special [[Get]] internal
// method did, but that section doesn't exist in ES9 anymore.
// Instead, the [[Get]] Receiver argument serves a similar purpose.
// Fast path: try to get primitive own property directly first.
PseudoHandle<> valOpt = tryGetPrimitiveOwnPropertyById(runtime, base, id);
if (!valOpt->isEmpty()) {
return valOpt;
}
// get the property descriptor from primitive prototype without
// boxing with vm::toObject(). This is where any properties will
// be.
CallResult<Handle<JSObject>> primitivePrototypeResult =
getPrimitivePrototype(runtime, base);
if (primitivePrototypeResult == ExecutionStatus::EXCEPTION) {
// If an exception is thrown, likely we are trying to read property on
// undefined/null. Passing over the name of the property
// so that we could emit more meaningful error messages.
return amendPropAccessErrorMsgWithPropName(runtime, base, "read", id);
}
return JSObject::getNamedWithReceiver_RJS(
*primitivePrototypeResult, runtime, id, base);
}
PseudoHandle<> Interpreter::getByValTransientFast(
Runtime *runtime,
Handle<> base,
Handle<> nameHandle) {
if (base->isString()) {
// Handle most common fast path -- array index property for string
// primitive.
// Since primitive string cannot have index like property we can
// skip ObjectFlags::fastIndexProperties checking and directly
// checking index storage from StringPrimitive.
OptValue<uint32_t> arrayIndex = toArrayIndexFastPath(*nameHandle);
// Get character directly from primitive if arrayIndex is within range.
// Otherwise we need to fall back to prototype lookup.
if (arrayIndex &&
arrayIndex.getValue() < base->getString()->getStringLength()) {
return createPseudoHandle(
runtime
->getCharacterString(base->getString()->at(arrayIndex.getValue()))
.getHermesValue());
}
}
return createPseudoHandle(HermesValue::encodeEmptyValue());
}
CallResult<PseudoHandle<>> Interpreter::getByValTransient_RJS(
Runtime *runtime,
Handle<> base,
Handle<> name) {
// This is similar to what ES5.1 8.7.1 special [[Get]] internal
// method did, but that section doesn't exist in ES9 anymore.
// Instead, the [[Get]] Receiver argument serves a similar purpose.
// Optimization: check fast path first.
PseudoHandle<> fastRes = getByValTransientFast(runtime, base, name);
if (!fastRes->isEmpty()) {
return fastRes;
}
auto res = toObject(runtime, base);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
return ExecutionStatus::EXCEPTION;
return JSObject::getComputedWithReceiver_RJS(
runtime->makeHandle<JSObject>(res.getValue()), runtime, name, base);
}
static ExecutionStatus
transientObjectPutErrorMessage(Runtime *runtime, Handle<> base, SymbolID id) {
// Emit an error message that looks like:
// "Cannot create property '%{id}' on ${typeof base} '${String(base)}'".
StringView propName =
runtime->getIdentifierTable().getStringView(runtime, id);
Handle<StringPrimitive> baseType =
runtime->makeHandle(vmcast<StringPrimitive>(typeOf(runtime, base)));
StringView baseTypeAsString =
StringPrimitive::createStringView(runtime, baseType);
MutableHandle<StringPrimitive> valueAsString{runtime};
if (base->isSymbol()) {
// Special workaround for Symbol which can't be stringified.
auto str = symbolDescriptiveString(runtime, Handle<SymbolID>::vmcast(base));
if (str != ExecutionStatus::EXCEPTION) {
valueAsString = *str;
} else {
runtime->clearThrownValue();
valueAsString = StringPrimitive::createNoThrow(
runtime, "<<Exception occurred getting the value>>");
}
} else {
auto str = toString_RJS(runtime, base);
assert(
str != ExecutionStatus::EXCEPTION &&
"Primitives should be convertible to string without exceptions");
valueAsString = std::move(*str);
}
StringView valueAsStringPrintable =
StringPrimitive::createStringView(runtime, valueAsString);
SmallU16String<32> tmp1;
SmallU16String<32> tmp2;
return runtime->raiseTypeError(
TwineChar16("Cannot create property '") + propName + "' on " +
baseTypeAsString.getUTF16Ref(tmp1) + " '" +
valueAsStringPrintable.getUTF16Ref(tmp2) + "'");
}
ExecutionStatus Interpreter::putByIdTransient_RJS(
Runtime *runtime,
Handle<> base,
SymbolID id,
Handle<> value,
bool strictMode) {
// ES5.1 8.7.2 special [[Get]] internal method.
// TODO: avoid boxing primitives unless we are calling an accessor.
// 1. Let O be ToObject(base)
auto res = toObject(runtime, base);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
// If an exception is thrown, likely we are trying to convert
// undefined/null to an object. Passing over the name of the property
// so that we could emit more meaningful error messages.
return amendPropAccessErrorMsgWithPropName(runtime, base, "set", id);
}
auto O = runtime->makeHandle<JSObject>(res.getValue());
NamedPropertyDescriptor desc;
JSObject *propObj = JSObject::getNamedDescriptor(O, runtime, id, desc);
// Is this a missing property, or a data property defined in the prototype
// chain? In both cases we would need to create an own property on the
// transient object, which is prohibited.
if (!propObj ||
(propObj != O.get() &&
(!desc.flags.accessor && !desc.flags.proxyObject))) {
if (strictMode) {
return transientObjectPutErrorMessage(runtime, base, id);
}
return ExecutionStatus::RETURNED;
}
// Modifying an own data property in a transient object is prohibited.
if (!desc.flags.accessor && !desc.flags.proxyObject) {
if (strictMode) {
return runtime->raiseTypeError(
"Cannot modify a property in a transient object");
}
return ExecutionStatus::RETURNED;
}
if (desc.flags.accessor) {
// This is an accessor.
auto *accessor = vmcast<PropertyAccessor>(
JSObject::getNamedSlotValue(propObj, runtime, desc));
// It needs to have a setter.
if (!accessor->setter) {
if (strictMode) {
return runtime->raiseTypeError("Cannot modify a read-only accessor");
}
return ExecutionStatus::RETURNED;
}
CallResult<PseudoHandle<>> setRes =
accessor->setter.get(runtime)->executeCall1(
runtime->makeHandle(accessor->setter), runtime, base, *value);
if (setRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
} else {
assert(desc.flags.proxyObject && "descriptor flags are impossible");
CallResult<bool> setRes = JSProxy::setNamed(
runtime->makeHandle(propObj), runtime, id, value, base);
if (setRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
if (!*setRes && strictMode) {
return runtime->raiseTypeError("transient proxy set returned false");
}
}
return ExecutionStatus::RETURNED;
}
ExecutionStatus Interpreter::putByValTransient_RJS(
Runtime *runtime,
Handle<> base,
Handle<> name,
Handle<> value,
bool strictMode) {
auto idRes = valueToSymbolID(runtime, name);
if (idRes == ExecutionStatus::EXCEPTION)
return ExecutionStatus::EXCEPTION;
return putByIdTransient_RJS(runtime, base, **idRes, value, strictMode);
}
CallResult<PseudoHandle<>> Interpreter::createObjectFromBuffer(
Runtime *runtime,
CodeBlock *curCodeBlock,
unsigned numLiterals,
unsigned keyBufferIndex,
unsigned valBufferIndex) {
// Fetch any cached hidden class first.
auto *runtimeModule = curCodeBlock->getRuntimeModule();
const llvh::Optional<Handle<HiddenClass>> optCachedHiddenClassHandle =
runtimeModule->findCachedLiteralHiddenClass(
runtime, keyBufferIndex, numLiterals);
// Create a new object using the built-in constructor or cached hidden class.
// Note that the built-in constructor is empty, so we don't actually need to
// call it.
auto obj = runtime->makeHandle(
optCachedHiddenClassHandle.hasValue()
? JSObject::create(runtime, optCachedHiddenClassHandle.getValue())
: JSObject::create(runtime, numLiterals));
MutableHandle<> tmpHandleKey(runtime);
MutableHandle<> tmpHandleVal(runtime);
auto &gcScope = *runtime->getTopGCScope();
auto marker = gcScope.createMarker();
auto genPair = curCodeBlock->getObjectBufferIter(
keyBufferIndex, valBufferIndex, numLiterals);
auto keyGen = genPair.first;
auto valGen = genPair.second;
if (optCachedHiddenClassHandle.hasValue()) {
uint32_t propIndex = 0;
// keyGen should always have the same amount of elements as valGen
while (valGen.hasNext()) {
#ifndef NDEBUG
{
// keyGen points to an element in the key buffer, which means it will
// only ever generate a Number or a Symbol. This means it will never
// allocate memory, and it is safe to not use a Handle.
SymbolID stringIdResult{};
auto key = keyGen.get(runtime);
if (key.isSymbol()) {
stringIdResult = ID(key.getSymbol().unsafeGetIndex());
} else {
tmpHandleKey = HermesValue::encodeDoubleValue(key.getNumber());
auto idRes = valueToSymbolID(runtime, tmpHandleKey);
assert(
idRes != ExecutionStatus::EXCEPTION &&
"valueToIdentifier() failed for uint32_t value");
stringIdResult = **idRes;
}
NamedPropertyDescriptor desc;
auto pos = HiddenClass::findProperty(
optCachedHiddenClassHandle.getValue(),
runtime,
stringIdResult,
PropertyFlags::defaultNewNamedPropertyFlags(),
desc);
assert(
pos &&
"Should find this property in cached hidden class property table.");
assert(
desc.slot == propIndex &&
"propIndex should be the same as recorded in hidden class table.");
}
#endif
// Explicitly make sure valGen.get() is called before obj.get() so that
// any allocation in valGen.get() won't invalidate the raw pointer
// retruned from obj.get().
auto val = valGen.get(runtime);
JSObject::setNamedSlotValue(obj.get(), runtime, propIndex, val);
gcScope.flushToMarker(marker);
++propIndex;
}
} else {
// keyGen should always have the same amount of elements as valGen
while (keyGen.hasNext()) {
// keyGen points to an element in the key buffer, which means it will
// only ever generate a Number or a Symbol. This means it will never
// allocate memory, and it is safe to not use a Handle.
auto key = keyGen.get(runtime);
tmpHandleVal = valGen.get(runtime);
if (key.isSymbol()) {
auto stringIdResult = ID(key.getSymbol().unsafeGetIndex());
if (LLVM_UNLIKELY(
JSObject::defineNewOwnProperty(
obj,
runtime,
stringIdResult,
PropertyFlags::defaultNewNamedPropertyFlags(),
tmpHandleVal) == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
} else {
tmpHandleKey = HermesValue::encodeDoubleValue(key.getNumber());
if (LLVM_UNLIKELY(
!JSObject::defineOwnComputedPrimitive(
obj,
runtime,
tmpHandleKey,
DefinePropertyFlags::getDefaultNewPropertyFlags(),
tmpHandleVal)
.getValue())) {
return ExecutionStatus::EXCEPTION;
}
}
gcScope.flushToMarker(marker);
}
}
tmpHandleKey.clear();
tmpHandleVal.clear();
// Hidden class in dictionary mode can't be shared.
HiddenClass *const clazz = obj->getClass(runtime);
if (!optCachedHiddenClassHandle.hasValue() && !clazz->isDictionary()) {
assert(
numLiterals == clazz->getNumProperties() &&
"numLiterals should match hidden class property count.");
assert(
clazz->getNumProperties() < 256 &&
"cached hidden class should have property count less than 256");
runtimeModule->tryCacheLiteralHiddenClass(runtime, keyBufferIndex, clazz);
}
return createPseudoHandle(HermesValue::encodeObjectValue(*obj));
}
CallResult<PseudoHandle<>> Interpreter::createArrayFromBuffer(
Runtime *runtime,
CodeBlock *curCodeBlock,
unsigned numElements,
unsigned numLiterals,
unsigned bufferIndex) {
// Create a new array using the built-in constructor, and initialize
// the elements from a literal array buffer.
auto arrRes = JSArray::create(runtime, numElements, numElements);
if (arrRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// Resize the array storage in advance.
auto arr = runtime->makeHandle(std::move(*arrRes));
JSArray::setStorageEndIndex(arr, runtime, numElements);
auto iter = curCodeBlock->getArrayBufferIter(bufferIndex, numLiterals);
JSArray::size_type i = 0;
while (iter.hasNext()) {
// NOTE: we must get the value in a separate step to guarantee ordering.
auto value = iter.get(runtime);
JSArray::unsafeSetExistingElementAt(*arr, runtime, i++, value);
}
return createPseudoHandle(HermesValue::encodeObjectValue(*arr));
}
#ifndef NDEBUG
namespace {
/// A tag used to instruct the output stream to dump more details about the
/// HermesValue, like the length of the string, etc.
struct DumpHermesValue {
const HermesValue hv;
DumpHermesValue(HermesValue hv) : hv(hv) {}
};
} // anonymous namespace.
static llvh::raw_ostream &operator<<(
llvh::raw_ostream &OS,
DumpHermesValue dhv) {
OS << dhv.hv;
// If it is a string, dump the contents, truncated to 8 characters.
if (dhv.hv.isString()) {
SmallU16String<32> str;
dhv.hv.getString()->appendUTF16String(str);
UTF16Ref ref = str.arrayRef();
if (str.size() <= 8) {
OS << ":'" << ref << "'";
} else {
OS << ":'" << ref.slice(0, 8) << "'";
OS << "...[" << str.size() << "]";
}
}
return OS;
}
/// Dump the arguments from a callee frame.
LLVM_ATTRIBUTE_UNUSED
static void dumpCallArguments(
llvh::raw_ostream &OS,
Runtime *runtime,
StackFramePtr calleeFrame) {
OS << "arguments:\n";
OS << " " << 0 << " " << DumpHermesValue(calleeFrame.getThisArgRef())
<< "\n";
for (unsigned i = 0; i < calleeFrame.getArgCount(); ++i) {
OS << " " << (i + 1) << " " << DumpHermesValue(calleeFrame.getArgRef(i))
<< "\n";
}
}
LLVM_ATTRIBUTE_UNUSED
static void printDebugInfo(
CodeBlock *curCodeBlock,
PinnedHermesValue *frameRegs,
const Inst *ip) {
// Check if LLVm debugging is enabled for us.
bool debug = false;
SLOW_DEBUG(debug = true);
if (!debug)
return;
DecodedInstruction decoded = decodeInstruction(ip);
dbgs() << llvh::format_decimal((const uint8_t *)ip - curCodeBlock->begin(), 4)
<< " OpCode::" << getOpCodeString(decoded.meta.opCode);
for (unsigned i = 0; i < decoded.meta.numOperands; ++i) {
auto operandType = decoded.meta.operandType[i];
auto value = decoded.operandValue[i];
dbgs() << (i == 0 ? " " : ", ");
dumpOperand(dbgs(), operandType, value);
if (operandType == OperandType::Reg8 || operandType == OperandType::Reg32) {
// Print the register value, if source.
if (i != 0 || decoded.meta.numOperands == 1)
dbgs() << "=" << DumpHermesValue(REG(value.integer));
}
}
dbgs() << "\n";
}
/// \return whether \p opcode is a call opcode (Call, CallDirect, Construct,
/// CallLongIndex, etc). Note CallBuiltin is not really a Call.
LLVM_ATTRIBUTE_UNUSED
static bool isCallType(OpCode opcode) {
switch (opcode) {
#define DEFINE_RET_TARGET(name) \
case OpCode::name: \
return true;
#include "hermes/BCGen/HBC/BytecodeList.def"
default:
return false;
}
}
#endif
/// \return the address of the next instruction after \p ip, which must be a
/// call-type instruction.
LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline const Inst *nextInstCall(const Inst *ip) {
HERMES_SLOW_ASSERT(isCallType(ip->opCode) && "ip is not of call type");
// The following is written to elicit compares instead of table lookup.
// The idea is to present code like so:
// if (opcode <= 70) return ip + 4;
// if (opcode <= 71) return ip + 4;
// if (opcode <= 72) return ip + 4;
// if (opcode <= 73) return ip + 5;
// if (opcode <= 74) return ip + 5;
// ...
// and the compiler will retain only compares where the result changes (here,
// 72 and 74). This allows us to compute the next instruction using three
// compares, instead of a naive compare-per-call type (or lookup table).
//
// Statically verify that increasing call opcodes correspond to monotone
// instruction sizes; this enables the compiler to do a better job optimizing.
constexpr bool callSizesMonotoneIncreasing = monotoneIncreasing(
#define DEFINE_RET_TARGET(name) sizeof(inst::name##Inst),
#include "hermes/BCGen/HBC/BytecodeList.def"
SIZE_MAX // sentinel avoiding a trailing comma.
);
static_assert(
callSizesMonotoneIncreasing,
"Call instruction sizes are not monotone increasing");
#define DEFINE_RET_TARGET(name) \
if (ip->opCode <= OpCode::name) \
return NEXTINST(name);
#include "hermes/BCGen/HBC/BytecodeList.def"
llvm_unreachable("Not a call type");
}
CallResult<HermesValue> Runtime::interpretFunctionImpl(
CodeBlock *newCodeBlock) {
newCodeBlock->lazyCompile(this);
#if defined(HERMES_ENABLE_ALLOCATION_LOCATION_TRACES) || !defined(NDEBUG)
// We always call getCurrentIP() in a debug build as this has the effect
// of asserting the IP is correctly set (not invalidated) at this point.
// This allows us to leverage our whole test-suite to find missing cases
// of CAPTURE_IP* macros in the interpreter loop.
const inst::Inst *ip = getCurrentIP();
(void)ip;
#endif
#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES
if (ip) {
const CodeBlock *codeBlock;
std::tie(codeBlock, ip) = getCurrentInterpreterLocation(ip);
// All functions end in a Ret so we must match this with a pushCallStack()
// before executing.
if (codeBlock) {
// Push a call entry at the last location we were executing bytecode.
// This will correctly attribute things like eval().
pushCallStack(codeBlock, ip);
} else {
// Push a call entry at the entry at the top of interpreted code.
pushCallStack(newCodeBlock, (const Inst *)newCodeBlock->begin());
}
} else {
// Push a call entry at the entry at the top of interpreted code.
pushCallStack(newCodeBlock, (const Inst *)newCodeBlock->begin());
}
#endif
InterpreterState state{newCodeBlock, 0};
return Interpreter::interpretFunction<false>(this, state);
}
CallResult<HermesValue> Runtime::interpretFunction(CodeBlock *newCodeBlock) {
#ifdef HERMESVM_PROFILER_EXTERN
auto id = getProfilerID(newCodeBlock);
if (id >= NUM_PROFILER_SYMBOLS) {
id = NUM_PROFILER_SYMBOLS - 1; // Overflow entry.
}
return interpWrappers[id](this, newCodeBlock);
#else
return interpretFunctionImpl(newCodeBlock);
#endif
}
#ifdef HERMES_ENABLE_DEBUGGER
ExecutionStatus Runtime::stepFunction(InterpreterState &state) {
return Interpreter::interpretFunction<true>(this, state).getStatus();
}
#endif
/// \return the quotient of x divided by y.
static double doDiv(double x, double y)
LLVM_NO_SANITIZE("float-divide-by-zero");
static inline double doDiv(double x, double y) {
// UBSan will complain about float divide by zero as our implementation
// of OpCode::Div depends on IEEE 754 float divide by zero. All modern
// compilers implement this and there is no trivial work-around without
// sacrificing performance and readability.
// NOTE: This was pulled out of the interpreter to avoid putting the sanitize
// silencer on the entire interpreter function.
return x / y;
}
/// \return the product of x multiplied by y.
static inline double doMult(double x, double y) {
return x * y;
}
/// \return the difference of y subtracted from x.
static inline double doSub(double x, double y) {
return x - y;
}
template <bool SingleStep>
CallResult<HermesValue> Interpreter::interpretFunction(
Runtime *runtime,
InterpreterState &state) {
// The interepter is re-entrant and also saves/restores its IP via the runtime
// whenever a call out is made (see the CAPTURE_IP_* macros). As such, failure
// to preserve the IP across calls to interpeterFunction() disrupt interpreter
// calls further up the C++ callstack. The RAII utility class below makes sure
// we always do this correctly.
//
// TODO: The IPs stored in the C++ callstack via this holder will generally be
// the same as in the JS stack frames via the Saved IP field. We can probably
// get rid of one of these redundant stores. Doing this isn't completely
// trivial as there are currently cases where we re-enter the interpreter
// without calling Runtime::saveCallerIPInStackFrame(), and there are features
// (I think mostly the debugger + stack traces) which implicitly rely on
// this behavior. At least their tests break if this behavior is not
// preserved.
struct IPSaver {
IPSaver(Runtime *runtime)
: ip_(runtime->getCurrentIP()), runtime_(runtime) {}
~IPSaver() {
runtime_->setCurrentIP(ip_);
}
private:
const Inst *ip_;
Runtime *runtime_;
};
IPSaver ipSaver(runtime);
#ifndef HERMES_ENABLE_DEBUGGER
static_assert(!SingleStep, "can't use single-step mode without the debugger");
#endif
// Make sure that the cache can use an optimization by avoiding a branch to
// access the property storage.
static_assert(
HiddenClass::kDictionaryThreshold <=
SegmentedArray::kValueToSegmentThreshold,
"Cannot avoid branches in cache check if the dictionary "
"crossover point is larger than the inline storage");
CodeBlock *curCodeBlock = state.codeBlock;
const Inst *ip = nullptr;
// Holds runtime->currentFrame_.ptr()-1 which is the first local
// register. This eliminates the indirect load from Runtime and the -1 offset.
PinnedHermesValue *frameRegs;
// Strictness of current function.
bool strictMode;
// Default flags when accessing properties.
PropOpFlags defaultPropOpFlags;
// These CAPTURE_IP* macros should wrap around any major calls out of the
// interpeter loop. They stash and retrieve the IP via the current Runtime
// allowing the IP to be externally observed and even altered to change the flow
// of execution. Explicitly saving AND restoring the IP from the Runtime in this
// way means the C++ compiler will keep IP in a register within the rest of the
// interpeter loop.
//
// When assertions are enabled we take the extra step of "invalidating" the IP
// between captures so we can detect if it's erroneously accessed.
//
// In some cases we explicitly don't want to invalidate the IP and instead want
// it to stay set. For this we use the *NO_INVALIDATE variants. This comes up
// when we're performing a call operation which may re-enter the interpeter
// loop, and so need the IP available for the saveCallerIPInStackFrame() call
// when we next enter.
#define CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr) \
runtime->setCurrentIP(ip); \
dst = expr; \
ip = runtime->getCurrentIP();
#ifdef NDEBUG
#define CAPTURE_IP(expr) \
runtime->setCurrentIP(ip); \
(void)expr; \
ip = runtime->getCurrentIP();
#define CAPTURE_IP_ASSIGN(dst, expr) CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr)
#else // !NDEBUG
#define CAPTURE_IP(expr) \
runtime->setCurrentIP(ip); \
(void)expr; \
ip = runtime->getCurrentIP(); \
runtime->invalidateCurrentIP();
#define CAPTURE_IP_ASSIGN(dst, expr) \
runtime->setCurrentIP(ip); \
dst = expr; \
ip = runtime->getCurrentIP(); \
runtime->invalidateCurrentIP();
#endif // NDEBUG
LLVM_DEBUG(dbgs() << "interpretFunction() called\n");
ScopedNativeDepthTracker depthTracker{runtime};
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
if (!SingleStep) {
if (auto jitPtr = runtime->jitContext_.compile(runtime, curCodeBlock)) {
return (*jitPtr)(runtime);
}
}
GCScope gcScope(runtime);
// Avoid allocating a handle dynamically by reusing this one.
MutableHandle<> tmpHandle(runtime);
CallResult<HermesValue> res{ExecutionStatus::EXCEPTION};
CallResult<PseudoHandle<>> resPH{ExecutionStatus::EXCEPTION};
CallResult<Handle<Arguments>> resArgs{ExecutionStatus::EXCEPTION};
CallResult<bool> boolRes{ExecutionStatus::EXCEPTION};
// Mark the gcScope so we can clear all allocated handles.
// Remember how many handles the scope has so we can clear them in the loop.
static constexpr unsigned KEEP_HANDLES = 1;
assert(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"scope has unexpected number of handles");
INIT_OPCODE_PROFILER;
#if !defined(HERMESVM_PROFILER_EXTERN)
tailCall:
#endif
PROFILER_ENTER_FUNCTION(curCodeBlock);
#ifdef HERMES_ENABLE_DEBUGGER
runtime->getDebugger().willEnterCodeBlock(curCodeBlock);
#endif
runtime->getCodeCoverageProfiler().markExecuted(runtime, curCodeBlock);
// Update function executionCount_ count
curCodeBlock->incrementExecutionCount();
if (!SingleStep) {
auto newFrame = runtime->setCurrentFrameToTopOfStack();
runtime->saveCallerIPInStackFrame();
#ifndef NDEBUG
runtime->invalidateCurrentIP();
#endif
// Point frameRegs to the first register in the new frame. Note that at this
// moment technically it points above the top of the stack, but we are never
// going to access it.
frameRegs = &newFrame.getFirstLocalRef();
#ifndef NDEBUG
LLVM_DEBUG(
dbgs() << "function entry: stackLevel=" << runtime->getStackLevel()
<< ", argCount=" << runtime->getCurrentFrame().getArgCount()
<< ", frameSize=" << curCodeBlock->getFrameSize() << "\n");
LLVM_DEBUG(
dbgs() << " callee "
<< DumpHermesValue(
runtime->getCurrentFrame().getCalleeClosureOrCBRef())
<< "\n");
LLVM_DEBUG(
dbgs() << " this "
<< DumpHermesValue(runtime->getCurrentFrame().getThisArgRef())
<< "\n");
for (uint32_t i = 0; i != runtime->getCurrentFrame()->getArgCount(); ++i) {
LLVM_DEBUG(
dbgs() << " " << llvh::format_decimal(i, 4) << " "
<< DumpHermesValue(runtime->getCurrentFrame().getArgRef(i))
<< "\n");
}
#endif
// Allocate the registers for the new frame.
if (LLVM_UNLIKELY(!runtime->checkAndAllocStack(
curCodeBlock->getFrameSize() +
StackFrameLayout::CalleeExtraRegistersAtStart,
HermesValue::encodeUndefinedValue())))
goto stackOverflow;
ip = (Inst const *)curCodeBlock->begin();
// Check for invalid invocation.
if (LLVM_UNLIKELY(curCodeBlock->getHeaderFlags().isCallProhibited(
newFrame.isConstructorCall()))) {
if (!newFrame.isConstructorCall()) {
CAPTURE_IP(
runtime->raiseTypeError("Class constructor invoked without new"));
} else {
CAPTURE_IP(runtime->raiseTypeError("Function is not a constructor"));
}
goto handleExceptionInParent;
}
} else {
// Point frameRegs to the first register in the frame.
frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();
ip = (Inst const *)(curCodeBlock->begin() + state.offset);
}
assert((const uint8_t *)ip < curCodeBlock->end() && "CodeBlock is empty");
INIT_STATE_FOR_CODEBLOCK(curCodeBlock);
#define BEFORE_OP_CODE \
{ \
UPDATE_OPCODE_TIME_SPENT; \
HERMES_SLOW_ASSERT( \
curCodeBlock->contains(ip) && "curCodeBlock must contain ip"); \
HERMES_SLOW_ASSERT((printDebugInfo(curCodeBlock, frameRegs, ip), true)); \
HERMES_SLOW_ASSERT( \
gcScope.getHandleCountDbg() == KEEP_HANDLES && \
"unaccounted handles were created"); \
HERMES_SLOW_ASSERT(tmpHandle->isUndefined() && "tmpHandle not cleared"); \
RECORD_OPCODE_START_TIME; \
INC_OPCODE_COUNT; \
}
#ifdef HERMESVM_INDIRECT_THREADING
static void *opcodeDispatch[] = {
#define DEFINE_OPCODE(name) &&case_##name,
#include "hermes/BCGen/HBC/BytecodeList.def"
&&case__last};
#define CASE(name) case_##name:
#define DISPATCH \
BEFORE_OP_CODE; \
if (SingleStep) { \
state.codeBlock = curCodeBlock; \
state.offset = CUROFFSET; \
return HermesValue::encodeUndefinedValue(); \
} \
goto *opcodeDispatch[(unsigned)ip->opCode]
#else // HERMESVM_INDIRECT_THREADING
#define CASE(name) case OpCode::name:
#define DISPATCH \
if (SingleStep) { \
state.codeBlock = curCodeBlock; \
state.offset = CUROFFSET; \
return HermesValue::encodeUndefinedValue(); \
} \
continue
#endif // HERMESVM_INDIRECT_THREADING
#define RUN_DEBUGGER_ASYNC_BREAK(flags) \
do { \
CAPTURE_IP_ASSIGN( \
auto dRes, \
runDebuggerUpdatingState( \
(uint8_t)(flags) & \
(uint8_t)Runtime::AsyncBreakReasonBits::DebuggerExplicit \
? Debugger::RunReason::AsyncBreakExplicit \
: Debugger::RunReason::AsyncBreakImplicit, \
runtime, \
curCodeBlock, \
ip, \
frameRegs)); \
if (dRes == ExecutionStatus::EXCEPTION) \
goto exception; \
} while (0)
for (;;) {
BEFORE_OP_CODE;
#ifdef HERMESVM_INDIRECT_THREADING
goto *opcodeDispatch[(unsigned)ip->opCode];
#else
switch (ip->opCode)
#endif
{
const Inst *nextIP;
uint32_t idVal;
bool tryProp;
uint32_t callArgCount;
// This is HermesValue::getRaw(), since HermesValue cannot be assigned
// to. It is meant to be used only for very short durations, in the
// dispatch of call instructions, when there is definitely no possibility
// of a GC.
HermesValue::RawType callNewTarget;
/// Handle an opcode \p name with an out-of-line implementation in a function
/// ExecutionStatus caseName(
/// Runtime *,
/// PinnedHermesValue *frameRegs,
/// Inst *ip)
#define CASE_OUTOFLINE(name) \
CASE(name) { \
CAPTURE_IP_ASSIGN(auto res, case##name(runtime, frameRegs, ip)); \
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { \
goto exception; \
} \
gcScope.flushToSmallCount(KEEP_HANDLES); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a binary arithmetic instruction with a fast path where both
/// operands are numbers.
/// \param name the name of the instruction. The fast path case will have a
/// "n" appended to the name.
/// \param oper the C++ operator to use to actually perform the arithmetic
/// operation.
#define BINOP(name, oper) \
CASE(name) { \
if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \
/* Fast-path. */ \
CASE(name##N) { \
O1REG(name) = HermesValue::encodeDoubleValue( \
oper(O2REG(name).getNumber(), O3REG(name).getNumber())); \
ip = NEXTINST(name); \
DISPATCH; \
} \
} \
CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) \
goto exception; \
double left = res->getDouble(); \
CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) \
goto exception; \
O1REG(name) = \
HermesValue::encodeDoubleValue(oper(left, res->getDouble())); \
gcScope.flushToSmallCount(KEEP_HANDLES); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a shift instruction with a fast path where both
/// operands are numbers.
/// \param name the name of the instruction.
/// \param oper the C++ operator to use to actually perform the shift
/// operation.
/// \param lConv the conversion function for the LHS of the expression.
/// \param lType the type of the LHS operand.
/// \param returnType the type of the return value.
#define SHIFTOP(name, oper, lConv, lType, returnType) \
CASE(name) { \
if (LLVM_LIKELY( \
O2REG(name).isNumber() && \
O3REG(name).isNumber())) { /* Fast-path. */ \
auto lnum = static_cast<lType>( \
hermes::truncateToInt32(O2REG(name).getNumber())); \
auto rnum = static_cast<uint32_t>( \
hermes::truncateToInt32(O3REG(name).getNumber())) & \
0x1f; \
O1REG(name) = HermesValue::encodeDoubleValue( \
static_cast<returnType>(lnum oper rnum)); \
ip = NEXTINST(name); \
DISPATCH; \
} \
CAPTURE_IP_ASSIGN(res, lConv(runtime, Handle<>(&O2REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
auto lnum = static_cast<lType>(res->getNumber()); \
CAPTURE_IP_ASSIGN(res, toUInt32_RJS(runtime, Handle<>(&O3REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
auto rnum = static_cast<uint32_t>(res->getNumber()) & 0x1f; \
gcScope.flushToSmallCount(KEEP_HANDLES); \
O1REG(name) = HermesValue::encodeDoubleValue( \
static_cast<returnType>(lnum oper rnum)); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a binary bitwise instruction with a fast path where both
/// operands are numbers.
/// \param name the name of the instruction.
/// \param oper the C++ operator to use to actually perform the bitwise
/// operation.
#define BITWISEBINOP(name, oper) \
CASE(name) { \
if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \
/* Fast-path. */ \
O1REG(name) = HermesValue::encodeDoubleValue( \
hermes::truncateToInt32(O2REG(name).getNumber()) \
oper hermes::truncateToInt32(O3REG(name).getNumber())); \
ip = NEXTINST(name); \
DISPATCH; \
} \
CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
int32_t left = res->getNumberAs<int32_t>(); \
CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O3REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
O1REG(name) = \
HermesValue::encodeNumberValue(left oper res->getNumberAs<int32_t>()); \
gcScope.flushToSmallCount(KEEP_HANDLES); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a comparison instruction.
/// \param name the name of the instruction.
/// \param oper the C++ operator to use to actually perform the fast arithmetic
/// comparison.
/// \param operFuncName function to call for the slow-path comparison.
#define CONDOP(name, oper, operFuncName) \
CASE(name) { \
if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \
/* Fast-path. */ \
O1REG(name) = HermesValue::encodeBoolValue( \
O2REG(name).getNumber() oper O3REG(name).getNumber()); \
ip = NEXTINST(name); \
DISPATCH; \
} \
CAPTURE_IP_ASSIGN( \
boolRes, \
operFuncName( \
runtime, Handle<>(&O2REG(name)), Handle<>(&O3REG(name)))); \
if (boolRes == ExecutionStatus::EXCEPTION) \
goto exception; \
gcScope.flushToSmallCount(KEEP_HANDLES); \
O1REG(name) = HermesValue::encodeBoolValue(boolRes.getValue()); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a comparison conditional jump with a fast path where both
/// operands are numbers.
/// \param name the name of the instruction. The fast path case will have a
/// "N" appended to the name.
/// \param suffix Optional suffix to be added to the end (e.g. Long)
/// \param oper the C++ operator to use to actually perform the fast arithmetic
/// comparison.
/// \param operFuncName function to call for the slow-path comparison.
/// \param trueDest ip value if the conditional evaluates to true
/// \param falseDest ip value if the conditional evaluates to false
#define JCOND_IMPL(name, suffix, oper, operFuncName, trueDest, falseDest) \
CASE(name##suffix) { \
if (LLVM_LIKELY( \
O2REG(name##suffix).isNumber() && \
O3REG(name##suffix).isNumber())) { \
/* Fast-path. */ \
CASE(name##N##suffix) { \
if (O2REG(name##N##suffix) \
.getNumber() oper O3REG(name##N##suffix) \
.getNumber()) { \
ip = trueDest; \
DISPATCH; \
} \
ip = falseDest; \
DISPATCH; \
} \
} \
CAPTURE_IP_ASSIGN( \
boolRes, \
operFuncName( \
runtime, \
Handle<>(&O2REG(name##suffix)), \
Handle<>(&O3REG(name##suffix)))); \
if (boolRes == ExecutionStatus::EXCEPTION) \
goto exception; \
gcScope.flushToSmallCount(KEEP_HANDLES); \
if (boolRes.getValue()) { \
ip = trueDest; \
DISPATCH; \
} \
ip = falseDest; \
DISPATCH; \
}
/// Implement a strict equality conditional jump
/// \param name the name of the instruction.
/// \param suffix Optional suffix to be added to the end (e.g. Long)
/// \param trueDest ip value if the conditional evaluates to true
/// \param falseDest ip value if the conditional evaluates to false
#define JCOND_STRICT_EQ_IMPL(name, suffix, trueDest, falseDest) \
CASE(name##suffix) { \
if (strictEqualityTest(O2REG(name##suffix), O3REG(name##suffix))) { \
ip = trueDest; \
DISPATCH; \
} \
ip = falseDest; \
DISPATCH; \
}
/// Implement an equality conditional jump
/// \param name the name of the instruction.
/// \param suffix Optional suffix to be added to the end (e.g. Long)
/// \param trueDest ip value if the conditional evaluates to true
/// \param falseDest ip value if the conditional evaluates to false
#define JCOND_EQ_IMPL(name, suffix, trueDest, falseDest) \
CASE(name##suffix) { \
CAPTURE_IP_ASSIGN( \
res, \
abstractEqualityTest_RJS( \
runtime, \
Handle<>(&O2REG(name##suffix)), \
Handle<>(&O3REG(name##suffix)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
gcScope.flushToSmallCount(KEEP_HANDLES); \
if (res->getBool()) { \
ip = trueDest; \
DISPATCH; \
} \
ip = falseDest; \
DISPATCH; \
}
/// Implement the long and short forms of a conditional jump, and its negation.
#define JCOND(name, oper, operFuncName) \
JCOND_IMPL( \
J##name, \
, \
oper, \
operFuncName, \
IPADD(ip->iJ##name.op1), \
NEXTINST(J##name)); \
JCOND_IMPL( \
J##name, \
Long, \
oper, \
operFuncName, \
IPADD(ip->iJ##name##Long.op1), \
NEXTINST(J##name##Long)); \
JCOND_IMPL( \
JNot##name, \
, \
oper, \
operFuncName, \
NEXTINST(JNot##name), \
IPADD(ip->iJNot##name.op1)); \
JCOND_IMPL( \
JNot##name, \
Long, \
oper, \
operFuncName, \
NEXTINST(JNot##name##Long), \
IPADD(ip->iJNot##name##Long.op1));
/// Load a constant.
/// \param value is the value to store in the output register.
#define LOAD_CONST(name, value) \
CASE(name) { \
O1REG(name) = value; \
ip = NEXTINST(name); \
DISPATCH; \
}
#define LOAD_CONST_CAPTURE_IP(name, value) \
CASE(name) { \
CAPTURE_IP_ASSIGN(O1REG(name), value); \
ip = NEXTINST(name); \
DISPATCH; \
}
CASE(Mov) {
O1REG(Mov) = O2REG(Mov);
ip = NEXTINST(Mov);
DISPATCH;
}
CASE(MovLong) {
O1REG(MovLong) = O2REG(MovLong);
ip = NEXTINST(MovLong);
DISPATCH;
}
CASE(LoadParam) {
if (LLVM_LIKELY(ip->iLoadParam.op2 <= FRAME.getArgCount())) {
// index 0 must load 'this'. Index 1 the first argument, etc.
O1REG(LoadParam) = FRAME.getArgRef((int32_t)ip->iLoadParam.op2 - 1);
ip = NEXTINST(LoadParam);
DISPATCH;
}
O1REG(LoadParam) = HermesValue::encodeUndefinedValue();
ip = NEXTINST(LoadParam);
DISPATCH;
}
CASE(LoadParamLong) {
if (LLVM_LIKELY(ip->iLoadParamLong.op2 <= FRAME.getArgCount())) {
// index 0 must load 'this'. Index 1 the first argument, etc.
O1REG(LoadParamLong) =
FRAME.getArgRef((int32_t)ip->iLoadParamLong.op2 - 1);
ip = NEXTINST(LoadParamLong);
DISPATCH;
}
O1REG(LoadParamLong) = HermesValue::encodeUndefinedValue();
ip = NEXTINST(LoadParamLong);
DISPATCH;
}
CASE(CoerceThisNS) {
if (LLVM_LIKELY(O2REG(CoerceThisNS).isObject())) {
O1REG(CoerceThisNS) = O2REG(CoerceThisNS);
} else if (
O2REG(CoerceThisNS).isNull() || O2REG(CoerceThisNS).isUndefined()) {
O1REG(CoerceThisNS) = runtime->global_;
} else {
tmpHandle = O2REG(CoerceThisNS);
nextIP = NEXTINST(CoerceThisNS);
goto coerceThisSlowPath;
}
ip = NEXTINST(CoerceThisNS);
DISPATCH;
}
CASE(LoadThisNS) {
if (LLVM_LIKELY(FRAME.getThisArgRef().isObject())) {
O1REG(LoadThisNS) = FRAME.getThisArgRef();
} else if (
FRAME.getThisArgRef().isNull() ||
FRAME.getThisArgRef().isUndefined()) {
O1REG(LoadThisNS) = runtime->global_;
} else {
tmpHandle = FRAME.getThisArgRef();
nextIP = NEXTINST(LoadThisNS);
goto coerceThisSlowPath;
}
ip = NEXTINST(LoadThisNS);
DISPATCH;
}
coerceThisSlowPath : {
CAPTURE_IP_ASSIGN(res, toObject(runtime, tmpHandle));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CoerceThisNS) = res.getValue();
tmpHandle.clear();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(ConstructLong) {
callArgCount = (uint32_t)ip->iConstructLong.op3;
nextIP = NEXTINST(ConstructLong);
callNewTarget = O2REG(ConstructLong).getRaw();
goto doCall;
}
CASE(CallLong) {
callArgCount = (uint32_t)ip->iCallLong.op3;
nextIP = NEXTINST(CallLong);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
// Note in Call1 through Call4, the first argument is 'this' which has
// argument index -1.
// Also note that we are writing to callNewTarget last, to avoid the
// possibility of it being aliased by the arg writes.
CASE(Call1) {
callArgCount = 1;
nextIP = NEXTINST(Call1);
StackFramePtr fr{runtime->stackPointer_};
fr.getArgRefUnsafe(-1) = O3REG(Call1);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
CASE(Call2) {
callArgCount = 2;
nextIP = NEXTINST(Call2);
StackFramePtr fr{runtime->stackPointer_};
fr.getArgRefUnsafe(-1) = O3REG(Call2);
fr.getArgRefUnsafe(0) = O4REG(Call2);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
CASE(Call3) {
callArgCount = 3;
nextIP = NEXTINST(Call3);
StackFramePtr fr{runtime->stackPointer_};
fr.getArgRefUnsafe(-1) = O3REG(Call3);
fr.getArgRefUnsafe(0) = O4REG(Call3);
fr.getArgRefUnsafe(1) = O5REG(Call3);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
CASE(Call4) {
callArgCount = 4;
nextIP = NEXTINST(Call4);
StackFramePtr fr{runtime->stackPointer_};
fr.getArgRefUnsafe(-1) = O3REG(Call4);
fr.getArgRefUnsafe(0) = O4REG(Call4);
fr.getArgRefUnsafe(1) = O5REG(Call4);
fr.getArgRefUnsafe(2) = O6REG(Call4);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
CASE(Construct) {
callArgCount = (uint32_t)ip->iConstruct.op3;
nextIP = NEXTINST(Construct);
callNewTarget = O2REG(Construct).getRaw();
goto doCall;
}
CASE(Call) {
callArgCount = (uint32_t)ip->iCall.op3;
nextIP = NEXTINST(Call);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
// Fall through.
}
doCall : {
#ifdef HERMES_ENABLE_DEBUGGER
// Check for an async debugger request.
if (uint8_t asyncFlags =
runtime->testAndClearDebuggerAsyncBreakRequest()) {
RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);
gcScope.flushToSmallCount(KEEP_HANDLES);
DISPATCH;
}
#endif
// Subtract 1 from callArgCount as 'this' is considered an argument in the
// instruction, but not in the frame.
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
auto newFrame,
StackFramePtr::initFrame(
runtime->stackPointer_,
FRAME,
ip,
curCodeBlock,
callArgCount - 1,
O2REG(Call),
HermesValue::fromRaw(callNewTarget)));
(void)newFrame;
SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));
if (auto *func = dyn_vmcast<JSFunction>(O2REG(Call))) {
assert(!SingleStep && "can't single-step a call");
#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES
runtime->pushCallStack(curCodeBlock, ip);
#endif
CodeBlock *calleeBlock = func->getCodeBlock();
calleeBlock->lazyCompile(runtime);
#if defined(HERMESVM_PROFILER_EXTERN)
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
res, runtime->interpretFunction(calleeBlock));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(Call) = *res;
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
#else
if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {
res = (*jitPtr)(runtime);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
goto exception;
O1REG(Call) = *res;
SLOW_DEBUG(
dbgs() << "JIT return value r" << (unsigned)ip->iCall.op1 << "="
<< DumpHermesValue(O1REG(Call)) << "\n");
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
curCodeBlock = calleeBlock;
goto tailCall;
#endif
}
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
resPH, Interpreter::handleCallSlowPath(runtime, &O2REG(Call)));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(Call) = std::move(resPH->get());
SLOW_DEBUG(
dbgs() << "native return value r" << (unsigned)ip->iCall.op1 << "="
<< DumpHermesValue(O1REG(Call)) << "\n");
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(CallDirect)
CASE(CallDirectLongIndex) {
#ifdef HERMES_ENABLE_DEBUGGER
// Check for an async debugger request.
if (uint8_t asyncFlags =
runtime->testAndClearDebuggerAsyncBreakRequest()) {
RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);
gcScope.flushToSmallCount(KEEP_HANDLES);
DISPATCH;
}
#endif
CAPTURE_IP_ASSIGN(
CodeBlock * calleeBlock,
ip->opCode == OpCode::CallDirect
? curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(
ip->iCallDirect.op3)
: curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(
ip->iCallDirectLongIndex.op3));
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
auto newFrame,
StackFramePtr::initFrame(
runtime->stackPointer_,
FRAME,
ip,
curCodeBlock,
(uint32_t)ip->iCallDirect.op2 - 1,
HermesValue::encodeNativePointer(calleeBlock),
HermesValue::encodeUndefinedValue()));
(void)newFrame;
LLVM_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));
assert(!SingleStep && "can't single-step a call");
calleeBlock->lazyCompile(runtime);
#if defined(HERMESVM_PROFILER_EXTERN)
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
res, runtime->interpretFunction(calleeBlock));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CallDirect) = *res;
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)
: NEXTINST(CallDirectLongIndex);
DISPATCH;
#else
if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {
res = (*jitPtr)(runtime);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
goto exception;
O1REG(CallDirect) = *res;
LLVM_DEBUG(
dbgs() << "JIT return value r" << (unsigned)ip->iCallDirect.op1
<< "=" << DumpHermesValue(O1REG(Call)) << "\n");
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)
: NEXTINST(CallDirectLongIndex);
DISPATCH;
}
curCodeBlock = calleeBlock;
goto tailCall;
#endif
}
CASE(CallBuiltin) {
NativeFunction *nf =
runtime->getBuiltinNativeFunction(ip->iCallBuiltin.op2);
CAPTURE_IP_ASSIGN(
auto newFrame,
StackFramePtr::initFrame(
runtime->stackPointer_,
FRAME,
ip,
curCodeBlock,
(uint32_t)ip->iCallBuiltin.op3 - 1,
nf,
false));
// "thisArg" is implicitly assumed to "undefined".
newFrame.getThisArgRef() = HermesValue::encodeUndefinedValue();
SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));
CAPTURE_IP_ASSIGN(resPH, NativeFunction::_nativeCall(nf, runtime));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION))
goto exception;
O1REG(CallBuiltin) = std::move(resPH->get());
SLOW_DEBUG(
dbgs() << "native return value r" << (unsigned)ip->iCallBuiltin.op1
<< "=" << DumpHermesValue(O1REG(CallBuiltin)) << "\n");
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CallBuiltin);
DISPATCH;
}
CASE(CompleteGenerator) {
auto *innerFn = vmcast<GeneratorInnerFunction>(
runtime->getCurrentFrame().getCalleeClosure());
innerFn->setState(GeneratorInnerFunction::State::Completed);
ip = NEXTINST(CompleteGenerator);
DISPATCH;
}
CASE(SaveGenerator) {
nextIP = IPADD(ip->iSaveGenerator.op1);
goto doSaveGen;
}
CASE(SaveGeneratorLong) {
nextIP = IPADD(ip->iSaveGeneratorLong.op1);
goto doSaveGen;
}
doSaveGen : {
auto *innerFn = vmcast<GeneratorInnerFunction>(
runtime->getCurrentFrame().getCalleeClosure());
innerFn->saveStack(runtime);
innerFn->setNextIP(nextIP);
innerFn->setState(GeneratorInnerFunction::State::SuspendedYield);
ip = NEXTINST(SaveGenerator);
DISPATCH;
}
CASE(StartGenerator) {
auto *innerFn = vmcast<GeneratorInnerFunction>(
runtime->getCurrentFrame().getCalleeClosure());
if (innerFn->getState() ==
GeneratorInnerFunction::State::SuspendedStart) {
nextIP = NEXTINST(StartGenerator);
} else {
nextIP = innerFn->getNextIP();
innerFn->restoreStack(runtime);
}
innerFn->setState(GeneratorInnerFunction::State::Executing);
ip = nextIP;
DISPATCH;
}
CASE(ResumeGenerator) {
auto *innerFn = vmcast<GeneratorInnerFunction>(
runtime->getCurrentFrame().getCalleeClosure());
O1REG(ResumeGenerator) = innerFn->getResult();
O2REG(ResumeGenerator) = HermesValue::encodeBoolValue(
innerFn->getAction() == GeneratorInnerFunction::Action::Return);
innerFn->clearResult(runtime);
if (innerFn->getAction() == GeneratorInnerFunction::Action::Throw) {
runtime->setThrownValue(O1REG(ResumeGenerator));
goto exception;
}
ip = NEXTINST(ResumeGenerator);
DISPATCH;
}
CASE(Ret) {
#ifdef HERMES_ENABLE_DEBUGGER
// Check for an async debugger request.
if (uint8_t asyncFlags =
runtime->testAndClearDebuggerAsyncBreakRequest()) {
RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);
gcScope.flushToSmallCount(KEEP_HANDLES);
DISPATCH;
}
#endif
PROFILER_EXIT_FUNCTION(curCodeBlock);
#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES
runtime->popCallStack();
#endif
// Store the return value.
res = O1REG(Ret);
ip = FRAME.getSavedIP();
curCodeBlock = FRAME.getSavedCodeBlock();
frameRegs =
&runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();
SLOW_DEBUG(
dbgs() << "function exit: restored stackLevel="
<< runtime->getStackLevel() << "\n");
// Are we returning to native code?
if (!curCodeBlock) {
SLOW_DEBUG(dbgs() << "function exit: returning to native code\n");
return res;
}
// Return because of recursive calling structure
#if defined(HERMESVM_PROFILER_EXTERN)
return res;
#endif
INIT_STATE_FOR_CODEBLOCK(curCodeBlock);
O1REG(Call) = res.getValue();
ip = nextInstCall(ip);
DISPATCH;
}
CASE(Catch) {
assert(!runtime->thrownValue_.isEmpty() && "Invalid thrown value");
assert(
!isUncatchableError(runtime->thrownValue_) &&
"Uncatchable thrown value was caught");
O1REG(Catch) = runtime->thrownValue_;
runtime->clearThrownValue();
#ifdef HERMES_ENABLE_DEBUGGER
// Signal to the debugger that we're done unwinding an exception,
// and we can resume normal debugging flow.
runtime->debugger_.finishedUnwindingException();
#endif
ip = NEXTINST(Catch);
DISPATCH;
}
CASE(Throw) {
runtime->thrownValue_ = O1REG(Throw);
SLOW_DEBUG(
dbgs() << "Exception thrown: "
<< DumpHermesValue(runtime->thrownValue_) << "\n");
goto exception;
}
CASE(ThrowIfUndefinedInst) {
if (LLVM_UNLIKELY(O1REG(ThrowIfUndefinedInst).isUndefined())) {
SLOW_DEBUG(
dbgs() << "Throwing ReferenceError for undefined variable");
CAPTURE_IP(runtime->raiseReferenceError(
"accessing an uninitialized variable"));
goto exception;
}
ip = NEXTINST(ThrowIfUndefinedInst);
DISPATCH;
}
CASE(Debugger) {
SLOW_DEBUG(dbgs() << "debugger statement executed\n");
#ifdef HERMES_ENABLE_DEBUGGER
{
if (!runtime->debugger_.isDebugging()) {
// Only run the debugger if we're not already debugging.
// Don't want to call it again and mess with its state.
CAPTURE_IP_ASSIGN(
auto res,
runDebuggerUpdatingState(
Debugger::RunReason::Opcode,
runtime,
curCodeBlock,
ip,
frameRegs));
if (res == ExecutionStatus::EXCEPTION) {
// If one of the internal steps threw,
// then handle that here by jumping to where we're supposed to go.
// If we're in mid-step, the breakpoint at the catch point
// will have been set by the debugger.
// We don't want to execute this instruction because it's already
// thrown.
goto exception;
}
}
auto breakpointOpt = runtime->debugger_.getBreakpointLocation(ip);
if (breakpointOpt.hasValue()) {
// We're on a breakpoint but we're supposed to continue.
curCodeBlock->uninstallBreakpointAtOffset(
CUROFFSET, breakpointOpt->opCode);
if (ip->opCode == OpCode::Debugger) {
// Breakpointed a debugger instruction, so move past it
// since we've already called the debugger on this instruction.
ip = NEXTINST(Debugger);
} else {
InterpreterState newState{curCodeBlock, (uint32_t)CUROFFSET};
CAPTURE_IP_ASSIGN(
ExecutionStatus status, runtime->stepFunction(newState));
curCodeBlock->installBreakpointAtOffset(CUROFFSET);
if (status == ExecutionStatus::EXCEPTION) {
goto exception;
}
curCodeBlock = newState.codeBlock;
ip = newState.codeBlock->getOffsetPtr(newState.offset);
INIT_STATE_FOR_CODEBLOCK(curCodeBlock);
// Single-stepping should handle call stack management for us.
frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();
}
} else if (ip->opCode == OpCode::Debugger) {
// No breakpoint here and we've already run the debugger,
// just continue on.
// If the current instruction is no longer a debugger instruction,
// we're just going to keep executing from the current IP.
ip = NEXTINST(Debugger);
}
gcScope.flushToSmallCount(KEEP_HANDLES);
}
DISPATCH;
#else
ip = NEXTINST(Debugger);
DISPATCH;
#endif
}
CASE(AsyncBreakCheck) {
if (LLVM_UNLIKELY(runtime->hasAsyncBreak())) {
#ifdef HERMES_ENABLE_DEBUGGER
if (uint8_t asyncFlags =
runtime->testAndClearDebuggerAsyncBreakRequest()) {
RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);
}
#endif
if (runtime->testAndClearTimeoutAsyncBreakRequest()) {
CAPTURE_IP_ASSIGN(auto nRes, runtime->notifyTimeout());
if (nRes == ExecutionStatus::EXCEPTION) {
goto exception;
}
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(AsyncBreakCheck);
DISPATCH;
}
CASE(ProfilePoint) {
#ifdef HERMESVM_PROFILER_BB
auto pointIndex = ip->iProfilePoint.op1;
SLOW_DEBUG(llvh::dbgs() << "ProfilePoint: " << pointIndex << "\n");
CAPTURE_IP(runtime->getBasicBlockExecutionInfo().executeBlock(
curCodeBlock, pointIndex));
#endif
ip = NEXTINST(ProfilePoint);
DISPATCH;
}
CASE(Unreachable) {
llvm_unreachable("Hermes bug: unreachable instruction");
}
CASE(CreateClosure) {
idVal = ip->iCreateClosure.op3;
nextIP = NEXTINST(CreateClosure);
goto createClosure;
}
CASE(CreateClosureLongIndex) {
idVal = ip->iCreateClosureLongIndex.op3;
nextIP = NEXTINST(CreateClosureLongIndex);
goto createClosure;
}
createClosure : {
auto *runtimeModule = curCodeBlock->getRuntimeModule();
CAPTURE_IP_ASSIGN(
O1REG(CreateClosure),
JSFunction::create(
runtime,
runtimeModule->getDomain(runtime),
Handle<JSObject>::vmcast(&runtime->functionPrototype),
Handle<Environment>::vmcast(&O2REG(CreateClosure)),
runtimeModule->getCodeBlockMayAllocate(idVal))
.getHermesValue());
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(CreateGeneratorClosure) {
CAPTURE_IP_ASSIGN(
auto res,
createGeneratorClosure(
runtime,
curCodeBlock->getRuntimeModule(),
ip->iCreateClosure.op3,
Handle<Environment>::vmcast(&O2REG(CreateGeneratorClosure))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CreateGeneratorClosure) = res->getHermesValue();
res->invalidate();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateGeneratorClosure);
DISPATCH;
}
CASE(CreateGeneratorClosureLongIndex) {
CAPTURE_IP_ASSIGN(
auto res,
createGeneratorClosure(
runtime,
curCodeBlock->getRuntimeModule(),
ip->iCreateClosureLongIndex.op3,
Handle<Environment>::vmcast(
&O2REG(CreateGeneratorClosureLongIndex))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CreateGeneratorClosureLongIndex) = res->getHermesValue();
res->invalidate();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateGeneratorClosureLongIndex);
DISPATCH;
}
CASE(CreateGenerator) {
CAPTURE_IP_ASSIGN(
auto res,
createGenerator_RJS(
runtime,
curCodeBlock->getRuntimeModule(),
ip->iCreateGenerator.op3,
Handle<Environment>::vmcast(&O2REG(CreateGenerator)),
FRAME.getNativeArgs()));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CreateGenerator) = res->getHermesValue();
res->invalidate();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateGenerator);
DISPATCH;
}
CASE(CreateGeneratorLongIndex) {
CAPTURE_IP_ASSIGN(
auto res,
createGenerator_RJS(
runtime,
curCodeBlock->getRuntimeModule(),
ip->iCreateGeneratorLongIndex.op3,
Handle<Environment>::vmcast(&O2REG(CreateGeneratorLongIndex)),
FRAME.getNativeArgs()));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CreateGeneratorLongIndex) = res->getHermesValue();
res->invalidate();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateGeneratorLongIndex);
DISPATCH;
}
CASE(GetEnvironment) {
// The currently executing function must exist, so get the environment.
Environment *curEnv =
FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime);
for (unsigned level = ip->iGetEnvironment.op2; level; --level) {
assert(curEnv && "invalid environment relative level");
curEnv = curEnv->getParentEnvironment(runtime);
}
O1REG(GetEnvironment) = HermesValue::encodeObjectValue(curEnv);
ip = NEXTINST(GetEnvironment);
DISPATCH;
}
CASE(CreateEnvironment) {
tmpHandle = HermesValue::encodeObjectValue(
FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime));
CAPTURE_IP_ASSIGN(
res,
Environment::create(
runtime,
tmpHandle->getPointer() ? Handle<Environment>::vmcast(tmpHandle)
: Handle<Environment>::vmcast_or_null(
&runtime->nullPointer_),
curCodeBlock->getEnvironmentSize()));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
O1REG(CreateEnvironment) = *res;
#ifdef HERMES_ENABLE_DEBUGGER
FRAME.getDebugEnvironmentRef() = *res;
#endif
tmpHandle = HermesValue::encodeUndefinedValue();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateEnvironment);
DISPATCH;
}
CASE(StoreToEnvironment) {
vmcast<Environment>(O1REG(StoreToEnvironment))
->slot(ip->iStoreToEnvironment.op2)
.set(O3REG(StoreToEnvironment), &runtime->getHeap());
ip = NEXTINST(StoreToEnvironment);
DISPATCH;
}
CASE(StoreToEnvironmentL) {
vmcast<Environment>(O1REG(StoreToEnvironmentL))
->slot(ip->iStoreToEnvironmentL.op2)
.set(O3REG(StoreToEnvironmentL), &runtime->getHeap());
ip = NEXTINST(StoreToEnvironmentL);
DISPATCH;
}
CASE(StoreNPToEnvironment) {
vmcast<Environment>(O1REG(StoreNPToEnvironment))
->slot(ip->iStoreNPToEnvironment.op2)
.setNonPtr(O3REG(StoreNPToEnvironment), &runtime->getHeap());
ip = NEXTINST(StoreNPToEnvironment);
DISPATCH;
}
CASE(StoreNPToEnvironmentL) {
vmcast<Environment>(O1REG(StoreNPToEnvironmentL))
->slot(ip->iStoreNPToEnvironmentL.op2)
.setNonPtr(O3REG(StoreNPToEnvironmentL), &runtime->getHeap());
ip = NEXTINST(StoreNPToEnvironmentL);
DISPATCH;
}
CASE(LoadFromEnvironment) {
O1REG(LoadFromEnvironment) =
vmcast<Environment>(O2REG(LoadFromEnvironment))
->slot(ip->iLoadFromEnvironment.op3);
ip = NEXTINST(LoadFromEnvironment);
DISPATCH;
}
CASE(LoadFromEnvironmentL) {
O1REG(LoadFromEnvironmentL) =
vmcast<Environment>(O2REG(LoadFromEnvironmentL))
->slot(ip->iLoadFromEnvironmentL.op3);
ip = NEXTINST(LoadFromEnvironmentL);
DISPATCH;
}
CASE(GetGlobalObject) {
O1REG(GetGlobalObject) = runtime->global_;
ip = NEXTINST(GetGlobalObject);
DISPATCH;
}
CASE(GetNewTarget) {
O1REG(GetNewTarget) = FRAME.getNewTargetRef();
ip = NEXTINST(GetNewTarget);
DISPATCH;
}
CASE(DeclareGlobalVar) {
DefinePropertyFlags dpf =
DefinePropertyFlags::getDefaultNewPropertyFlags();
dpf.configurable = 0;
// Do not overwrite existing globals with undefined.
dpf.setValue = 0;
CAPTURE_IP_ASSIGN(
auto res,
JSObject::defineOwnProperty(
runtime->getGlobal(),
runtime,
ID(ip->iDeclareGlobalVar.op1),
dpf,
Runtime::getUndefinedValue(),
PropOpFlags().plusThrowOnError()));
if (res == ExecutionStatus::EXCEPTION) {
assert(
!runtime->getGlobal()->isProxyObject() &&
"global can't be a proxy object");
// If the property already exists, this should be a noop.
// Instead of incurring the cost to check every time, do it
// only if an exception is thrown, and swallow the exception
// if it exists, since we didn't want to make the call,
// anyway. This most likely means the property is
// non-configurable.
NamedPropertyDescriptor desc;
CAPTURE_IP_ASSIGN(
auto res,
JSObject::getOwnNamedDescriptor(
runtime->getGlobal(),
runtime,
ID(ip->iDeclareGlobalVar.op1),
desc));
if (!res) {
goto exception;
} else {
runtime->clearThrownValue();
}
// fall through
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(DeclareGlobalVar);
DISPATCH;
}
CASE(TryGetByIdLong) {
tryProp = true;
idVal = ip->iTryGetByIdLong.op4;
nextIP = NEXTINST(TryGetByIdLong);
goto getById;
}
CASE(GetByIdLong) {
tryProp = false;
idVal = ip->iGetByIdLong.op4;
nextIP = NEXTINST(GetByIdLong);
goto getById;
}
CASE(GetByIdShort) {
tryProp = false;
idVal = ip->iGetByIdShort.op4;
nextIP = NEXTINST(GetByIdShort);
goto getById;
}
CASE(TryGetById) {
tryProp = true;
idVal = ip->iTryGetById.op4;
nextIP = NEXTINST(TryGetById);
goto getById;
}
CASE(GetById) {
tryProp = false;
idVal = ip->iGetById.op4;
nextIP = NEXTINST(GetById);
}
getById : {
++NumGetById;
// NOTE: it is safe to use OnREG(GetById) here because all instructions
// have the same layout: opcode, registers, non-register operands, i.e.
// they only differ in the width of the last "identifier" field.
CallResult<HermesValue> propRes{ExecutionStatus::EXCEPTION};
if (LLVM_LIKELY(O2REG(GetById).isObject())) {
auto *obj = vmcast<JSObject>(O2REG(GetById));
auto cacheIdx = ip->iGetById.op3;
auto *cacheEntry = curCodeBlock->getReadCacheEntry(cacheIdx);
#ifdef HERMESVM_PROFILER_BB
{
HERMES_SLOW_ASSERT(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"unaccounted handles were created");
auto objHandle = runtime->makeHandle(obj);
auto cacheHCPtr = vmcast_or_null<HiddenClass>(static_cast<GCCell *>(
cacheEntry->clazz.get(runtime, &runtime->getHeap())));
CAPTURE_IP(runtime->recordHiddenClass(
curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));
// obj may be moved by GC due to recordHiddenClass
obj = objHandle.get();
}
gcScope.flushToSmallCount(KEEP_HANDLES);
#endif
auto clazzGCPtr = obj->getClassGCPtr();
#ifndef NDEBUG
if (clazzGCPtr.get(runtime)->isDictionary())
++NumGetByIdDict;
#else
(void)NumGetByIdDict;
#endif
// If we have a cache hit, reuse the cached offset and immediately
// return the property.
if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {
++NumGetByIdCacheHits;
CAPTURE_IP_ASSIGN(
O1REG(GetById),
JSObject::getNamedSlotValue<PropStorage::Inline::Yes>(
obj, runtime, cacheEntry->slot));
ip = nextIP;
DISPATCH;
}
auto id = ID(idVal);
NamedPropertyDescriptor desc;
CAPTURE_IP_ASSIGN(
OptValue<bool> fastPathResult,
JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));
if (LLVM_LIKELY(
fastPathResult.hasValue() && fastPathResult.getValue()) &&
!desc.flags.accessor) {
++NumGetByIdFastPaths;
// cacheIdx == 0 indicates no caching so don't update the cache in
// those cases.
auto *clazz = clazzGCPtr.getNonNull(runtime);
if (LLVM_LIKELY(!clazz->isDictionaryNoCache()) &&
LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {
#ifdef HERMES_SLOW_DEBUG
if (cacheEntry->clazz &&
cacheEntry->clazz != clazzGCPtr.getStorageType())
++NumGetByIdCacheEvicts;
#else
(void)NumGetByIdCacheEvicts;
#endif
// Cache the class, id and property slot.
cacheEntry->clazz = clazzGCPtr.getStorageType();
cacheEntry->slot = desc.slot;
}
CAPTURE_IP_ASSIGN(
O1REG(GetById), JSObject::getNamedSlotValue(obj, runtime, desc));
ip = nextIP;
DISPATCH;
}
// The cache may also be populated via the prototype of the object.
// This value is only reliable if the fast path was a definite
// not-found.
if (fastPathResult.hasValue() && !fastPathResult.getValue() &&
!obj->isProxyObject()) {
CAPTURE_IP_ASSIGN(JSObject * parent, obj->getParent(runtime));
// TODO: This isLazy check is because a lazy object is reported as
// having no properties and therefore cannot contain the property.
// This check does not belong here, it should be merged into
// tryGetOwnNamedDescriptorFast().
if (parent &&
cacheEntry->clazz == parent->getClassGCPtr().getStorageType() &&
LLVM_LIKELY(!obj->isLazy())) {
++NumGetByIdProtoHits;
CAPTURE_IP_ASSIGN(
O1REG(GetById),
JSObject::getNamedSlotValue(parent, runtime, cacheEntry->slot));
ip = nextIP;
DISPATCH;
}
}
#ifdef HERMES_SLOW_DEBUG
CAPTURE_IP_ASSIGN(
JSObject * propObj,
JSObject::getNamedDescriptor(
Handle<JSObject>::vmcast(&O2REG(GetById)), runtime, id, desc));
if (propObj) {
if (desc.flags.accessor)
++NumGetByIdAccessor;
else if (propObj != vmcast<JSObject>(O2REG(GetById)))
++NumGetByIdProto;
} else {
++NumGetByIdNotFound;
}
#else
(void)NumGetByIdAccessor;
(void)NumGetByIdProto;
(void)NumGetByIdNotFound;
#endif
#ifdef HERMES_SLOW_DEBUG
auto *savedClass = cacheIdx != hbc::PROPERTY_CACHING_DISABLED
? cacheEntry->clazz.get(runtime, &runtime->getHeap())
: nullptr;
#endif
++NumGetByIdSlow;
CAPTURE_IP_ASSIGN(
resPH,
JSObject::getNamed_RJS(
Handle<JSObject>::vmcast(&O2REG(GetById)),
runtime,
id,
!tryProp ? defaultPropOpFlags
: defaultPropOpFlags.plusMustExist(),
cacheIdx != hbc::PROPERTY_CACHING_DISABLED ? cacheEntry
: nullptr));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
#ifdef HERMES_SLOW_DEBUG
if (cacheIdx != hbc::PROPERTY_CACHING_DISABLED && savedClass &&
cacheEntry->clazz.get(runtime, &runtime->getHeap()) != savedClass) {
++NumGetByIdCacheEvicts;
}
#endif
} else {
++NumGetByIdTransient;
assert(!tryProp && "TryGetById can only be used on the global object");
/* Slow path. */
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::getByIdTransient_RJS(
runtime, Handle<>(&O2REG(GetById)), ID(idVal)));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
}
O1REG(GetById) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(TryPutByIdLong) {
tryProp = true;
idVal = ip->iTryPutByIdLong.op4;
nextIP = NEXTINST(TryPutByIdLong);
goto putById;
}
CASE(PutByIdLong) {
tryProp = false;
idVal = ip->iPutByIdLong.op4;
nextIP = NEXTINST(PutByIdLong);
goto putById;
}
CASE(TryPutById) {
tryProp = true;
idVal = ip->iTryPutById.op4;
nextIP = NEXTINST(TryPutById);
goto putById;
}
CASE(PutById) {
tryProp = false;
idVal = ip->iPutById.op4;
nextIP = NEXTINST(PutById);
}
putById : {
++NumPutById;
if (LLVM_LIKELY(O1REG(PutById).isObject())) {
auto *obj = vmcast<JSObject>(O1REG(PutById));
auto cacheIdx = ip->iPutById.op3;
auto *cacheEntry = curCodeBlock->getWriteCacheEntry(cacheIdx);
#ifdef HERMESVM_PROFILER_BB
{
HERMES_SLOW_ASSERT(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"unaccounted handles were created");
auto objHandle = runtime->makeHandle(obj);
auto cacheHCPtr = vmcast_or_null<HiddenClass>(static_cast<GCCell *>(
cacheEntry->clazz.get(runtime, &runtime->getHeap())));
CAPTURE_IP(runtime->recordHiddenClass(
curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));
// obj may be moved by GC due to recordHiddenClass
obj = objHandle.get();
}
gcScope.flushToSmallCount(KEEP_HANDLES);
#endif
auto clazzGCPtr = obj->getClassGCPtr();
// If we have a cache hit, reuse the cached offset and immediately
// return the property.
if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {
++NumPutByIdCacheHits;
CAPTURE_IP(JSObject::setNamedSlotValue<PropStorage::Inline::Yes>(
obj, runtime, cacheEntry->slot, O2REG(PutById)));
ip = nextIP;
DISPATCH;
}
auto id = ID(idVal);
NamedPropertyDescriptor desc;
CAPTURE_IP_ASSIGN(
OptValue<bool> hasOwnProp,
JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));
if (LLVM_LIKELY(hasOwnProp.hasValue() && hasOwnProp.getValue()) &&
!desc.flags.accessor && desc.flags.writable &&
!desc.flags.internalSetter) {
++NumPutByIdFastPaths;
// cacheIdx == 0 indicates no caching so don't update the cache in
// those cases.
auto *clazz = clazzGCPtr.getNonNull(runtime);
if (LLVM_LIKELY(!clazz->isDictionary()) &&
LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {
#ifdef HERMES_SLOW_DEBUG
if (cacheEntry->clazz &&
cacheEntry->clazz != clazzGCPtr.getStorageType())
++NumPutByIdCacheEvicts;
#else
(void)NumPutByIdCacheEvicts;
#endif
// Cache the class and property slot.
cacheEntry->clazz = clazzGCPtr.getStorageType();
cacheEntry->slot = desc.slot;
}
CAPTURE_IP(JSObject::setNamedSlotValue(
obj, runtime, desc.slot, O2REG(PutById)));
ip = nextIP;
DISPATCH;
}
CAPTURE_IP_ASSIGN(
auto putRes,
JSObject::putNamed_RJS(
Handle<JSObject>::vmcast(&O1REG(PutById)),
runtime,
id,
Handle<>(&O2REG(PutById)),
!tryProp ? defaultPropOpFlags
: defaultPropOpFlags.plusMustExist()));
if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {
goto exception;
}
} else {
++NumPutByIdTransient;
assert(!tryProp && "TryPutById can only be used on the global object");
CAPTURE_IP_ASSIGN(
auto retStatus,
Interpreter::putByIdTransient_RJS(
runtime,
Handle<>(&O1REG(PutById)),
ID(idVal),
Handle<>(&O2REG(PutById)),
strictMode));
if (retStatus == ExecutionStatus::EXCEPTION) {
goto exception;
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(GetByVal) {
CallResult<HermesValue> propRes{ExecutionStatus::EXCEPTION};
if (LLVM_LIKELY(O2REG(GetByVal).isObject())) {
CAPTURE_IP_ASSIGN(
resPH,
JSObject::getComputed_RJS(
Handle<JSObject>::vmcast(&O2REG(GetByVal)),
runtime,
Handle<>(&O3REG(GetByVal))));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
} else {
// This is the "slow path".
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::getByValTransient_RJS(
runtime,
Handle<>(&O2REG(GetByVal)),
Handle<>(&O3REG(GetByVal))));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(GetByVal) = resPH->get();
ip = NEXTINST(GetByVal);
DISPATCH;
}
CASE(PutByVal) {
if (LLVM_LIKELY(O1REG(PutByVal).isObject())) {
CAPTURE_IP_ASSIGN(
auto putRes,
JSObject::putComputed_RJS(
Handle<JSObject>::vmcast(&O1REG(PutByVal)),
runtime,
Handle<>(&O2REG(PutByVal)),
Handle<>(&O3REG(PutByVal)),
defaultPropOpFlags));
if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {
goto exception;
}
} else {
// This is the "slow path".
CAPTURE_IP_ASSIGN(
auto retStatus,
Interpreter::putByValTransient_RJS(
runtime,
Handle<>(&O1REG(PutByVal)),
Handle<>(&O2REG(PutByVal)),
Handle<>(&O3REG(PutByVal)),
strictMode));
if (LLVM_UNLIKELY(retStatus == ExecutionStatus::EXCEPTION)) {
goto exception;
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(PutByVal);
DISPATCH;
}
CASE(PutOwnByIndexL) {
nextIP = NEXTINST(PutOwnByIndexL);
idVal = ip->iPutOwnByIndexL.op3;
goto putOwnByIndex;
}
CASE(PutOwnByIndex) {
nextIP = NEXTINST(PutOwnByIndex);
idVal = ip->iPutOwnByIndex.op3;
}
putOwnByIndex : {
tmpHandle = HermesValue::encodeDoubleValue(idVal);
CAPTURE_IP(JSObject::defineOwnComputedPrimitive(
Handle<JSObject>::vmcast(&O1REG(PutOwnByIndex)),
runtime,
tmpHandle,
DefinePropertyFlags::getDefaultNewPropertyFlags(),
Handle<>(&O2REG(PutOwnByIndex))));
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = nextIP;
DISPATCH;
}
CASE(GetPNameList) {
CAPTURE_IP_ASSIGN(
auto pRes, handleGetPNameList(runtime, frameRegs, ip));
if (LLVM_UNLIKELY(pRes == ExecutionStatus::EXCEPTION)) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(GetPNameList);
DISPATCH;
}
CASE(GetNextPName) {
{
assert(
vmisa<BigStorage>(O2REG(GetNextPName)) &&
"GetNextPName's second op must be BigStorage");
auto obj = Handle<JSObject>::vmcast(&O3REG(GetNextPName));
auto arr = Handle<BigStorage>::vmcast(&O2REG(GetNextPName));
uint32_t idx = O4REG(GetNextPName).getNumber();
uint32_t size = O5REG(GetNextPName).getNumber();
MutableHandle<JSObject> propObj{runtime};
// Loop until we find a property which is present.
while (idx < size) {
tmpHandle = arr->at(idx);
ComputedPropertyDescriptor desc;
CAPTURE_IP(JSObject::getComputedPrimitiveDescriptor(
obj, runtime, tmpHandle, propObj, desc));
if (LLVM_LIKELY(propObj))
break;
++idx;
}
if (idx < size) {
// We must return the property as a string
if (tmpHandle->isNumber()) {
CAPTURE_IP_ASSIGN(auto status, toString_RJS(runtime, tmpHandle));
assert(
status == ExecutionStatus::RETURNED &&
"toString on number cannot fail");
tmpHandle = status->getHermesValue();
}
O1REG(GetNextPName) = tmpHandle.get();
O4REG(GetNextPName) = HermesValue::encodeNumberValue(idx + 1);
} else {
O1REG(GetNextPName) = HermesValue::encodeUndefinedValue();
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = NEXTINST(GetNextPName);
DISPATCH;
}
CASE(ToNumber) {
if (LLVM_LIKELY(O2REG(ToNumber).isNumber())) {
O1REG(ToNumber) = O2REG(ToNumber);
ip = NEXTINST(ToNumber);
} else {
CAPTURE_IP_ASSIGN(
res, toNumber_RJS(runtime, Handle<>(&O2REG(ToNumber))));
if (res == ExecutionStatus::EXCEPTION)
goto exception;
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(ToNumber) = res.getValue();
ip = NEXTINST(ToNumber);
}
DISPATCH;
}
CASE(ToInt32) {
CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(ToInt32))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
goto exception;
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(ToInt32) = res.getValue();
ip = NEXTINST(ToInt32);
DISPATCH;
}
CASE(AddEmptyString) {
if (LLVM_LIKELY(O2REG(AddEmptyString).isString())) {
O1REG(AddEmptyString) = O2REG(AddEmptyString);
ip = NEXTINST(AddEmptyString);
} else {
CAPTURE_IP_ASSIGN(
res,
toPrimitive_RJS(
runtime,
Handle<>(&O2REG(AddEmptyString)),
PreferredType::NONE));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
goto exception;
tmpHandle = res.getValue();
CAPTURE_IP_ASSIGN(auto strRes, toString_RJS(runtime, tmpHandle));
if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION))
goto exception;
tmpHandle.clear();
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(AddEmptyString) = strRes->getHermesValue();
ip = NEXTINST(AddEmptyString);
}
DISPATCH;
}
CASE(Jmp) {
ip = IPADD(ip->iJmp.op1);
DISPATCH;
}
CASE(JmpLong) {
ip = IPADD(ip->iJmpLong.op1);
DISPATCH;
}
CASE(JmpTrue) {
if (toBoolean(O2REG(JmpTrue)))
ip = IPADD(ip->iJmpTrue.op1);
else
ip = NEXTINST(JmpTrue);
DISPATCH;
}
CASE(JmpTrueLong) {
if (toBoolean(O2REG(JmpTrueLong)))
ip = IPADD(ip->iJmpTrueLong.op1);
else
ip = NEXTINST(JmpTrueLong);
DISPATCH;
}
CASE(JmpFalse) {
if (!toBoolean(O2REG(JmpFalse)))
ip = IPADD(ip->iJmpFalse.op1);
else
ip = NEXTINST(JmpFalse);
DISPATCH;
}
CASE(JmpFalseLong) {
if (!toBoolean(O2REG(JmpFalseLong)))
ip = IPADD(ip->iJmpFalseLong.op1);
else
ip = NEXTINST(JmpFalseLong);
DISPATCH;
}
CASE(JmpUndefined) {
if (O2REG(JmpUndefined).isUndefined())
ip = IPADD(ip->iJmpUndefined.op1);
else
ip = NEXTINST(JmpUndefined);
DISPATCH;
}
CASE(JmpUndefinedLong) {
if (O2REG(JmpUndefinedLong).isUndefined())
ip = IPADD(ip->iJmpUndefinedLong.op1);
else
ip = NEXTINST(JmpUndefinedLong);
DISPATCH;
}
CASE(Add) {
if (LLVM_LIKELY(
O2REG(Add).isNumber() &&
O3REG(Add).isNumber())) { /* Fast-path. */
CASE(AddN) {
O1REG(Add) = HermesValue::encodeDoubleValue(
O2REG(Add).getNumber() + O3REG(Add).getNumber());
ip = NEXTINST(Add);
DISPATCH;
}
}
CAPTURE_IP_ASSIGN(
res,
addOp_RJS(runtime, Handle<>(&O2REG(Add)), Handle<>(&O3REG(Add))));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(Add) = res.getValue();
ip = NEXTINST(Add);
DISPATCH;
}
CASE(BitNot) {
if (LLVM_LIKELY(O2REG(BitNot).isNumber())) { /* Fast-path. */
O1REG(BitNot) = HermesValue::encodeDoubleValue(
~hermes::truncateToInt32(O2REG(BitNot).getNumber()));
ip = NEXTINST(BitNot);
DISPATCH;
}
CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(BitNot))));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(BitNot) = HermesValue::encodeDoubleValue(
~static_cast<int32_t>(res->getNumber()));
ip = NEXTINST(BitNot);
DISPATCH;
}
CASE(GetArgumentsLength) {
// If the arguments object hasn't been created yet.
if (O2REG(GetArgumentsLength).isUndefined()) {
O1REG(GetArgumentsLength) =
HermesValue::encodeNumberValue(FRAME.getArgCount());
ip = NEXTINST(GetArgumentsLength);
DISPATCH;
}
// The arguments object has been created, so this is a regular property
// get.
assert(
O2REG(GetArgumentsLength).isObject() &&
"arguments lazy register is not an object");
CAPTURE_IP_ASSIGN(
resPH,
JSObject::getNamed_RJS(
Handle<JSObject>::vmcast(&O2REG(GetArgumentsLength)),
runtime,
Predefined::getSymbolID(Predefined::length)));
if (resPH == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(GetArgumentsLength) = resPH->get();
ip = NEXTINST(GetArgumentsLength);
DISPATCH;
}
CASE(GetArgumentsPropByVal) {
// If the arguments object hasn't been created yet and we have a
// valid integer index, we use the fast path.
if (O3REG(GetArgumentsPropByVal).isUndefined()) {
// If this is an integer index.
if (auto index = toArrayIndexFastPath(O2REG(GetArgumentsPropByVal))) {
// Is this an existing argument?
if (*index < FRAME.getArgCount()) {
O1REG(GetArgumentsPropByVal) = FRAME.getArgRef(*index);
ip = NEXTINST(GetArgumentsPropByVal);
DISPATCH;
}
}
}
// Slow path.
CAPTURE_IP_ASSIGN(
auto res,
getArgumentsPropByValSlowPath_RJS(
runtime,
&O3REG(GetArgumentsPropByVal),
&O2REG(GetArgumentsPropByVal),
FRAME.getCalleeClosureHandleUnsafe(),
strictMode));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(GetArgumentsPropByVal) = res->getHermesValue();
ip = NEXTINST(GetArgumentsPropByVal);
DISPATCH;
}
CASE(ReifyArguments) {
// If the arguments object was already created, do nothing.
if (!O1REG(ReifyArguments).isUndefined()) {
assert(
O1REG(ReifyArguments).isObject() &&
"arguments lazy register is not an object");
ip = NEXTINST(ReifyArguments);
DISPATCH;
}
CAPTURE_IP_ASSIGN(
resArgs,
reifyArgumentsSlowPath(
runtime, FRAME.getCalleeClosureHandleUnsafe(), strictMode));
if (LLVM_UNLIKELY(resArgs == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(ReifyArguments) = resArgs->getHermesValue();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(ReifyArguments);
DISPATCH;
}
CASE(NewObject) {
// Create a new object using the built-in constructor. Note that the
// built-in constructor is empty, so we don't actually need to call
// it.
CAPTURE_IP_ASSIGN(
O1REG(NewObject), JSObject::create(runtime).getHermesValue());
assert(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"Should not create handles.");
ip = NEXTINST(NewObject);
DISPATCH;
}
CASE(NewObjectWithParent) {
CAPTURE_IP_ASSIGN(
O1REG(NewObjectWithParent),
JSObject::create(
runtime,
O2REG(NewObjectWithParent).isObject()
? Handle<JSObject>::vmcast(&O2REG(NewObjectWithParent))
: O2REG(NewObjectWithParent).isNull()
? Runtime::makeNullHandle<JSObject>()
: Handle<JSObject>::vmcast(&runtime->objectPrototype))
.getHermesValue());
assert(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"Should not create handles.");
ip = NEXTINST(NewObjectWithParent);
DISPATCH;
}
CASE(NewObjectWithBuffer) {
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::createObjectFromBuffer(
runtime,
curCodeBlock,
ip->iNewObjectWithBuffer.op3,
ip->iNewObjectWithBuffer.op4,
ip->iNewObjectWithBuffer.op5));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(NewObjectWithBuffer) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(NewObjectWithBuffer);
DISPATCH;
}
CASE(NewObjectWithBufferLong) {
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::createObjectFromBuffer(
runtime,
curCodeBlock,
ip->iNewObjectWithBufferLong.op3,
ip->iNewObjectWithBufferLong.op4,
ip->iNewObjectWithBufferLong.op5));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(NewObjectWithBufferLong) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(NewObjectWithBufferLong);
DISPATCH;
}
CASE(NewArray) {
// Create a new array using the built-in constructor. Note that the
// built-in constructor is empty, so we don't actually need to call
// it.
CAPTURE_IP_ASSIGN(
auto createRes,
JSArray::create(runtime, ip->iNewArray.op2, ip->iNewArray.op2));
if (createRes == ExecutionStatus::EXCEPTION) {
goto exception;
}
O1REG(NewArray) = createRes->getHermesValue();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(NewArray);
DISPATCH;
}
CASE(NewArrayWithBuffer) {
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::createArrayFromBuffer(
runtime,
curCodeBlock,
ip->iNewArrayWithBuffer.op2,
ip->iNewArrayWithBuffer.op3,
ip->iNewArrayWithBuffer.op4));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(NewArrayWithBuffer) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = NEXTINST(NewArrayWithBuffer);
DISPATCH;
}
CASE(NewArrayWithBufferLong) {
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::createArrayFromBuffer(
runtime,
curCodeBlock,
ip->iNewArrayWithBufferLong.op2,
ip->iNewArrayWithBufferLong.op3,
ip->iNewArrayWithBufferLong.op4));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(NewArrayWithBufferLong) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = NEXTINST(NewArrayWithBufferLong);
DISPATCH;
}
CASE(CreateThis) {
// Registers: output, prototype, closure.
if (LLVM_UNLIKELY(!vmisa<Callable>(O3REG(CreateThis)))) {
CAPTURE_IP(runtime->raiseTypeError("constructor is not callable"));
goto exception;
}
CAPTURE_IP_ASSIGN(
auto res,
Callable::newObject(
Handle<Callable>::vmcast(&O3REG(CreateThis)),
runtime,
Handle<JSObject>::vmcast(
O2REG(CreateThis).isObject() ? &O2REG(CreateThis)
: &runtime->objectPrototype)));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(CreateThis) = res->getHermesValue();
ip = NEXTINST(CreateThis);
DISPATCH;
}
CASE(SelectObject) {
// Registers: output, thisObject, constructorReturnValue.
O1REG(SelectObject) = O3REG(SelectObject).isObject()
? O3REG(SelectObject)
: O2REG(SelectObject);
ip = NEXTINST(SelectObject);
DISPATCH;
}
CASE(Eq)
CASE(Neq) {
CAPTURE_IP_ASSIGN(
res,
abstractEqualityTest_RJS(
runtime, Handle<>(&O2REG(Eq)), Handle<>(&O3REG(Eq))));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(Eq) = ip->opCode == OpCode::Eq
? res.getValue()
: HermesValue::encodeBoolValue(!res->getBool());
ip = NEXTINST(Eq);
DISPATCH;
}
CASE(StrictEq) {
O1REG(StrictEq) = HermesValue::encodeBoolValue(
strictEqualityTest(O2REG(StrictEq), O3REG(StrictEq)));
ip = NEXTINST(StrictEq);
DISPATCH;
}
CASE(StrictNeq) {
O1REG(StrictNeq) = HermesValue::encodeBoolValue(
!strictEqualityTest(O2REG(StrictNeq), O3REG(StrictNeq)));
ip = NEXTINST(StrictNeq);
DISPATCH;
}
CASE(Not) {
O1REG(Not) = HermesValue::encodeBoolValue(!toBoolean(O2REG(Not)));
ip = NEXTINST(Not);
DISPATCH;
}
CASE(Negate) {
if (LLVM_LIKELY(O2REG(Negate).isNumber())) {
O1REG(Negate) =
HermesValue::encodeDoubleValue(-O2REG(Negate).getNumber());
} else {
CAPTURE_IP_ASSIGN(
res, toNumber_RJS(runtime, Handle<>(&O2REG(Negate))));
if (res == ExecutionStatus::EXCEPTION)
goto exception;
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(Negate) = HermesValue::encodeDoubleValue(-res->getNumber());
}
ip = NEXTINST(Negate);
DISPATCH;
}
CASE(TypeOf) {
CAPTURE_IP_ASSIGN(
O1REG(TypeOf), typeOf(runtime, Handle<>(&O2REG(TypeOf))));
ip = NEXTINST(TypeOf);
DISPATCH;
}
CASE(Mod) {
// We use fmod here for simplicity. Theoretically fmod behaves slightly
// differently than the ECMAScript Spec. fmod applies round-towards-zero
// for the remainder when it's not representable by a double; while the
// spec requires round-to-nearest. As an example, 5 % 0.7 will give
// 0.10000000000000031 using fmod, but using the rounding style
// described
// by the spec, the output should really be 0.10000000000000053.
// Such difference can be ignored in practice.
if (LLVM_LIKELY(O2REG(Mod).isNumber() && O3REG(Mod).isNumber())) {
/* Fast-path. */
O1REG(Mod) = HermesValue::encodeDoubleValue(
std::fmod(O2REG(Mod).getNumber(), O3REG(Mod).getNumber()));
ip = NEXTINST(Mod);
DISPATCH;
}
CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(Mod))));
if (res == ExecutionStatus::EXCEPTION)
goto exception;
double left = res->getDouble();
CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(Mod))));
if (res == ExecutionStatus::EXCEPTION)
goto exception;
O1REG(Mod) =
HermesValue::encodeDoubleValue(std::fmod(left, res->getDouble()));
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(Mod);
DISPATCH;
}
CASE(InstanceOf) {
CAPTURE_IP_ASSIGN(
auto result,
instanceOfOperator_RJS(
runtime,
Handle<>(&O2REG(InstanceOf)),
Handle<>(&O3REG(InstanceOf))));
if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(InstanceOf) = HermesValue::encodeBoolValue(*result);
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(InstanceOf);
DISPATCH;
}
CASE(IsIn) {
{
if (LLVM_UNLIKELY(!O3REG(IsIn).isObject())) {
CAPTURE_IP(runtime->raiseTypeError(
"right operand of 'in' is not an object"));
goto exception;
}
CAPTURE_IP_ASSIGN(
auto cr,
JSObject::hasComputed(
Handle<JSObject>::vmcast(&O3REG(IsIn)),
runtime,
Handle<>(&O2REG(IsIn))));
if (cr == ExecutionStatus::EXCEPTION) {
goto exception;
}
O1REG(IsIn) = HermesValue::encodeBoolValue(*cr);
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(IsIn);
DISPATCH;
}
CASE(PutNewOwnByIdShort) {
nextIP = NEXTINST(PutNewOwnByIdShort);
idVal = ip->iPutNewOwnByIdShort.op3;
goto putOwnById;
}
CASE(PutNewOwnNEByIdLong)
CASE(PutNewOwnByIdLong) {
nextIP = NEXTINST(PutNewOwnByIdLong);
idVal = ip->iPutNewOwnByIdLong.op3;
goto putOwnById;
}
CASE(PutNewOwnNEById)
CASE(PutNewOwnById) {
nextIP = NEXTINST(PutNewOwnById);
idVal = ip->iPutNewOwnById.op3;
}
putOwnById : {
assert(
O1REG(PutNewOwnById).isObject() &&
"Object argument of PutNewOwnById must be an object");
CAPTURE_IP_ASSIGN(
auto res,
JSObject::defineNewOwnProperty(
Handle<JSObject>::vmcast(&O1REG(PutNewOwnById)),
runtime,
ID(idVal),
ip->opCode <= OpCode::PutNewOwnByIdLong
? PropertyFlags::defaultNewNamedPropertyFlags()
: PropertyFlags::nonEnumerablePropertyFlags(),
Handle<>(&O2REG(PutNewOwnById))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(DelByIdLong) {
idVal = ip->iDelByIdLong.op3;
nextIP = NEXTINST(DelByIdLong);
goto DelById;
}
CASE(DelById) {
idVal = ip->iDelById.op3;
nextIP = NEXTINST(DelById);
}
DelById : {
if (LLVM_LIKELY(O2REG(DelById).isObject())) {
CAPTURE_IP_ASSIGN(
auto status,
JSObject::deleteNamed(
Handle<JSObject>::vmcast(&O2REG(DelById)),
runtime,
ID(idVal),
defaultPropOpFlags));
if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());
} else {
// This is the "slow path".
CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelById))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
// If an exception is thrown, likely we are trying to convert
// undefined/null to an object. Passing over the name of the property
// so that we could emit more meaningful error messages.
CAPTURE_IP(amendPropAccessErrorMsgWithPropName(
runtime, Handle<>(&O2REG(DelById)), "delete", ID(idVal)));
goto exception;
}
tmpHandle = res.getValue();
CAPTURE_IP_ASSIGN(
auto status,
JSObject::deleteNamed(
Handle<JSObject>::vmcast(tmpHandle),
runtime,
ID(idVal),
defaultPropOpFlags));
if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());
tmpHandle.clear();
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(DelByVal) {
if (LLVM_LIKELY(O2REG(DelByVal).isObject())) {
CAPTURE_IP_ASSIGN(
auto status,
JSObject::deleteComputed(
Handle<JSObject>::vmcast(&O2REG(DelByVal)),
runtime,
Handle<>(&O3REG(DelByVal)),
defaultPropOpFlags));
if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());
} else {
// This is the "slow path".
CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelByVal))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
tmpHandle = res.getValue();
CAPTURE_IP_ASSIGN(
auto status,
JSObject::deleteComputed(
Handle<JSObject>::vmcast(tmpHandle),
runtime,
Handle<>(&O3REG(DelByVal)),
defaultPropOpFlags));
if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());
}
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = NEXTINST(DelByVal);
DISPATCH;
}
CASE(CreateRegExp) {
{
// Create the RegExp object.
CAPTURE_IP_ASSIGN(auto re, JSRegExp::create(runtime));
// Initialize the regexp.
CAPTURE_IP_ASSIGN(
auto pattern,
runtime->makeHandle(curCodeBlock->getRuntimeModule()
->getStringPrimFromStringIDMayAllocate(
ip->iCreateRegExp.op2)));
CAPTURE_IP_ASSIGN(
auto flags,
runtime->makeHandle(curCodeBlock->getRuntimeModule()
->getStringPrimFromStringIDMayAllocate(
ip->iCreateRegExp.op3)));
CAPTURE_IP_ASSIGN(
auto bytecode,
curCodeBlock->getRuntimeModule()->getRegExpBytecodeFromRegExpID(
ip->iCreateRegExp.op4));
CAPTURE_IP_ASSIGN(
auto initRes,
JSRegExp::initialize(re, runtime, pattern, flags, bytecode));
if (LLVM_UNLIKELY(initRes == ExecutionStatus::EXCEPTION)) {
goto exception;
}
// Done, return the new object.
O1REG(CreateRegExp) = re.getHermesValue();
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateRegExp);
DISPATCH;
}
CASE(SwitchImm) {
if (LLVM_LIKELY(O1REG(SwitchImm).isNumber())) {
double numVal = O1REG(SwitchImm).getNumber();
uint32_t uintVal = (uint32_t)numVal;
if (LLVM_LIKELY(numVal == uintVal) && // Only integers.
LLVM_LIKELY(uintVal >= ip->iSwitchImm.op4) && // Bounds checking.
LLVM_LIKELY(uintVal <= ip->iSwitchImm.op5)) // Bounds checking.
{
// Calculate the offset into the bytecode where the jump table for
// this SwitchImm starts.
const uint8_t *tablestart = (const uint8_t *)llvh::alignAddr(
(const uint8_t *)ip + ip->iSwitchImm.op2, sizeof(uint32_t));
// Read the offset from the table.
// Must be signed to account for backwards branching.
const int32_t *loc =
(const int32_t *)tablestart + uintVal - ip->iSwitchImm.op4;
ip = IPADD(*loc);
DISPATCH;
}
}
// Wrong type or out of range, jump to default.
ip = IPADD(ip->iSwitchImm.op3);
DISPATCH;
}
LOAD_CONST(
LoadConstUInt8,
HermesValue::encodeDoubleValue(ip->iLoadConstUInt8.op2));
LOAD_CONST(
LoadConstInt, HermesValue::encodeDoubleValue(ip->iLoadConstInt.op2));
LOAD_CONST(
LoadConstDouble,
HermesValue::encodeDoubleValue(ip->iLoadConstDouble.op2));
LOAD_CONST_CAPTURE_IP(
LoadConstString,
HermesValue::encodeStringValue(
curCodeBlock->getRuntimeModule()
->getStringPrimFromStringIDMayAllocate(
ip->iLoadConstString.op2)));
LOAD_CONST_CAPTURE_IP(
LoadConstStringLongIndex,
HermesValue::encodeStringValue(
curCodeBlock->getRuntimeModule()
->getStringPrimFromStringIDMayAllocate(
ip->iLoadConstStringLongIndex.op2)));
LOAD_CONST(LoadConstUndefined, HermesValue::encodeUndefinedValue());
LOAD_CONST(LoadConstNull, HermesValue::encodeNullValue());
LOAD_CONST(LoadConstTrue, HermesValue::encodeBoolValue(true));
LOAD_CONST(LoadConstFalse, HermesValue::encodeBoolValue(false));
LOAD_CONST(LoadConstZero, HermesValue::encodeDoubleValue(0));
BINOP(Sub, doSub);
BINOP(Mul, doMult);
BINOP(Div, doDiv);
BITWISEBINOP(BitAnd, &);
BITWISEBINOP(BitOr, |);
BITWISEBINOP(BitXor, ^);
// For LShift, we need to use toUInt32 first because lshift on negative
// numbers is undefined behavior in theory.
SHIFTOP(LShift, <<, toUInt32_RJS, uint32_t, int32_t);
SHIFTOP(RShift, >>, toInt32_RJS, int32_t, int32_t);
SHIFTOP(URshift, >>, toUInt32_RJS, uint32_t, uint32_t);
CONDOP(Less, <, lessOp_RJS);
CONDOP(LessEq, <=, lessEqualOp_RJS);
CONDOP(Greater, >, greaterOp_RJS);
CONDOP(GreaterEq, >=, greaterEqualOp_RJS);
JCOND(Less, <, lessOp_RJS);
JCOND(LessEqual, <=, lessEqualOp_RJS);
JCOND(Greater, >, greaterOp_RJS);
JCOND(GreaterEqual, >=, greaterEqualOp_RJS);
JCOND_STRICT_EQ_IMPL(
JStrictEqual, , IPADD(ip->iJStrictEqual.op1), NEXTINST(JStrictEqual));
JCOND_STRICT_EQ_IMPL(
JStrictEqual,
Long,
IPADD(ip->iJStrictEqualLong.op1),
NEXTINST(JStrictEqualLong));
JCOND_STRICT_EQ_IMPL(
JStrictNotEqual,
,
NEXTINST(JStrictNotEqual),
IPADD(ip->iJStrictNotEqual.op1));
JCOND_STRICT_EQ_IMPL(
JStrictNotEqual,
Long,
NEXTINST(JStrictNotEqualLong),
IPADD(ip->iJStrictNotEqualLong.op1));
JCOND_EQ_IMPL(JEqual, , IPADD(ip->iJEqual.op1), NEXTINST(JEqual));
JCOND_EQ_IMPL(
JEqual, Long, IPADD(ip->iJEqualLong.op1), NEXTINST(JEqualLong));
JCOND_EQ_IMPL(
JNotEqual, , NEXTINST(JNotEqual), IPADD(ip->iJNotEqual.op1));
JCOND_EQ_IMPL(
JNotEqual,
Long,
NEXTINST(JNotEqualLong),
IPADD(ip->iJNotEqualLong.op1));
CASE_OUTOFLINE(PutOwnByVal);
CASE_OUTOFLINE(PutOwnGetterSetterByVal);
CASE_OUTOFLINE(DirectEval);
CASE_OUTOFLINE(IteratorBegin);
CASE_OUTOFLINE(IteratorNext);
CASE(IteratorClose) {
if (LLVM_UNLIKELY(O1REG(IteratorClose).isObject())) {
// The iterator must be closed if it's still an object.
// That means it was never an index and is not done iterating (a state
// which is indicated by `undefined`).
CAPTURE_IP_ASSIGN(
auto res,
iteratorClose(
runtime,
Handle<JSObject>::vmcast(&O1REG(IteratorClose)),
Runtime::getEmptyValue()));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
if (ip->iIteratorClose.op2 &&
!isUncatchableError(runtime->thrownValue_)) {
// Ignore inner exception.
runtime->clearThrownValue();
} else {
goto exception;
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
}
ip = NEXTINST(IteratorClose);
DISPATCH;
}
CASE(_last) {
llvm_unreachable("Invalid opcode _last");
}
}
llvm_unreachable("unreachable");
// We arrive here if we couldn't allocate the registers for the current frame.
stackOverflow:
CAPTURE_IP(runtime->raiseStackOverflow(
Runtime::StackOverflowKind::JSRegisterStack));
// We arrive here when we raised an exception in a callee, but we don't want
// the callee to be able to handle it.
handleExceptionInParent:
// Restore the caller code block and IP.
curCodeBlock = FRAME.getSavedCodeBlock();
ip = FRAME.getSavedIP();
// Pop to the previous frame where technically the error happened.
frameRegs =
&runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();
// If we are coming from native code, return.
if (!curCodeBlock)
return ExecutionStatus::EXCEPTION;
// Return because of recursive calling structure
#ifdef HERMESVM_PROFILER_EXTERN
return ExecutionStatus::EXCEPTION;
#endif
// Handle the exception.
exception:
UPDATE_OPCODE_TIME_SPENT;
assert(
!runtime->thrownValue_.isEmpty() &&
"thrownValue unavailable at exception");
bool catchable = true;
// If this is an Error object that was thrown internally, it didn't have
// access to the current codeblock and IP, so collect the stack trace here.
if (auto *jsError = dyn_vmcast<JSError>(runtime->thrownValue_)) {
catchable = jsError->catchable();
if (!jsError->getStackTrace()) {
// Temporarily clear the thrown value for following operations.
CAPTURE_IP_ASSIGN(
auto errorHandle,
runtime->makeHandle(vmcast<JSError>(runtime->thrownValue_)));
runtime->clearThrownValue();
CAPTURE_IP(JSError::recordStackTrace(
errorHandle, runtime, false, curCodeBlock, ip));
// Restore the thrown value.
runtime->setThrownValue(errorHandle.getHermesValue());
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
#ifdef HERMES_ENABLE_DEBUGGER
if (SingleStep) {
// If we're single stepping, don't bother with any more checks,
// and simply signal that we should continue execution with an exception.
state.codeBlock = curCodeBlock;
state.offset = CUROFFSET;
return ExecutionStatus::EXCEPTION;
}
using PauseOnThrowMode = facebook::hermes::debugger::PauseOnThrowMode;
auto mode = runtime->debugger_.getPauseOnThrowMode();
if (mode != PauseOnThrowMode::None) {
if (!runtime->debugger_.isDebugging()) {
// Determine whether the PauseOnThrowMode requires us to stop here.
bool caught =
runtime->debugger_
.findCatchTarget(InterpreterState(curCodeBlock, CUROFFSET))
.hasValue();
bool shouldStop = mode == PauseOnThrowMode::All ||
(mode == PauseOnThrowMode::Uncaught && !caught);
if (shouldStop) {
// When runDebugger is invoked after an exception,
// stepping should never happen internally.
// Any step is a step to an exception handler, which we do
// directly here in the interpreter.
// Thus, the result state should be the same as the input state.
InterpreterState tmpState{curCodeBlock, (uint32_t)CUROFFSET};
CAPTURE_IP_ASSIGN(
ExecutionStatus resultStatus,
runtime->debugger_.runDebugger(
Debugger::RunReason::Exception, tmpState));
(void)resultStatus;
assert(
tmpState == InterpreterState(curCodeBlock, CUROFFSET) &&
"not allowed to step internally in a pauseOnThrow");
gcScope.flushToSmallCount(KEEP_HANDLES);
}
}
}
#endif
int32_t handlerOffset = 0;
// If the exception is not catchable, skip found catch blocks.
while (((handlerOffset = curCodeBlock->findCatchTargetOffset(CUROFFSET)) ==
-1) ||
!catchable) {
PROFILER_EXIT_FUNCTION(curCodeBlock);
#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES
runtime->popCallStack();
#endif
// Restore the code block and IP.
curCodeBlock = FRAME.getSavedCodeBlock();
ip = FRAME.getSavedIP();
// Pop a stack frame.
frameRegs =
&runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();
SLOW_DEBUG(
dbgs() << "function exit with exception: restored stackLevel="
<< runtime->getStackLevel() << "\n");
// Are we returning to native code?
if (!curCodeBlock) {
SLOW_DEBUG(
dbgs()
<< "function exit with exception: returning to native code\n");
return ExecutionStatus::EXCEPTION;
}
assert(
isCallType(ip->opCode) &&
"return address is not Call-type instruction");
// Return because of recursive calling structure
#ifdef HERMESVM_PROFILER_EXTERN
return ExecutionStatus::EXCEPTION;
#endif
}
INIT_STATE_FOR_CODEBLOCK(curCodeBlock);
ip = IPADD(handlerOffset - CUROFFSET);
}
}
} // namespace vm
} // namespace hermes
| ./CrossVul/dataset_final_sorted/CWE-670/cpp/bad_4258_2 |
crossvul-cpp_data_good_4258_2 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#define DEBUG_TYPE "vm"
#include "hermes/VM/Interpreter.h"
#include "hermes/VM/Runtime.h"
#include "hermes/Inst/InstDecode.h"
#include "hermes/Support/Conversions.h"
#include "hermes/Support/SlowAssert.h"
#include "hermes/Support/Statistic.h"
#include "hermes/VM/Callable.h"
#include "hermes/VM/CodeBlock.h"
#include "hermes/VM/HandleRootOwner-inline.h"
#include "hermes/VM/JIT/JIT.h"
#include "hermes/VM/JSArray.h"
#include "hermes/VM/JSError.h"
#include "hermes/VM/JSGenerator.h"
#include "hermes/VM/JSProxy.h"
#include "hermes/VM/JSRegExp.h"
#include "hermes/VM/Operations.h"
#include "hermes/VM/Profiler.h"
#include "hermes/VM/Profiler/CodeCoverageProfiler.h"
#include "hermes/VM/Runtime-inline.h"
#include "hermes/VM/RuntimeModule-inline.h"
#include "hermes/VM/StackFrame-inline.h"
#include "hermes/VM/StringPrimitive.h"
#include "hermes/VM/StringView.h"
#include "llvh/ADT/SmallSet.h"
#include "llvh/Support/Debug.h"
#include "llvh/Support/Format.h"
#include "llvh/Support/raw_ostream.h"
#include "Interpreter-internal.h"
using llvh::dbgs;
using namespace hermes::inst;
HERMES_SLOW_STATISTIC(
NumGetById,
"NumGetById: Number of property 'read by id' accesses");
HERMES_SLOW_STATISTIC(
NumGetByIdCacheHits,
"NumGetByIdCacheHits: Number of property 'read by id' cache hits");
HERMES_SLOW_STATISTIC(
NumGetByIdProtoHits,
"NumGetByIdProtoHits: Number of property 'read by id' cache hits for the prototype");
HERMES_SLOW_STATISTIC(
NumGetByIdCacheEvicts,
"NumGetByIdCacheEvicts: Number of property 'read by id' cache evictions");
HERMES_SLOW_STATISTIC(
NumGetByIdFastPaths,
"NumGetByIdFastPaths: Number of property 'read by id' fast paths");
HERMES_SLOW_STATISTIC(
NumGetByIdAccessor,
"NumGetByIdAccessor: Number of property 'read by id' accessors");
HERMES_SLOW_STATISTIC(
NumGetByIdProto,
"NumGetByIdProto: Number of property 'read by id' in the prototype chain");
HERMES_SLOW_STATISTIC(
NumGetByIdNotFound,
"NumGetByIdNotFound: Number of property 'read by id' not found");
HERMES_SLOW_STATISTIC(
NumGetByIdTransient,
"NumGetByIdTransient: Number of property 'read by id' of non-objects");
HERMES_SLOW_STATISTIC(
NumGetByIdDict,
"NumGetByIdDict: Number of property 'read by id' of dictionaries");
HERMES_SLOW_STATISTIC(
NumGetByIdSlow,
"NumGetByIdSlow: Number of property 'read by id' slow path");
HERMES_SLOW_STATISTIC(
NumPutById,
"NumPutById: Number of property 'write by id' accesses");
HERMES_SLOW_STATISTIC(
NumPutByIdCacheHits,
"NumPutByIdCacheHits: Number of property 'write by id' cache hits");
HERMES_SLOW_STATISTIC(
NumPutByIdCacheEvicts,
"NumPutByIdCacheEvicts: Number of property 'write by id' cache evictions");
HERMES_SLOW_STATISTIC(
NumPutByIdFastPaths,
"NumPutByIdFastPaths: Number of property 'write by id' fast paths");
HERMES_SLOW_STATISTIC(
NumPutByIdTransient,
"NumPutByIdTransient: Number of property 'write by id' to non-objects");
HERMES_SLOW_STATISTIC(
NumNativeFunctionCalls,
"NumNativeFunctionCalls: Number of native function calls");
HERMES_SLOW_STATISTIC(
NumBoundFunctionCalls,
"NumBoundCalls: Number of bound function calls");
// Ensure that instructions declared as having matching layouts actually do.
#include "InstLayout.inc"
#if defined(HERMESVM_PROFILER_EXTERN)
// External profiler mode wraps calls to each JS function with a unique native
// function that recusively calls the interpreter. See Profiler.{h,cpp} for how
// these symbols are subsequently patched with JS function names.
#define INTERP_WRAPPER(name) \
__attribute__((__noinline__)) static llvh::CallResult<llvh::HermesValue> \
name(hermes::vm::Runtime *runtime, hermes::vm::CodeBlock *newCodeBlock) { \
return runtime->interpretFunctionImpl(newCodeBlock); \
}
PROFILER_SYMBOLS(INTERP_WRAPPER)
#endif
namespace hermes {
namespace vm {
#if defined(HERMESVM_PROFILER_EXTERN)
typedef CallResult<HermesValue> (*WrapperFunc)(Runtime *, CodeBlock *);
#define LIST_ITEM(name) name,
static const WrapperFunc interpWrappers[] = {PROFILER_SYMBOLS(LIST_ITEM)};
#endif
/// Initialize the state of some internal variables based on the current
/// code block.
#define INIT_STATE_FOR_CODEBLOCK(codeBlock) \
do { \
strictMode = (codeBlock)->isStrictMode(); \
defaultPropOpFlags = DEFAULT_PROP_OP_FLAGS(strictMode); \
} while (0)
CallResult<PseudoHandle<JSGeneratorFunction>>
Interpreter::createGeneratorClosure(
Runtime *runtime,
RuntimeModule *runtimeModule,
unsigned funcIndex,
Handle<Environment> envHandle) {
return JSGeneratorFunction::create(
runtime,
runtimeModule->getDomain(runtime),
Handle<JSObject>::vmcast(&runtime->generatorFunctionPrototype),
envHandle,
runtimeModule->getCodeBlockMayAllocate(funcIndex));
}
CallResult<PseudoHandle<JSGenerator>> Interpreter::createGenerator_RJS(
Runtime *runtime,
RuntimeModule *runtimeModule,
unsigned funcIndex,
Handle<Environment> envHandle,
NativeArgs args) {
auto gifRes = GeneratorInnerFunction::create(
runtime,
runtimeModule->getDomain(runtime),
Handle<JSObject>::vmcast(&runtime->functionPrototype),
envHandle,
runtimeModule->getCodeBlockMayAllocate(funcIndex),
args);
if (LLVM_UNLIKELY(gifRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto generatorFunction = runtime->makeHandle(vmcast<JSGeneratorFunction>(
runtime->getCurrentFrame().getCalleeClosure()));
auto prototypeProp = JSObject::getNamed_RJS(
generatorFunction,
runtime,
Predefined::getSymbolID(Predefined::prototype));
if (LLVM_UNLIKELY(prototypeProp == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
Handle<JSObject> prototype = vmisa<JSObject>(prototypeProp->get())
? runtime->makeHandle<JSObject>(prototypeProp->get())
: Handle<JSObject>::vmcast(&runtime->generatorPrototype);
return JSGenerator::create(runtime, *gifRes, prototype);
}
CallResult<Handle<Arguments>> Interpreter::reifyArgumentsSlowPath(
Runtime *runtime,
Handle<Callable> curFunction,
bool strictMode) {
auto frame = runtime->getCurrentFrame();
uint32_t argCount = frame.getArgCount();
// Define each JavaScript argument.
auto argRes = Arguments::create(runtime, argCount, curFunction, strictMode);
if (LLVM_UNLIKELY(argRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
Handle<Arguments> args = *argRes;
for (uint32_t argIndex = 0; argIndex < argCount; ++argIndex) {
Arguments::unsafeSetExistingElementAt(
*args, runtime, argIndex, frame.getArgRef(argIndex));
}
// The returned value should already be set from the create call.
return args;
}
CallResult<PseudoHandle<>> Interpreter::getArgumentsPropByValSlowPath_RJS(
Runtime *runtime,
PinnedHermesValue *lazyReg,
PinnedHermesValue *valueReg,
Handle<Callable> curFunction,
bool strictMode) {
auto frame = runtime->getCurrentFrame();
// If the arguments object has already been created.
if (!lazyReg->isUndefined()) {
// The arguments object has been created, so this is a regular property
// get.
assert(lazyReg->isObject() && "arguments lazy register is not an object");
return JSObject::getComputed_RJS(
Handle<JSObject>::vmcast(lazyReg), runtime, Handle<>(valueReg));
}
if (!valueReg->isSymbol()) {
// Attempt a fast path in the case that the key is not a symbol.
// If it is a symbol, force reification for now.
// Convert the value to a string.
auto strRes = toString_RJS(runtime, Handle<>(valueReg));
if (strRes == ExecutionStatus::EXCEPTION)
return ExecutionStatus::EXCEPTION;
auto strPrim = runtime->makeHandle(std::move(*strRes));
// Check if the string is a valid argument index.
if (auto index = toArrayIndex(runtime, strPrim)) {
if (*index < frame.getArgCount()) {
return createPseudoHandle(frame.getArgRef(*index));
}
auto objectPrototype =
Handle<JSObject>::vmcast(&runtime->objectPrototype);
// OK, they are requesting an index that either doesn't exist or is
// somewhere up in the prototype chain. Since we want to avoid reifying,
// check which it is:
MutableHandle<JSObject> inObject{runtime};
ComputedPropertyDescriptor desc;
JSObject::getComputedPrimitiveDescriptor(
objectPrototype, runtime, strPrim, inObject, desc);
// If we couldn't find the property, just return 'undefined'.
if (!inObject)
return createPseudoHandle(HermesValue::encodeUndefinedValue());
// If the property isn't an accessor, we can just return it without
// reifying.
if (!desc.flags.accessor) {
return createPseudoHandle(
JSObject::getComputedSlotValue(inObject.get(), runtime, desc));
}
}
// Are they requesting "arguments.length"?
if (runtime->symbolEqualsToStringPrim(
Predefined::getSymbolID(Predefined::length), *strPrim)) {
return createPseudoHandle(
HermesValue::encodeDoubleValue(frame.getArgCount()));
}
}
// Looking for an accessor or a property that needs reification.
auto argRes = reifyArgumentsSlowPath(runtime, curFunction, strictMode);
if (argRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// Update the register with the reified value.
*lazyReg = argRes->getHermesValue();
// For simplicity, call ourselves again.
return getArgumentsPropByValSlowPath_RJS(
runtime, lazyReg, valueReg, curFunction, strictMode);
}
ExecutionStatus Interpreter::handleGetPNameList(
Runtime *runtime,
PinnedHermesValue *frameRegs,
const Inst *ip) {
if (O2REG(GetPNameList).isUndefined() || O2REG(GetPNameList).isNull()) {
// Set the iterator to be undefined value.
O1REG(GetPNameList) = HermesValue::encodeUndefinedValue();
return ExecutionStatus::RETURNED;
}
// Convert to object and store it back to the register.
auto res = toObject(runtime, Handle<>(&O2REG(GetPNameList)));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
O2REG(GetPNameList) = res.getValue();
auto obj = runtime->makeMutableHandle(vmcast<JSObject>(res.getValue()));
uint32_t beginIndex;
uint32_t endIndex;
auto cr = getForInPropertyNames(runtime, obj, beginIndex, endIndex);
if (cr == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto arr = *cr;
O1REG(GetPNameList) = arr.getHermesValue();
O3REG(GetPNameList) = HermesValue::encodeNumberValue(beginIndex);
O4REG(GetPNameList) = HermesValue::encodeNumberValue(endIndex);
return ExecutionStatus::RETURNED;
}
CallResult<PseudoHandle<>> Interpreter::handleCallSlowPath(
Runtime *runtime,
PinnedHermesValue *callTarget) {
if (auto *native = dyn_vmcast<NativeFunction>(*callTarget)) {
++NumNativeFunctionCalls;
// Call the native function directly
return NativeFunction::_nativeCall(native, runtime);
} else if (auto *bound = dyn_vmcast<BoundFunction>(*callTarget)) {
++NumBoundFunctionCalls;
// Call the bound function.
return BoundFunction::_boundCall(bound, runtime->getCurrentIP(), runtime);
} else {
return runtime->raiseTypeErrorForValue(
Handle<>(callTarget), " is not a function");
}
}
inline PseudoHandle<> Interpreter::tryGetPrimitiveOwnPropertyById(
Runtime *runtime,
Handle<> base,
SymbolID id) {
if (base->isString() && id == Predefined::getSymbolID(Predefined::length)) {
return createPseudoHandle(
HermesValue::encodeNumberValue(base->getString()->getStringLength()));
}
return createPseudoHandle(HermesValue::encodeEmptyValue());
}
CallResult<PseudoHandle<>> Interpreter::getByIdTransient_RJS(
Runtime *runtime,
Handle<> base,
SymbolID id) {
// This is similar to what ES5.1 8.7.1 special [[Get]] internal
// method did, but that section doesn't exist in ES9 anymore.
// Instead, the [[Get]] Receiver argument serves a similar purpose.
// Fast path: try to get primitive own property directly first.
PseudoHandle<> valOpt = tryGetPrimitiveOwnPropertyById(runtime, base, id);
if (!valOpt->isEmpty()) {
return valOpt;
}
// get the property descriptor from primitive prototype without
// boxing with vm::toObject(). This is where any properties will
// be.
CallResult<Handle<JSObject>> primitivePrototypeResult =
getPrimitivePrototype(runtime, base);
if (primitivePrototypeResult == ExecutionStatus::EXCEPTION) {
// If an exception is thrown, likely we are trying to read property on
// undefined/null. Passing over the name of the property
// so that we could emit more meaningful error messages.
return amendPropAccessErrorMsgWithPropName(runtime, base, "read", id);
}
return JSObject::getNamedWithReceiver_RJS(
*primitivePrototypeResult, runtime, id, base);
}
PseudoHandle<> Interpreter::getByValTransientFast(
Runtime *runtime,
Handle<> base,
Handle<> nameHandle) {
if (base->isString()) {
// Handle most common fast path -- array index property for string
// primitive.
// Since primitive string cannot have index like property we can
// skip ObjectFlags::fastIndexProperties checking and directly
// checking index storage from StringPrimitive.
OptValue<uint32_t> arrayIndex = toArrayIndexFastPath(*nameHandle);
// Get character directly from primitive if arrayIndex is within range.
// Otherwise we need to fall back to prototype lookup.
if (arrayIndex &&
arrayIndex.getValue() < base->getString()->getStringLength()) {
return createPseudoHandle(
runtime
->getCharacterString(base->getString()->at(arrayIndex.getValue()))
.getHermesValue());
}
}
return createPseudoHandle(HermesValue::encodeEmptyValue());
}
CallResult<PseudoHandle<>> Interpreter::getByValTransient_RJS(
Runtime *runtime,
Handle<> base,
Handle<> name) {
// This is similar to what ES5.1 8.7.1 special [[Get]] internal
// method did, but that section doesn't exist in ES9 anymore.
// Instead, the [[Get]] Receiver argument serves a similar purpose.
// Optimization: check fast path first.
PseudoHandle<> fastRes = getByValTransientFast(runtime, base, name);
if (!fastRes->isEmpty()) {
return fastRes;
}
auto res = toObject(runtime, base);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
return ExecutionStatus::EXCEPTION;
return JSObject::getComputedWithReceiver_RJS(
runtime->makeHandle<JSObject>(res.getValue()), runtime, name, base);
}
static ExecutionStatus
transientObjectPutErrorMessage(Runtime *runtime, Handle<> base, SymbolID id) {
// Emit an error message that looks like:
// "Cannot create property '%{id}' on ${typeof base} '${String(base)}'".
StringView propName =
runtime->getIdentifierTable().getStringView(runtime, id);
Handle<StringPrimitive> baseType =
runtime->makeHandle(vmcast<StringPrimitive>(typeOf(runtime, base)));
StringView baseTypeAsString =
StringPrimitive::createStringView(runtime, baseType);
MutableHandle<StringPrimitive> valueAsString{runtime};
if (base->isSymbol()) {
// Special workaround for Symbol which can't be stringified.
auto str = symbolDescriptiveString(runtime, Handle<SymbolID>::vmcast(base));
if (str != ExecutionStatus::EXCEPTION) {
valueAsString = *str;
} else {
runtime->clearThrownValue();
valueAsString = StringPrimitive::createNoThrow(
runtime, "<<Exception occurred getting the value>>");
}
} else {
auto str = toString_RJS(runtime, base);
assert(
str != ExecutionStatus::EXCEPTION &&
"Primitives should be convertible to string without exceptions");
valueAsString = std::move(*str);
}
StringView valueAsStringPrintable =
StringPrimitive::createStringView(runtime, valueAsString);
SmallU16String<32> tmp1;
SmallU16String<32> tmp2;
return runtime->raiseTypeError(
TwineChar16("Cannot create property '") + propName + "' on " +
baseTypeAsString.getUTF16Ref(tmp1) + " '" +
valueAsStringPrintable.getUTF16Ref(tmp2) + "'");
}
ExecutionStatus Interpreter::putByIdTransient_RJS(
Runtime *runtime,
Handle<> base,
SymbolID id,
Handle<> value,
bool strictMode) {
// ES5.1 8.7.2 special [[Get]] internal method.
// TODO: avoid boxing primitives unless we are calling an accessor.
// 1. Let O be ToObject(base)
auto res = toObject(runtime, base);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
// If an exception is thrown, likely we are trying to convert
// undefined/null to an object. Passing over the name of the property
// so that we could emit more meaningful error messages.
return amendPropAccessErrorMsgWithPropName(runtime, base, "set", id);
}
auto O = runtime->makeHandle<JSObject>(res.getValue());
NamedPropertyDescriptor desc;
JSObject *propObj = JSObject::getNamedDescriptor(O, runtime, id, desc);
// Is this a missing property, or a data property defined in the prototype
// chain? In both cases we would need to create an own property on the
// transient object, which is prohibited.
if (!propObj ||
(propObj != O.get() &&
(!desc.flags.accessor && !desc.flags.proxyObject))) {
if (strictMode) {
return transientObjectPutErrorMessage(runtime, base, id);
}
return ExecutionStatus::RETURNED;
}
// Modifying an own data property in a transient object is prohibited.
if (!desc.flags.accessor && !desc.flags.proxyObject) {
if (strictMode) {
return runtime->raiseTypeError(
"Cannot modify a property in a transient object");
}
return ExecutionStatus::RETURNED;
}
if (desc.flags.accessor) {
// This is an accessor.
auto *accessor = vmcast<PropertyAccessor>(
JSObject::getNamedSlotValue(propObj, runtime, desc));
// It needs to have a setter.
if (!accessor->setter) {
if (strictMode) {
return runtime->raiseTypeError("Cannot modify a read-only accessor");
}
return ExecutionStatus::RETURNED;
}
CallResult<PseudoHandle<>> setRes =
accessor->setter.get(runtime)->executeCall1(
runtime->makeHandle(accessor->setter), runtime, base, *value);
if (setRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
} else {
assert(desc.flags.proxyObject && "descriptor flags are impossible");
CallResult<bool> setRes = JSProxy::setNamed(
runtime->makeHandle(propObj), runtime, id, value, base);
if (setRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
if (!*setRes && strictMode) {
return runtime->raiseTypeError("transient proxy set returned false");
}
}
return ExecutionStatus::RETURNED;
}
ExecutionStatus Interpreter::putByValTransient_RJS(
Runtime *runtime,
Handle<> base,
Handle<> name,
Handle<> value,
bool strictMode) {
auto idRes = valueToSymbolID(runtime, name);
if (idRes == ExecutionStatus::EXCEPTION)
return ExecutionStatus::EXCEPTION;
return putByIdTransient_RJS(runtime, base, **idRes, value, strictMode);
}
CallResult<PseudoHandle<>> Interpreter::createObjectFromBuffer(
Runtime *runtime,
CodeBlock *curCodeBlock,
unsigned numLiterals,
unsigned keyBufferIndex,
unsigned valBufferIndex) {
// Fetch any cached hidden class first.
auto *runtimeModule = curCodeBlock->getRuntimeModule();
const llvh::Optional<Handle<HiddenClass>> optCachedHiddenClassHandle =
runtimeModule->findCachedLiteralHiddenClass(
runtime, keyBufferIndex, numLiterals);
// Create a new object using the built-in constructor or cached hidden class.
// Note that the built-in constructor is empty, so we don't actually need to
// call it.
auto obj = runtime->makeHandle(
optCachedHiddenClassHandle.hasValue()
? JSObject::create(runtime, optCachedHiddenClassHandle.getValue())
: JSObject::create(runtime, numLiterals));
MutableHandle<> tmpHandleKey(runtime);
MutableHandle<> tmpHandleVal(runtime);
auto &gcScope = *runtime->getTopGCScope();
auto marker = gcScope.createMarker();
auto genPair = curCodeBlock->getObjectBufferIter(
keyBufferIndex, valBufferIndex, numLiterals);
auto keyGen = genPair.first;
auto valGen = genPair.second;
if (optCachedHiddenClassHandle.hasValue()) {
uint32_t propIndex = 0;
// keyGen should always have the same amount of elements as valGen
while (valGen.hasNext()) {
#ifndef NDEBUG
{
// keyGen points to an element in the key buffer, which means it will
// only ever generate a Number or a Symbol. This means it will never
// allocate memory, and it is safe to not use a Handle.
SymbolID stringIdResult{};
auto key = keyGen.get(runtime);
if (key.isSymbol()) {
stringIdResult = ID(key.getSymbol().unsafeGetIndex());
} else {
tmpHandleKey = HermesValue::encodeDoubleValue(key.getNumber());
auto idRes = valueToSymbolID(runtime, tmpHandleKey);
assert(
idRes != ExecutionStatus::EXCEPTION &&
"valueToIdentifier() failed for uint32_t value");
stringIdResult = **idRes;
}
NamedPropertyDescriptor desc;
auto pos = HiddenClass::findProperty(
optCachedHiddenClassHandle.getValue(),
runtime,
stringIdResult,
PropertyFlags::defaultNewNamedPropertyFlags(),
desc);
assert(
pos &&
"Should find this property in cached hidden class property table.");
assert(
desc.slot == propIndex &&
"propIndex should be the same as recorded in hidden class table.");
}
#endif
// Explicitly make sure valGen.get() is called before obj.get() so that
// any allocation in valGen.get() won't invalidate the raw pointer
// retruned from obj.get().
auto val = valGen.get(runtime);
JSObject::setNamedSlotValue(obj.get(), runtime, propIndex, val);
gcScope.flushToMarker(marker);
++propIndex;
}
} else {
// keyGen should always have the same amount of elements as valGen
while (keyGen.hasNext()) {
// keyGen points to an element in the key buffer, which means it will
// only ever generate a Number or a Symbol. This means it will never
// allocate memory, and it is safe to not use a Handle.
auto key = keyGen.get(runtime);
tmpHandleVal = valGen.get(runtime);
if (key.isSymbol()) {
auto stringIdResult = ID(key.getSymbol().unsafeGetIndex());
if (LLVM_UNLIKELY(
JSObject::defineNewOwnProperty(
obj,
runtime,
stringIdResult,
PropertyFlags::defaultNewNamedPropertyFlags(),
tmpHandleVal) == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
} else {
tmpHandleKey = HermesValue::encodeDoubleValue(key.getNumber());
if (LLVM_UNLIKELY(
!JSObject::defineOwnComputedPrimitive(
obj,
runtime,
tmpHandleKey,
DefinePropertyFlags::getDefaultNewPropertyFlags(),
tmpHandleVal)
.getValue())) {
return ExecutionStatus::EXCEPTION;
}
}
gcScope.flushToMarker(marker);
}
}
tmpHandleKey.clear();
tmpHandleVal.clear();
// Hidden class in dictionary mode can't be shared.
HiddenClass *const clazz = obj->getClass(runtime);
if (!optCachedHiddenClassHandle.hasValue() && !clazz->isDictionary()) {
assert(
numLiterals == clazz->getNumProperties() &&
"numLiterals should match hidden class property count.");
assert(
clazz->getNumProperties() < 256 &&
"cached hidden class should have property count less than 256");
runtimeModule->tryCacheLiteralHiddenClass(runtime, keyBufferIndex, clazz);
}
return createPseudoHandle(HermesValue::encodeObjectValue(*obj));
}
CallResult<PseudoHandle<>> Interpreter::createArrayFromBuffer(
Runtime *runtime,
CodeBlock *curCodeBlock,
unsigned numElements,
unsigned numLiterals,
unsigned bufferIndex) {
// Create a new array using the built-in constructor, and initialize
// the elements from a literal array buffer.
auto arrRes = JSArray::create(runtime, numElements, numElements);
if (arrRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// Resize the array storage in advance.
auto arr = runtime->makeHandle(std::move(*arrRes));
JSArray::setStorageEndIndex(arr, runtime, numElements);
auto iter = curCodeBlock->getArrayBufferIter(bufferIndex, numLiterals);
JSArray::size_type i = 0;
while (iter.hasNext()) {
// NOTE: we must get the value in a separate step to guarantee ordering.
auto value = iter.get(runtime);
JSArray::unsafeSetExistingElementAt(*arr, runtime, i++, value);
}
return createPseudoHandle(HermesValue::encodeObjectValue(*arr));
}
#ifndef NDEBUG
namespace {
/// A tag used to instruct the output stream to dump more details about the
/// HermesValue, like the length of the string, etc.
struct DumpHermesValue {
const HermesValue hv;
DumpHermesValue(HermesValue hv) : hv(hv) {}
};
} // anonymous namespace.
static llvh::raw_ostream &operator<<(
llvh::raw_ostream &OS,
DumpHermesValue dhv) {
OS << dhv.hv;
// If it is a string, dump the contents, truncated to 8 characters.
if (dhv.hv.isString()) {
SmallU16String<32> str;
dhv.hv.getString()->appendUTF16String(str);
UTF16Ref ref = str.arrayRef();
if (str.size() <= 8) {
OS << ":'" << ref << "'";
} else {
OS << ":'" << ref.slice(0, 8) << "'";
OS << "...[" << str.size() << "]";
}
}
return OS;
}
/// Dump the arguments from a callee frame.
LLVM_ATTRIBUTE_UNUSED
static void dumpCallArguments(
llvh::raw_ostream &OS,
Runtime *runtime,
StackFramePtr calleeFrame) {
OS << "arguments:\n";
OS << " " << 0 << " " << DumpHermesValue(calleeFrame.getThisArgRef())
<< "\n";
for (unsigned i = 0; i < calleeFrame.getArgCount(); ++i) {
OS << " " << (i + 1) << " " << DumpHermesValue(calleeFrame.getArgRef(i))
<< "\n";
}
}
LLVM_ATTRIBUTE_UNUSED
static void printDebugInfo(
CodeBlock *curCodeBlock,
PinnedHermesValue *frameRegs,
const Inst *ip) {
// Check if LLVm debugging is enabled for us.
bool debug = false;
SLOW_DEBUG(debug = true);
if (!debug)
return;
DecodedInstruction decoded = decodeInstruction(ip);
dbgs() << llvh::format_decimal((const uint8_t *)ip - curCodeBlock->begin(), 4)
<< " OpCode::" << getOpCodeString(decoded.meta.opCode);
for (unsigned i = 0; i < decoded.meta.numOperands; ++i) {
auto operandType = decoded.meta.operandType[i];
auto value = decoded.operandValue[i];
dbgs() << (i == 0 ? " " : ", ");
dumpOperand(dbgs(), operandType, value);
if (operandType == OperandType::Reg8 || operandType == OperandType::Reg32) {
// Print the register value, if source.
if (i != 0 || decoded.meta.numOperands == 1)
dbgs() << "=" << DumpHermesValue(REG(value.integer));
}
}
dbgs() << "\n";
}
/// \return whether \p opcode is a call opcode (Call, CallDirect, Construct,
/// CallLongIndex, etc). Note CallBuiltin is not really a Call.
LLVM_ATTRIBUTE_UNUSED
static bool isCallType(OpCode opcode) {
switch (opcode) {
#define DEFINE_RET_TARGET(name) \
case OpCode::name: \
return true;
#include "hermes/BCGen/HBC/BytecodeList.def"
default:
return false;
}
}
#endif
/// \return the address of the next instruction after \p ip, which must be a
/// call-type instruction.
LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline const Inst *nextInstCall(const Inst *ip) {
HERMES_SLOW_ASSERT(isCallType(ip->opCode) && "ip is not of call type");
// The following is written to elicit compares instead of table lookup.
// The idea is to present code like so:
// if (opcode <= 70) return ip + 4;
// if (opcode <= 71) return ip + 4;
// if (opcode <= 72) return ip + 4;
// if (opcode <= 73) return ip + 5;
// if (opcode <= 74) return ip + 5;
// ...
// and the compiler will retain only compares where the result changes (here,
// 72 and 74). This allows us to compute the next instruction using three
// compares, instead of a naive compare-per-call type (or lookup table).
//
// Statically verify that increasing call opcodes correspond to monotone
// instruction sizes; this enables the compiler to do a better job optimizing.
constexpr bool callSizesMonotoneIncreasing = monotoneIncreasing(
#define DEFINE_RET_TARGET(name) sizeof(inst::name##Inst),
#include "hermes/BCGen/HBC/BytecodeList.def"
SIZE_MAX // sentinel avoiding a trailing comma.
);
static_assert(
callSizesMonotoneIncreasing,
"Call instruction sizes are not monotone increasing");
#define DEFINE_RET_TARGET(name) \
if (ip->opCode <= OpCode::name) \
return NEXTINST(name);
#include "hermes/BCGen/HBC/BytecodeList.def"
llvm_unreachable("Not a call type");
}
CallResult<HermesValue> Runtime::interpretFunctionImpl(
CodeBlock *newCodeBlock) {
newCodeBlock->lazyCompile(this);
#if defined(HERMES_ENABLE_ALLOCATION_LOCATION_TRACES) || !defined(NDEBUG)
// We always call getCurrentIP() in a debug build as this has the effect
// of asserting the IP is correctly set (not invalidated) at this point.
// This allows us to leverage our whole test-suite to find missing cases
// of CAPTURE_IP* macros in the interpreter loop.
const inst::Inst *ip = getCurrentIP();
(void)ip;
#endif
#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES
if (ip) {
const CodeBlock *codeBlock;
std::tie(codeBlock, ip) = getCurrentInterpreterLocation(ip);
// All functions end in a Ret so we must match this with a pushCallStack()
// before executing.
if (codeBlock) {
// Push a call entry at the last location we were executing bytecode.
// This will correctly attribute things like eval().
pushCallStack(codeBlock, ip);
} else {
// Push a call entry at the entry at the top of interpreted code.
pushCallStack(newCodeBlock, (const Inst *)newCodeBlock->begin());
}
} else {
// Push a call entry at the entry at the top of interpreted code.
pushCallStack(newCodeBlock, (const Inst *)newCodeBlock->begin());
}
#endif
InterpreterState state{newCodeBlock, 0};
return Interpreter::interpretFunction<false>(this, state);
}
CallResult<HermesValue> Runtime::interpretFunction(CodeBlock *newCodeBlock) {
#ifdef HERMESVM_PROFILER_EXTERN
auto id = getProfilerID(newCodeBlock);
if (id >= NUM_PROFILER_SYMBOLS) {
id = NUM_PROFILER_SYMBOLS - 1; // Overflow entry.
}
return interpWrappers[id](this, newCodeBlock);
#else
return interpretFunctionImpl(newCodeBlock);
#endif
}
#ifdef HERMES_ENABLE_DEBUGGER
ExecutionStatus Runtime::stepFunction(InterpreterState &state) {
return Interpreter::interpretFunction<true>(this, state).getStatus();
}
#endif
/// \return the quotient of x divided by y.
static double doDiv(double x, double y)
LLVM_NO_SANITIZE("float-divide-by-zero");
static inline double doDiv(double x, double y) {
// UBSan will complain about float divide by zero as our implementation
// of OpCode::Div depends on IEEE 754 float divide by zero. All modern
// compilers implement this and there is no trivial work-around without
// sacrificing performance and readability.
// NOTE: This was pulled out of the interpreter to avoid putting the sanitize
// silencer on the entire interpreter function.
return x / y;
}
/// \return the product of x multiplied by y.
static inline double doMult(double x, double y) {
return x * y;
}
/// \return the difference of y subtracted from x.
static inline double doSub(double x, double y) {
return x - y;
}
template <bool SingleStep>
CallResult<HermesValue> Interpreter::interpretFunction(
Runtime *runtime,
InterpreterState &state) {
// The interepter is re-entrant and also saves/restores its IP via the runtime
// whenever a call out is made (see the CAPTURE_IP_* macros). As such, failure
// to preserve the IP across calls to interpeterFunction() disrupt interpreter
// calls further up the C++ callstack. The RAII utility class below makes sure
// we always do this correctly.
//
// TODO: The IPs stored in the C++ callstack via this holder will generally be
// the same as in the JS stack frames via the Saved IP field. We can probably
// get rid of one of these redundant stores. Doing this isn't completely
// trivial as there are currently cases where we re-enter the interpreter
// without calling Runtime::saveCallerIPInStackFrame(), and there are features
// (I think mostly the debugger + stack traces) which implicitly rely on
// this behavior. At least their tests break if this behavior is not
// preserved.
struct IPSaver {
IPSaver(Runtime *runtime)
: ip_(runtime->getCurrentIP()), runtime_(runtime) {}
~IPSaver() {
runtime_->setCurrentIP(ip_);
}
private:
const Inst *ip_;
Runtime *runtime_;
};
IPSaver ipSaver(runtime);
#ifndef HERMES_ENABLE_DEBUGGER
static_assert(!SingleStep, "can't use single-step mode without the debugger");
#endif
// Make sure that the cache can use an optimization by avoiding a branch to
// access the property storage.
static_assert(
HiddenClass::kDictionaryThreshold <=
SegmentedArray::kValueToSegmentThreshold,
"Cannot avoid branches in cache check if the dictionary "
"crossover point is larger than the inline storage");
CodeBlock *curCodeBlock = state.codeBlock;
const Inst *ip = nullptr;
// Holds runtime->currentFrame_.ptr()-1 which is the first local
// register. This eliminates the indirect load from Runtime and the -1 offset.
PinnedHermesValue *frameRegs;
// Strictness of current function.
bool strictMode;
// Default flags when accessing properties.
PropOpFlags defaultPropOpFlags;
// These CAPTURE_IP* macros should wrap around any major calls out of the
// interpeter loop. They stash and retrieve the IP via the current Runtime
// allowing the IP to be externally observed and even altered to change the flow
// of execution. Explicitly saving AND restoring the IP from the Runtime in this
// way means the C++ compiler will keep IP in a register within the rest of the
// interpeter loop.
//
// When assertions are enabled we take the extra step of "invalidating" the IP
// between captures so we can detect if it's erroneously accessed.
//
// In some cases we explicitly don't want to invalidate the IP and instead want
// it to stay set. For this we use the *NO_INVALIDATE variants. This comes up
// when we're performing a call operation which may re-enter the interpeter
// loop, and so need the IP available for the saveCallerIPInStackFrame() call
// when we next enter.
#define CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr) \
runtime->setCurrentIP(ip); \
dst = expr; \
ip = runtime->getCurrentIP();
#ifdef NDEBUG
#define CAPTURE_IP(expr) \
runtime->setCurrentIP(ip); \
(void)expr; \
ip = runtime->getCurrentIP();
#define CAPTURE_IP_ASSIGN(dst, expr) CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr)
#else // !NDEBUG
#define CAPTURE_IP(expr) \
runtime->setCurrentIP(ip); \
(void)expr; \
ip = runtime->getCurrentIP(); \
runtime->invalidateCurrentIP();
#define CAPTURE_IP_ASSIGN(dst, expr) \
runtime->setCurrentIP(ip); \
dst = expr; \
ip = runtime->getCurrentIP(); \
runtime->invalidateCurrentIP();
#endif // NDEBUG
/// \def DONT_CAPTURE_IP(expr)
/// \param expr A call expression to a function external to the interpreter. The
/// expression should not make any allocations and the IP should be set
/// immediately following this macro.
#define DONT_CAPTURE_IP(expr) \
do { \
NoAllocScope noAlloc(runtime); \
(void)expr; \
} while (false)
LLVM_DEBUG(dbgs() << "interpretFunction() called\n");
ScopedNativeDepthTracker depthTracker{runtime};
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
if (!SingleStep) {
if (auto jitPtr = runtime->jitContext_.compile(runtime, curCodeBlock)) {
return (*jitPtr)(runtime);
}
}
GCScope gcScope(runtime);
// Avoid allocating a handle dynamically by reusing this one.
MutableHandle<> tmpHandle(runtime);
CallResult<HermesValue> res{ExecutionStatus::EXCEPTION};
CallResult<PseudoHandle<>> resPH{ExecutionStatus::EXCEPTION};
CallResult<Handle<Arguments>> resArgs{ExecutionStatus::EXCEPTION};
CallResult<bool> boolRes{ExecutionStatus::EXCEPTION};
// Mark the gcScope so we can clear all allocated handles.
// Remember how many handles the scope has so we can clear them in the loop.
static constexpr unsigned KEEP_HANDLES = 1;
assert(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"scope has unexpected number of handles");
INIT_OPCODE_PROFILER;
#if !defined(HERMESVM_PROFILER_EXTERN)
tailCall:
#endif
PROFILER_ENTER_FUNCTION(curCodeBlock);
#ifdef HERMES_ENABLE_DEBUGGER
runtime->getDebugger().willEnterCodeBlock(curCodeBlock);
#endif
runtime->getCodeCoverageProfiler().markExecuted(runtime, curCodeBlock);
// Update function executionCount_ count
curCodeBlock->incrementExecutionCount();
if (!SingleStep) {
auto newFrame = runtime->setCurrentFrameToTopOfStack();
runtime->saveCallerIPInStackFrame();
#ifndef NDEBUG
runtime->invalidateCurrentIP();
#endif
// Point frameRegs to the first register in the new frame. Note that at this
// moment technically it points above the top of the stack, but we are never
// going to access it.
frameRegs = &newFrame.getFirstLocalRef();
#ifndef NDEBUG
LLVM_DEBUG(
dbgs() << "function entry: stackLevel=" << runtime->getStackLevel()
<< ", argCount=" << runtime->getCurrentFrame().getArgCount()
<< ", frameSize=" << curCodeBlock->getFrameSize() << "\n");
LLVM_DEBUG(
dbgs() << " callee "
<< DumpHermesValue(
runtime->getCurrentFrame().getCalleeClosureOrCBRef())
<< "\n");
LLVM_DEBUG(
dbgs() << " this "
<< DumpHermesValue(runtime->getCurrentFrame().getThisArgRef())
<< "\n");
for (uint32_t i = 0; i != runtime->getCurrentFrame()->getArgCount(); ++i) {
LLVM_DEBUG(
dbgs() << " " << llvh::format_decimal(i, 4) << " "
<< DumpHermesValue(runtime->getCurrentFrame().getArgRef(i))
<< "\n");
}
#endif
// Allocate the registers for the new frame.
if (LLVM_UNLIKELY(!runtime->checkAndAllocStack(
curCodeBlock->getFrameSize() +
StackFrameLayout::CalleeExtraRegistersAtStart,
HermesValue::encodeUndefinedValue())))
goto stackOverflow;
ip = (Inst const *)curCodeBlock->begin();
// Check for invalid invocation.
if (LLVM_UNLIKELY(curCodeBlock->getHeaderFlags().isCallProhibited(
newFrame.isConstructorCall()))) {
if (!newFrame.isConstructorCall()) {
CAPTURE_IP(
runtime->raiseTypeError("Class constructor invoked without new"));
} else {
CAPTURE_IP(runtime->raiseTypeError("Function is not a constructor"));
}
goto handleExceptionInParent;
}
} else {
// Point frameRegs to the first register in the frame.
frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();
ip = (Inst const *)(curCodeBlock->begin() + state.offset);
}
assert((const uint8_t *)ip < curCodeBlock->end() && "CodeBlock is empty");
INIT_STATE_FOR_CODEBLOCK(curCodeBlock);
#define BEFORE_OP_CODE \
{ \
UPDATE_OPCODE_TIME_SPENT; \
HERMES_SLOW_ASSERT( \
curCodeBlock->contains(ip) && "curCodeBlock must contain ip"); \
HERMES_SLOW_ASSERT((printDebugInfo(curCodeBlock, frameRegs, ip), true)); \
HERMES_SLOW_ASSERT( \
gcScope.getHandleCountDbg() == KEEP_HANDLES && \
"unaccounted handles were created"); \
HERMES_SLOW_ASSERT(tmpHandle->isUndefined() && "tmpHandle not cleared"); \
RECORD_OPCODE_START_TIME; \
INC_OPCODE_COUNT; \
}
#ifdef HERMESVM_INDIRECT_THREADING
static void *opcodeDispatch[] = {
#define DEFINE_OPCODE(name) &&case_##name,
#include "hermes/BCGen/HBC/BytecodeList.def"
&&case__last};
#define CASE(name) case_##name:
#define DISPATCH \
BEFORE_OP_CODE; \
if (SingleStep) { \
state.codeBlock = curCodeBlock; \
state.offset = CUROFFSET; \
return HermesValue::encodeUndefinedValue(); \
} \
goto *opcodeDispatch[(unsigned)ip->opCode]
#else // HERMESVM_INDIRECT_THREADING
#define CASE(name) case OpCode::name:
#define DISPATCH \
if (SingleStep) { \
state.codeBlock = curCodeBlock; \
state.offset = CUROFFSET; \
return HermesValue::encodeUndefinedValue(); \
} \
continue
#endif // HERMESVM_INDIRECT_THREADING
#define RUN_DEBUGGER_ASYNC_BREAK(flags) \
do { \
CAPTURE_IP_ASSIGN( \
auto dRes, \
runDebuggerUpdatingState( \
(uint8_t)(flags) & \
(uint8_t)Runtime::AsyncBreakReasonBits::DebuggerExplicit \
? Debugger::RunReason::AsyncBreakExplicit \
: Debugger::RunReason::AsyncBreakImplicit, \
runtime, \
curCodeBlock, \
ip, \
frameRegs)); \
if (dRes == ExecutionStatus::EXCEPTION) \
goto exception; \
} while (0)
for (;;) {
BEFORE_OP_CODE;
#ifdef HERMESVM_INDIRECT_THREADING
goto *opcodeDispatch[(unsigned)ip->opCode];
#else
switch (ip->opCode)
#endif
{
const Inst *nextIP;
uint32_t idVal;
bool tryProp;
uint32_t callArgCount;
// This is HermesValue::getRaw(), since HermesValue cannot be assigned
// to. It is meant to be used only for very short durations, in the
// dispatch of call instructions, when there is definitely no possibility
// of a GC.
HermesValue::RawType callNewTarget;
/// Handle an opcode \p name with an out-of-line implementation in a function
/// ExecutionStatus caseName(
/// Runtime *,
/// PinnedHermesValue *frameRegs,
/// Inst *ip)
#define CASE_OUTOFLINE(name) \
CASE(name) { \
CAPTURE_IP_ASSIGN(auto res, case##name(runtime, frameRegs, ip)); \
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { \
goto exception; \
} \
gcScope.flushToSmallCount(KEEP_HANDLES); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a binary arithmetic instruction with a fast path where both
/// operands are numbers.
/// \param name the name of the instruction. The fast path case will have a
/// "n" appended to the name.
/// \param oper the C++ operator to use to actually perform the arithmetic
/// operation.
#define BINOP(name, oper) \
CASE(name) { \
if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \
/* Fast-path. */ \
CASE(name##N) { \
O1REG(name) = HermesValue::encodeDoubleValue( \
oper(O2REG(name).getNumber(), O3REG(name).getNumber())); \
ip = NEXTINST(name); \
DISPATCH; \
} \
} \
CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) \
goto exception; \
double left = res->getDouble(); \
CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) \
goto exception; \
O1REG(name) = \
HermesValue::encodeDoubleValue(oper(left, res->getDouble())); \
gcScope.flushToSmallCount(KEEP_HANDLES); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a shift instruction with a fast path where both
/// operands are numbers.
/// \param name the name of the instruction.
/// \param oper the C++ operator to use to actually perform the shift
/// operation.
/// \param lConv the conversion function for the LHS of the expression.
/// \param lType the type of the LHS operand.
/// \param returnType the type of the return value.
#define SHIFTOP(name, oper, lConv, lType, returnType) \
CASE(name) { \
if (LLVM_LIKELY( \
O2REG(name).isNumber() && \
O3REG(name).isNumber())) { /* Fast-path. */ \
auto lnum = static_cast<lType>( \
hermes::truncateToInt32(O2REG(name).getNumber())); \
auto rnum = static_cast<uint32_t>( \
hermes::truncateToInt32(O3REG(name).getNumber())) & \
0x1f; \
O1REG(name) = HermesValue::encodeDoubleValue( \
static_cast<returnType>(lnum oper rnum)); \
ip = NEXTINST(name); \
DISPATCH; \
} \
CAPTURE_IP_ASSIGN(res, lConv(runtime, Handle<>(&O2REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
auto lnum = static_cast<lType>(res->getNumber()); \
CAPTURE_IP_ASSIGN(res, toUInt32_RJS(runtime, Handle<>(&O3REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
auto rnum = static_cast<uint32_t>(res->getNumber()) & 0x1f; \
gcScope.flushToSmallCount(KEEP_HANDLES); \
O1REG(name) = HermesValue::encodeDoubleValue( \
static_cast<returnType>(lnum oper rnum)); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a binary bitwise instruction with a fast path where both
/// operands are numbers.
/// \param name the name of the instruction.
/// \param oper the C++ operator to use to actually perform the bitwise
/// operation.
#define BITWISEBINOP(name, oper) \
CASE(name) { \
if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \
/* Fast-path. */ \
O1REG(name) = HermesValue::encodeDoubleValue( \
hermes::truncateToInt32(O2REG(name).getNumber()) \
oper hermes::truncateToInt32(O3REG(name).getNumber())); \
ip = NEXTINST(name); \
DISPATCH; \
} \
CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
int32_t left = res->getNumberAs<int32_t>(); \
CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O3REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
O1REG(name) = \
HermesValue::encodeNumberValue(left oper res->getNumberAs<int32_t>()); \
gcScope.flushToSmallCount(KEEP_HANDLES); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a comparison instruction.
/// \param name the name of the instruction.
/// \param oper the C++ operator to use to actually perform the fast arithmetic
/// comparison.
/// \param operFuncName function to call for the slow-path comparison.
#define CONDOP(name, oper, operFuncName) \
CASE(name) { \
if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \
/* Fast-path. */ \
O1REG(name) = HermesValue::encodeBoolValue( \
O2REG(name).getNumber() oper O3REG(name).getNumber()); \
ip = NEXTINST(name); \
DISPATCH; \
} \
CAPTURE_IP_ASSIGN( \
boolRes, \
operFuncName( \
runtime, Handle<>(&O2REG(name)), Handle<>(&O3REG(name)))); \
if (boolRes == ExecutionStatus::EXCEPTION) \
goto exception; \
gcScope.flushToSmallCount(KEEP_HANDLES); \
O1REG(name) = HermesValue::encodeBoolValue(boolRes.getValue()); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a comparison conditional jump with a fast path where both
/// operands are numbers.
/// \param name the name of the instruction. The fast path case will have a
/// "N" appended to the name.
/// \param suffix Optional suffix to be added to the end (e.g. Long)
/// \param oper the C++ operator to use to actually perform the fast arithmetic
/// comparison.
/// \param operFuncName function to call for the slow-path comparison.
/// \param trueDest ip value if the conditional evaluates to true
/// \param falseDest ip value if the conditional evaluates to false
#define JCOND_IMPL(name, suffix, oper, operFuncName, trueDest, falseDest) \
CASE(name##suffix) { \
if (LLVM_LIKELY( \
O2REG(name##suffix).isNumber() && \
O3REG(name##suffix).isNumber())) { \
/* Fast-path. */ \
CASE(name##N##suffix) { \
if (O2REG(name##N##suffix) \
.getNumber() oper O3REG(name##N##suffix) \
.getNumber()) { \
ip = trueDest; \
DISPATCH; \
} \
ip = falseDest; \
DISPATCH; \
} \
} \
CAPTURE_IP_ASSIGN( \
boolRes, \
operFuncName( \
runtime, \
Handle<>(&O2REG(name##suffix)), \
Handle<>(&O3REG(name##suffix)))); \
if (boolRes == ExecutionStatus::EXCEPTION) \
goto exception; \
gcScope.flushToSmallCount(KEEP_HANDLES); \
if (boolRes.getValue()) { \
ip = trueDest; \
DISPATCH; \
} \
ip = falseDest; \
DISPATCH; \
}
/// Implement a strict equality conditional jump
/// \param name the name of the instruction.
/// \param suffix Optional suffix to be added to the end (e.g. Long)
/// \param trueDest ip value if the conditional evaluates to true
/// \param falseDest ip value if the conditional evaluates to false
#define JCOND_STRICT_EQ_IMPL(name, suffix, trueDest, falseDest) \
CASE(name##suffix) { \
if (strictEqualityTest(O2REG(name##suffix), O3REG(name##suffix))) { \
ip = trueDest; \
DISPATCH; \
} \
ip = falseDest; \
DISPATCH; \
}
/// Implement an equality conditional jump
/// \param name the name of the instruction.
/// \param suffix Optional suffix to be added to the end (e.g. Long)
/// \param trueDest ip value if the conditional evaluates to true
/// \param falseDest ip value if the conditional evaluates to false
#define JCOND_EQ_IMPL(name, suffix, trueDest, falseDest) \
CASE(name##suffix) { \
CAPTURE_IP_ASSIGN( \
res, \
abstractEqualityTest_RJS( \
runtime, \
Handle<>(&O2REG(name##suffix)), \
Handle<>(&O3REG(name##suffix)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
gcScope.flushToSmallCount(KEEP_HANDLES); \
if (res->getBool()) { \
ip = trueDest; \
DISPATCH; \
} \
ip = falseDest; \
DISPATCH; \
}
/// Implement the long and short forms of a conditional jump, and its negation.
#define JCOND(name, oper, operFuncName) \
JCOND_IMPL( \
J##name, \
, \
oper, \
operFuncName, \
IPADD(ip->iJ##name.op1), \
NEXTINST(J##name)); \
JCOND_IMPL( \
J##name, \
Long, \
oper, \
operFuncName, \
IPADD(ip->iJ##name##Long.op1), \
NEXTINST(J##name##Long)); \
JCOND_IMPL( \
JNot##name, \
, \
oper, \
operFuncName, \
NEXTINST(JNot##name), \
IPADD(ip->iJNot##name.op1)); \
JCOND_IMPL( \
JNot##name, \
Long, \
oper, \
operFuncName, \
NEXTINST(JNot##name##Long), \
IPADD(ip->iJNot##name##Long.op1));
/// Load a constant.
/// \param value is the value to store in the output register.
#define LOAD_CONST(name, value) \
CASE(name) { \
O1REG(name) = value; \
ip = NEXTINST(name); \
DISPATCH; \
}
#define LOAD_CONST_CAPTURE_IP(name, value) \
CASE(name) { \
CAPTURE_IP_ASSIGN(O1REG(name), value); \
ip = NEXTINST(name); \
DISPATCH; \
}
CASE(Mov) {
O1REG(Mov) = O2REG(Mov);
ip = NEXTINST(Mov);
DISPATCH;
}
CASE(MovLong) {
O1REG(MovLong) = O2REG(MovLong);
ip = NEXTINST(MovLong);
DISPATCH;
}
CASE(LoadParam) {
if (LLVM_LIKELY(ip->iLoadParam.op2 <= FRAME.getArgCount())) {
// index 0 must load 'this'. Index 1 the first argument, etc.
O1REG(LoadParam) = FRAME.getArgRef((int32_t)ip->iLoadParam.op2 - 1);
ip = NEXTINST(LoadParam);
DISPATCH;
}
O1REG(LoadParam) = HermesValue::encodeUndefinedValue();
ip = NEXTINST(LoadParam);
DISPATCH;
}
CASE(LoadParamLong) {
if (LLVM_LIKELY(ip->iLoadParamLong.op2 <= FRAME.getArgCount())) {
// index 0 must load 'this'. Index 1 the first argument, etc.
O1REG(LoadParamLong) =
FRAME.getArgRef((int32_t)ip->iLoadParamLong.op2 - 1);
ip = NEXTINST(LoadParamLong);
DISPATCH;
}
O1REG(LoadParamLong) = HermesValue::encodeUndefinedValue();
ip = NEXTINST(LoadParamLong);
DISPATCH;
}
CASE(CoerceThisNS) {
if (LLVM_LIKELY(O2REG(CoerceThisNS).isObject())) {
O1REG(CoerceThisNS) = O2REG(CoerceThisNS);
} else if (
O2REG(CoerceThisNS).isNull() || O2REG(CoerceThisNS).isUndefined()) {
O1REG(CoerceThisNS) = runtime->global_;
} else {
tmpHandle = O2REG(CoerceThisNS);
nextIP = NEXTINST(CoerceThisNS);
goto coerceThisSlowPath;
}
ip = NEXTINST(CoerceThisNS);
DISPATCH;
}
CASE(LoadThisNS) {
if (LLVM_LIKELY(FRAME.getThisArgRef().isObject())) {
O1REG(LoadThisNS) = FRAME.getThisArgRef();
} else if (
FRAME.getThisArgRef().isNull() ||
FRAME.getThisArgRef().isUndefined()) {
O1REG(LoadThisNS) = runtime->global_;
} else {
tmpHandle = FRAME.getThisArgRef();
nextIP = NEXTINST(LoadThisNS);
goto coerceThisSlowPath;
}
ip = NEXTINST(LoadThisNS);
DISPATCH;
}
coerceThisSlowPath : {
CAPTURE_IP_ASSIGN(res, toObject(runtime, tmpHandle));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CoerceThisNS) = res.getValue();
tmpHandle.clear();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(ConstructLong) {
callArgCount = (uint32_t)ip->iConstructLong.op3;
nextIP = NEXTINST(ConstructLong);
callNewTarget = O2REG(ConstructLong).getRaw();
goto doCall;
}
CASE(CallLong) {
callArgCount = (uint32_t)ip->iCallLong.op3;
nextIP = NEXTINST(CallLong);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
// Note in Call1 through Call4, the first argument is 'this' which has
// argument index -1.
// Also note that we are writing to callNewTarget last, to avoid the
// possibility of it being aliased by the arg writes.
CASE(Call1) {
callArgCount = 1;
nextIP = NEXTINST(Call1);
StackFramePtr fr{runtime->stackPointer_};
fr.getArgRefUnsafe(-1) = O3REG(Call1);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
CASE(Call2) {
callArgCount = 2;
nextIP = NEXTINST(Call2);
StackFramePtr fr{runtime->stackPointer_};
fr.getArgRefUnsafe(-1) = O3REG(Call2);
fr.getArgRefUnsafe(0) = O4REG(Call2);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
CASE(Call3) {
callArgCount = 3;
nextIP = NEXTINST(Call3);
StackFramePtr fr{runtime->stackPointer_};
fr.getArgRefUnsafe(-1) = O3REG(Call3);
fr.getArgRefUnsafe(0) = O4REG(Call3);
fr.getArgRefUnsafe(1) = O5REG(Call3);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
CASE(Call4) {
callArgCount = 4;
nextIP = NEXTINST(Call4);
StackFramePtr fr{runtime->stackPointer_};
fr.getArgRefUnsafe(-1) = O3REG(Call4);
fr.getArgRefUnsafe(0) = O4REG(Call4);
fr.getArgRefUnsafe(1) = O5REG(Call4);
fr.getArgRefUnsafe(2) = O6REG(Call4);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
CASE(Construct) {
callArgCount = (uint32_t)ip->iConstruct.op3;
nextIP = NEXTINST(Construct);
callNewTarget = O2REG(Construct).getRaw();
goto doCall;
}
CASE(Call) {
callArgCount = (uint32_t)ip->iCall.op3;
nextIP = NEXTINST(Call);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
// Fall through.
}
doCall : {
#ifdef HERMES_ENABLE_DEBUGGER
// Check for an async debugger request.
if (uint8_t asyncFlags =
runtime->testAndClearDebuggerAsyncBreakRequest()) {
RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);
gcScope.flushToSmallCount(KEEP_HANDLES);
DISPATCH;
}
#endif
// Subtract 1 from callArgCount as 'this' is considered an argument in the
// instruction, but not in the frame.
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
auto newFrame,
StackFramePtr::initFrame(
runtime->stackPointer_,
FRAME,
ip,
curCodeBlock,
callArgCount - 1,
O2REG(Call),
HermesValue::fromRaw(callNewTarget)));
(void)newFrame;
SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));
if (auto *func = dyn_vmcast<JSFunction>(O2REG(Call))) {
assert(!SingleStep && "can't single-step a call");
#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES
runtime->pushCallStack(curCodeBlock, ip);
#endif
CodeBlock *calleeBlock = func->getCodeBlock();
calleeBlock->lazyCompile(runtime);
#if defined(HERMESVM_PROFILER_EXTERN)
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
res, runtime->interpretFunction(calleeBlock));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(Call) = *res;
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
#else
if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {
res = (*jitPtr)(runtime);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
goto exception;
O1REG(Call) = *res;
SLOW_DEBUG(
dbgs() << "JIT return value r" << (unsigned)ip->iCall.op1 << "="
<< DumpHermesValue(O1REG(Call)) << "\n");
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
curCodeBlock = calleeBlock;
goto tailCall;
#endif
}
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
resPH, Interpreter::handleCallSlowPath(runtime, &O2REG(Call)));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(Call) = std::move(resPH->get());
SLOW_DEBUG(
dbgs() << "native return value r" << (unsigned)ip->iCall.op1 << "="
<< DumpHermesValue(O1REG(Call)) << "\n");
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(CallDirect)
CASE(CallDirectLongIndex) {
#ifdef HERMES_ENABLE_DEBUGGER
// Check for an async debugger request.
if (uint8_t asyncFlags =
runtime->testAndClearDebuggerAsyncBreakRequest()) {
RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);
gcScope.flushToSmallCount(KEEP_HANDLES);
DISPATCH;
}
#endif
CAPTURE_IP_ASSIGN(
CodeBlock * calleeBlock,
ip->opCode == OpCode::CallDirect
? curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(
ip->iCallDirect.op3)
: curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(
ip->iCallDirectLongIndex.op3));
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
auto newFrame,
StackFramePtr::initFrame(
runtime->stackPointer_,
FRAME,
ip,
curCodeBlock,
(uint32_t)ip->iCallDirect.op2 - 1,
HermesValue::encodeNativePointer(calleeBlock),
HermesValue::encodeUndefinedValue()));
(void)newFrame;
LLVM_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));
assert(!SingleStep && "can't single-step a call");
calleeBlock->lazyCompile(runtime);
#if defined(HERMESVM_PROFILER_EXTERN)
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
res, runtime->interpretFunction(calleeBlock));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CallDirect) = *res;
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)
: NEXTINST(CallDirectLongIndex);
DISPATCH;
#else
if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {
res = (*jitPtr)(runtime);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
goto exception;
O1REG(CallDirect) = *res;
LLVM_DEBUG(
dbgs() << "JIT return value r" << (unsigned)ip->iCallDirect.op1
<< "=" << DumpHermesValue(O1REG(Call)) << "\n");
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)
: NEXTINST(CallDirectLongIndex);
DISPATCH;
}
curCodeBlock = calleeBlock;
goto tailCall;
#endif
}
CASE(CallBuiltin) {
NativeFunction *nf =
runtime->getBuiltinNativeFunction(ip->iCallBuiltin.op2);
CAPTURE_IP_ASSIGN(
auto newFrame,
StackFramePtr::initFrame(
runtime->stackPointer_,
FRAME,
ip,
curCodeBlock,
(uint32_t)ip->iCallBuiltin.op3 - 1,
nf,
false));
// "thisArg" is implicitly assumed to "undefined".
newFrame.getThisArgRef() = HermesValue::encodeUndefinedValue();
SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));
CAPTURE_IP_ASSIGN(resPH, NativeFunction::_nativeCall(nf, runtime));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION))
goto exception;
O1REG(CallBuiltin) = std::move(resPH->get());
SLOW_DEBUG(
dbgs() << "native return value r" << (unsigned)ip->iCallBuiltin.op1
<< "=" << DumpHermesValue(O1REG(CallBuiltin)) << "\n");
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CallBuiltin);
DISPATCH;
}
CASE(CompleteGenerator) {
auto *innerFn = vmcast<GeneratorInnerFunction>(
runtime->getCurrentFrame().getCalleeClosure());
innerFn->setState(GeneratorInnerFunction::State::Completed);
ip = NEXTINST(CompleteGenerator);
DISPATCH;
}
CASE(SaveGenerator) {
DONT_CAPTURE_IP(
saveGenerator(runtime, frameRegs, IPADD(ip->iSaveGenerator.op1)));
ip = NEXTINST(SaveGenerator);
DISPATCH;
}
CASE(SaveGeneratorLong) {
DONT_CAPTURE_IP(saveGenerator(
runtime, frameRegs, IPADD(ip->iSaveGeneratorLong.op1)));
ip = NEXTINST(SaveGeneratorLong);
DISPATCH;
}
CASE(StartGenerator) {
auto *innerFn = vmcast<GeneratorInnerFunction>(
runtime->getCurrentFrame().getCalleeClosure());
if (innerFn->getState() ==
GeneratorInnerFunction::State::SuspendedStart) {
nextIP = NEXTINST(StartGenerator);
} else {
nextIP = innerFn->getNextIP();
innerFn->restoreStack(runtime);
}
innerFn->setState(GeneratorInnerFunction::State::Executing);
ip = nextIP;
DISPATCH;
}
CASE(ResumeGenerator) {
auto *innerFn = vmcast<GeneratorInnerFunction>(
runtime->getCurrentFrame().getCalleeClosure());
O1REG(ResumeGenerator) = innerFn->getResult();
O2REG(ResumeGenerator) = HermesValue::encodeBoolValue(
innerFn->getAction() == GeneratorInnerFunction::Action::Return);
innerFn->clearResult(runtime);
if (innerFn->getAction() == GeneratorInnerFunction::Action::Throw) {
runtime->setThrownValue(O1REG(ResumeGenerator));
goto exception;
}
ip = NEXTINST(ResumeGenerator);
DISPATCH;
}
CASE(Ret) {
#ifdef HERMES_ENABLE_DEBUGGER
// Check for an async debugger request.
if (uint8_t asyncFlags =
runtime->testAndClearDebuggerAsyncBreakRequest()) {
RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);
gcScope.flushToSmallCount(KEEP_HANDLES);
DISPATCH;
}
#endif
PROFILER_EXIT_FUNCTION(curCodeBlock);
#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES
runtime->popCallStack();
#endif
// Store the return value.
res = O1REG(Ret);
ip = FRAME.getSavedIP();
curCodeBlock = FRAME.getSavedCodeBlock();
frameRegs =
&runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();
SLOW_DEBUG(
dbgs() << "function exit: restored stackLevel="
<< runtime->getStackLevel() << "\n");
// Are we returning to native code?
if (!curCodeBlock) {
SLOW_DEBUG(dbgs() << "function exit: returning to native code\n");
return res;
}
// Return because of recursive calling structure
#if defined(HERMESVM_PROFILER_EXTERN)
return res;
#endif
INIT_STATE_FOR_CODEBLOCK(curCodeBlock);
O1REG(Call) = res.getValue();
ip = nextInstCall(ip);
DISPATCH;
}
CASE(Catch) {
assert(!runtime->thrownValue_.isEmpty() && "Invalid thrown value");
assert(
!isUncatchableError(runtime->thrownValue_) &&
"Uncatchable thrown value was caught");
O1REG(Catch) = runtime->thrownValue_;
runtime->clearThrownValue();
#ifdef HERMES_ENABLE_DEBUGGER
// Signal to the debugger that we're done unwinding an exception,
// and we can resume normal debugging flow.
runtime->debugger_.finishedUnwindingException();
#endif
ip = NEXTINST(Catch);
DISPATCH;
}
CASE(Throw) {
runtime->thrownValue_ = O1REG(Throw);
SLOW_DEBUG(
dbgs() << "Exception thrown: "
<< DumpHermesValue(runtime->thrownValue_) << "\n");
goto exception;
}
CASE(ThrowIfUndefinedInst) {
if (LLVM_UNLIKELY(O1REG(ThrowIfUndefinedInst).isUndefined())) {
SLOW_DEBUG(
dbgs() << "Throwing ReferenceError for undefined variable");
CAPTURE_IP(runtime->raiseReferenceError(
"accessing an uninitialized variable"));
goto exception;
}
ip = NEXTINST(ThrowIfUndefinedInst);
DISPATCH;
}
CASE(Debugger) {
SLOW_DEBUG(dbgs() << "debugger statement executed\n");
#ifdef HERMES_ENABLE_DEBUGGER
{
if (!runtime->debugger_.isDebugging()) {
// Only run the debugger if we're not already debugging.
// Don't want to call it again and mess with its state.
CAPTURE_IP_ASSIGN(
auto res,
runDebuggerUpdatingState(
Debugger::RunReason::Opcode,
runtime,
curCodeBlock,
ip,
frameRegs));
if (res == ExecutionStatus::EXCEPTION) {
// If one of the internal steps threw,
// then handle that here by jumping to where we're supposed to go.
// If we're in mid-step, the breakpoint at the catch point
// will have been set by the debugger.
// We don't want to execute this instruction because it's already
// thrown.
goto exception;
}
}
auto breakpointOpt = runtime->debugger_.getBreakpointLocation(ip);
if (breakpointOpt.hasValue()) {
// We're on a breakpoint but we're supposed to continue.
curCodeBlock->uninstallBreakpointAtOffset(
CUROFFSET, breakpointOpt->opCode);
if (ip->opCode == OpCode::Debugger) {
// Breakpointed a debugger instruction, so move past it
// since we've already called the debugger on this instruction.
ip = NEXTINST(Debugger);
} else {
InterpreterState newState{curCodeBlock, (uint32_t)CUROFFSET};
CAPTURE_IP_ASSIGN(
ExecutionStatus status, runtime->stepFunction(newState));
curCodeBlock->installBreakpointAtOffset(CUROFFSET);
if (status == ExecutionStatus::EXCEPTION) {
goto exception;
}
curCodeBlock = newState.codeBlock;
ip = newState.codeBlock->getOffsetPtr(newState.offset);
INIT_STATE_FOR_CODEBLOCK(curCodeBlock);
// Single-stepping should handle call stack management for us.
frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();
}
} else if (ip->opCode == OpCode::Debugger) {
// No breakpoint here and we've already run the debugger,
// just continue on.
// If the current instruction is no longer a debugger instruction,
// we're just going to keep executing from the current IP.
ip = NEXTINST(Debugger);
}
gcScope.flushToSmallCount(KEEP_HANDLES);
}
DISPATCH;
#else
ip = NEXTINST(Debugger);
DISPATCH;
#endif
}
CASE(AsyncBreakCheck) {
if (LLVM_UNLIKELY(runtime->hasAsyncBreak())) {
#ifdef HERMES_ENABLE_DEBUGGER
if (uint8_t asyncFlags =
runtime->testAndClearDebuggerAsyncBreakRequest()) {
RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);
}
#endif
if (runtime->testAndClearTimeoutAsyncBreakRequest()) {
CAPTURE_IP_ASSIGN(auto nRes, runtime->notifyTimeout());
if (nRes == ExecutionStatus::EXCEPTION) {
goto exception;
}
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(AsyncBreakCheck);
DISPATCH;
}
CASE(ProfilePoint) {
#ifdef HERMESVM_PROFILER_BB
auto pointIndex = ip->iProfilePoint.op1;
SLOW_DEBUG(llvh::dbgs() << "ProfilePoint: " << pointIndex << "\n");
CAPTURE_IP(runtime->getBasicBlockExecutionInfo().executeBlock(
curCodeBlock, pointIndex));
#endif
ip = NEXTINST(ProfilePoint);
DISPATCH;
}
CASE(Unreachable) {
llvm_unreachable("Hermes bug: unreachable instruction");
}
CASE(CreateClosure) {
idVal = ip->iCreateClosure.op3;
nextIP = NEXTINST(CreateClosure);
goto createClosure;
}
CASE(CreateClosureLongIndex) {
idVal = ip->iCreateClosureLongIndex.op3;
nextIP = NEXTINST(CreateClosureLongIndex);
goto createClosure;
}
createClosure : {
auto *runtimeModule = curCodeBlock->getRuntimeModule();
CAPTURE_IP_ASSIGN(
O1REG(CreateClosure),
JSFunction::create(
runtime,
runtimeModule->getDomain(runtime),
Handle<JSObject>::vmcast(&runtime->functionPrototype),
Handle<Environment>::vmcast(&O2REG(CreateClosure)),
runtimeModule->getCodeBlockMayAllocate(idVal))
.getHermesValue());
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(CreateGeneratorClosure) {
CAPTURE_IP_ASSIGN(
auto res,
createGeneratorClosure(
runtime,
curCodeBlock->getRuntimeModule(),
ip->iCreateClosure.op3,
Handle<Environment>::vmcast(&O2REG(CreateGeneratorClosure))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CreateGeneratorClosure) = res->getHermesValue();
res->invalidate();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateGeneratorClosure);
DISPATCH;
}
CASE(CreateGeneratorClosureLongIndex) {
CAPTURE_IP_ASSIGN(
auto res,
createGeneratorClosure(
runtime,
curCodeBlock->getRuntimeModule(),
ip->iCreateClosureLongIndex.op3,
Handle<Environment>::vmcast(
&O2REG(CreateGeneratorClosureLongIndex))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CreateGeneratorClosureLongIndex) = res->getHermesValue();
res->invalidate();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateGeneratorClosureLongIndex);
DISPATCH;
}
CASE(CreateGenerator) {
CAPTURE_IP_ASSIGN(
auto res,
createGenerator_RJS(
runtime,
curCodeBlock->getRuntimeModule(),
ip->iCreateGenerator.op3,
Handle<Environment>::vmcast(&O2REG(CreateGenerator)),
FRAME.getNativeArgs()));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CreateGenerator) = res->getHermesValue();
res->invalidate();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateGenerator);
DISPATCH;
}
CASE(CreateGeneratorLongIndex) {
CAPTURE_IP_ASSIGN(
auto res,
createGenerator_RJS(
runtime,
curCodeBlock->getRuntimeModule(),
ip->iCreateGeneratorLongIndex.op3,
Handle<Environment>::vmcast(&O2REG(CreateGeneratorLongIndex)),
FRAME.getNativeArgs()));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CreateGeneratorLongIndex) = res->getHermesValue();
res->invalidate();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateGeneratorLongIndex);
DISPATCH;
}
CASE(GetEnvironment) {
// The currently executing function must exist, so get the environment.
Environment *curEnv =
FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime);
for (unsigned level = ip->iGetEnvironment.op2; level; --level) {
assert(curEnv && "invalid environment relative level");
curEnv = curEnv->getParentEnvironment(runtime);
}
O1REG(GetEnvironment) = HermesValue::encodeObjectValue(curEnv);
ip = NEXTINST(GetEnvironment);
DISPATCH;
}
CASE(CreateEnvironment) {
tmpHandle = HermesValue::encodeObjectValue(
FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime));
CAPTURE_IP_ASSIGN(
res,
Environment::create(
runtime,
tmpHandle->getPointer() ? Handle<Environment>::vmcast(tmpHandle)
: Handle<Environment>::vmcast_or_null(
&runtime->nullPointer_),
curCodeBlock->getEnvironmentSize()));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
O1REG(CreateEnvironment) = *res;
#ifdef HERMES_ENABLE_DEBUGGER
FRAME.getDebugEnvironmentRef() = *res;
#endif
tmpHandle = HermesValue::encodeUndefinedValue();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateEnvironment);
DISPATCH;
}
CASE(StoreToEnvironment) {
vmcast<Environment>(O1REG(StoreToEnvironment))
->slot(ip->iStoreToEnvironment.op2)
.set(O3REG(StoreToEnvironment), &runtime->getHeap());
ip = NEXTINST(StoreToEnvironment);
DISPATCH;
}
CASE(StoreToEnvironmentL) {
vmcast<Environment>(O1REG(StoreToEnvironmentL))
->slot(ip->iStoreToEnvironmentL.op2)
.set(O3REG(StoreToEnvironmentL), &runtime->getHeap());
ip = NEXTINST(StoreToEnvironmentL);
DISPATCH;
}
CASE(StoreNPToEnvironment) {
vmcast<Environment>(O1REG(StoreNPToEnvironment))
->slot(ip->iStoreNPToEnvironment.op2)
.setNonPtr(O3REG(StoreNPToEnvironment), &runtime->getHeap());
ip = NEXTINST(StoreNPToEnvironment);
DISPATCH;
}
CASE(StoreNPToEnvironmentL) {
vmcast<Environment>(O1REG(StoreNPToEnvironmentL))
->slot(ip->iStoreNPToEnvironmentL.op2)
.setNonPtr(O3REG(StoreNPToEnvironmentL), &runtime->getHeap());
ip = NEXTINST(StoreNPToEnvironmentL);
DISPATCH;
}
CASE(LoadFromEnvironment) {
O1REG(LoadFromEnvironment) =
vmcast<Environment>(O2REG(LoadFromEnvironment))
->slot(ip->iLoadFromEnvironment.op3);
ip = NEXTINST(LoadFromEnvironment);
DISPATCH;
}
CASE(LoadFromEnvironmentL) {
O1REG(LoadFromEnvironmentL) =
vmcast<Environment>(O2REG(LoadFromEnvironmentL))
->slot(ip->iLoadFromEnvironmentL.op3);
ip = NEXTINST(LoadFromEnvironmentL);
DISPATCH;
}
CASE(GetGlobalObject) {
O1REG(GetGlobalObject) = runtime->global_;
ip = NEXTINST(GetGlobalObject);
DISPATCH;
}
CASE(GetNewTarget) {
O1REG(GetNewTarget) = FRAME.getNewTargetRef();
ip = NEXTINST(GetNewTarget);
DISPATCH;
}
CASE(DeclareGlobalVar) {
DefinePropertyFlags dpf =
DefinePropertyFlags::getDefaultNewPropertyFlags();
dpf.configurable = 0;
// Do not overwrite existing globals with undefined.
dpf.setValue = 0;
CAPTURE_IP_ASSIGN(
auto res,
JSObject::defineOwnProperty(
runtime->getGlobal(),
runtime,
ID(ip->iDeclareGlobalVar.op1),
dpf,
Runtime::getUndefinedValue(),
PropOpFlags().plusThrowOnError()));
if (res == ExecutionStatus::EXCEPTION) {
assert(
!runtime->getGlobal()->isProxyObject() &&
"global can't be a proxy object");
// If the property already exists, this should be a noop.
// Instead of incurring the cost to check every time, do it
// only if an exception is thrown, and swallow the exception
// if it exists, since we didn't want to make the call,
// anyway. This most likely means the property is
// non-configurable.
NamedPropertyDescriptor desc;
CAPTURE_IP_ASSIGN(
auto res,
JSObject::getOwnNamedDescriptor(
runtime->getGlobal(),
runtime,
ID(ip->iDeclareGlobalVar.op1),
desc));
if (!res) {
goto exception;
} else {
runtime->clearThrownValue();
}
// fall through
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(DeclareGlobalVar);
DISPATCH;
}
CASE(TryGetByIdLong) {
tryProp = true;
idVal = ip->iTryGetByIdLong.op4;
nextIP = NEXTINST(TryGetByIdLong);
goto getById;
}
CASE(GetByIdLong) {
tryProp = false;
idVal = ip->iGetByIdLong.op4;
nextIP = NEXTINST(GetByIdLong);
goto getById;
}
CASE(GetByIdShort) {
tryProp = false;
idVal = ip->iGetByIdShort.op4;
nextIP = NEXTINST(GetByIdShort);
goto getById;
}
CASE(TryGetById) {
tryProp = true;
idVal = ip->iTryGetById.op4;
nextIP = NEXTINST(TryGetById);
goto getById;
}
CASE(GetById) {
tryProp = false;
idVal = ip->iGetById.op4;
nextIP = NEXTINST(GetById);
}
getById : {
++NumGetById;
// NOTE: it is safe to use OnREG(GetById) here because all instructions
// have the same layout: opcode, registers, non-register operands, i.e.
// they only differ in the width of the last "identifier" field.
CallResult<HermesValue> propRes{ExecutionStatus::EXCEPTION};
if (LLVM_LIKELY(O2REG(GetById).isObject())) {
auto *obj = vmcast<JSObject>(O2REG(GetById));
auto cacheIdx = ip->iGetById.op3;
auto *cacheEntry = curCodeBlock->getReadCacheEntry(cacheIdx);
#ifdef HERMESVM_PROFILER_BB
{
HERMES_SLOW_ASSERT(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"unaccounted handles were created");
auto objHandle = runtime->makeHandle(obj);
auto cacheHCPtr = vmcast_or_null<HiddenClass>(static_cast<GCCell *>(
cacheEntry->clazz.get(runtime, &runtime->getHeap())));
CAPTURE_IP(runtime->recordHiddenClass(
curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));
// obj may be moved by GC due to recordHiddenClass
obj = objHandle.get();
}
gcScope.flushToSmallCount(KEEP_HANDLES);
#endif
auto clazzGCPtr = obj->getClassGCPtr();
#ifndef NDEBUG
if (clazzGCPtr.get(runtime)->isDictionary())
++NumGetByIdDict;
#else
(void)NumGetByIdDict;
#endif
// If we have a cache hit, reuse the cached offset and immediately
// return the property.
if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {
++NumGetByIdCacheHits;
CAPTURE_IP_ASSIGN(
O1REG(GetById),
JSObject::getNamedSlotValue<PropStorage::Inline::Yes>(
obj, runtime, cacheEntry->slot));
ip = nextIP;
DISPATCH;
}
auto id = ID(idVal);
NamedPropertyDescriptor desc;
CAPTURE_IP_ASSIGN(
OptValue<bool> fastPathResult,
JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));
if (LLVM_LIKELY(
fastPathResult.hasValue() && fastPathResult.getValue()) &&
!desc.flags.accessor) {
++NumGetByIdFastPaths;
// cacheIdx == 0 indicates no caching so don't update the cache in
// those cases.
auto *clazz = clazzGCPtr.getNonNull(runtime);
if (LLVM_LIKELY(!clazz->isDictionaryNoCache()) &&
LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {
#ifdef HERMES_SLOW_DEBUG
if (cacheEntry->clazz &&
cacheEntry->clazz != clazzGCPtr.getStorageType())
++NumGetByIdCacheEvicts;
#else
(void)NumGetByIdCacheEvicts;
#endif
// Cache the class, id and property slot.
cacheEntry->clazz = clazzGCPtr.getStorageType();
cacheEntry->slot = desc.slot;
}
CAPTURE_IP_ASSIGN(
O1REG(GetById), JSObject::getNamedSlotValue(obj, runtime, desc));
ip = nextIP;
DISPATCH;
}
// The cache may also be populated via the prototype of the object.
// This value is only reliable if the fast path was a definite
// not-found.
if (fastPathResult.hasValue() && !fastPathResult.getValue() &&
!obj->isProxyObject()) {
CAPTURE_IP_ASSIGN(JSObject * parent, obj->getParent(runtime));
// TODO: This isLazy check is because a lazy object is reported as
// having no properties and therefore cannot contain the property.
// This check does not belong here, it should be merged into
// tryGetOwnNamedDescriptorFast().
if (parent &&
cacheEntry->clazz == parent->getClassGCPtr().getStorageType() &&
LLVM_LIKELY(!obj->isLazy())) {
++NumGetByIdProtoHits;
CAPTURE_IP_ASSIGN(
O1REG(GetById),
JSObject::getNamedSlotValue(parent, runtime, cacheEntry->slot));
ip = nextIP;
DISPATCH;
}
}
#ifdef HERMES_SLOW_DEBUG
CAPTURE_IP_ASSIGN(
JSObject * propObj,
JSObject::getNamedDescriptor(
Handle<JSObject>::vmcast(&O2REG(GetById)), runtime, id, desc));
if (propObj) {
if (desc.flags.accessor)
++NumGetByIdAccessor;
else if (propObj != vmcast<JSObject>(O2REG(GetById)))
++NumGetByIdProto;
} else {
++NumGetByIdNotFound;
}
#else
(void)NumGetByIdAccessor;
(void)NumGetByIdProto;
(void)NumGetByIdNotFound;
#endif
#ifdef HERMES_SLOW_DEBUG
auto *savedClass = cacheIdx != hbc::PROPERTY_CACHING_DISABLED
? cacheEntry->clazz.get(runtime, &runtime->getHeap())
: nullptr;
#endif
++NumGetByIdSlow;
CAPTURE_IP_ASSIGN(
resPH,
JSObject::getNamed_RJS(
Handle<JSObject>::vmcast(&O2REG(GetById)),
runtime,
id,
!tryProp ? defaultPropOpFlags
: defaultPropOpFlags.plusMustExist(),
cacheIdx != hbc::PROPERTY_CACHING_DISABLED ? cacheEntry
: nullptr));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
#ifdef HERMES_SLOW_DEBUG
if (cacheIdx != hbc::PROPERTY_CACHING_DISABLED && savedClass &&
cacheEntry->clazz.get(runtime, &runtime->getHeap()) != savedClass) {
++NumGetByIdCacheEvicts;
}
#endif
} else {
++NumGetByIdTransient;
assert(!tryProp && "TryGetById can only be used on the global object");
/* Slow path. */
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::getByIdTransient_RJS(
runtime, Handle<>(&O2REG(GetById)), ID(idVal)));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
}
O1REG(GetById) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(TryPutByIdLong) {
tryProp = true;
idVal = ip->iTryPutByIdLong.op4;
nextIP = NEXTINST(TryPutByIdLong);
goto putById;
}
CASE(PutByIdLong) {
tryProp = false;
idVal = ip->iPutByIdLong.op4;
nextIP = NEXTINST(PutByIdLong);
goto putById;
}
CASE(TryPutById) {
tryProp = true;
idVal = ip->iTryPutById.op4;
nextIP = NEXTINST(TryPutById);
goto putById;
}
CASE(PutById) {
tryProp = false;
idVal = ip->iPutById.op4;
nextIP = NEXTINST(PutById);
}
putById : {
++NumPutById;
if (LLVM_LIKELY(O1REG(PutById).isObject())) {
auto *obj = vmcast<JSObject>(O1REG(PutById));
auto cacheIdx = ip->iPutById.op3;
auto *cacheEntry = curCodeBlock->getWriteCacheEntry(cacheIdx);
#ifdef HERMESVM_PROFILER_BB
{
HERMES_SLOW_ASSERT(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"unaccounted handles were created");
auto objHandle = runtime->makeHandle(obj);
auto cacheHCPtr = vmcast_or_null<HiddenClass>(static_cast<GCCell *>(
cacheEntry->clazz.get(runtime, &runtime->getHeap())));
CAPTURE_IP(runtime->recordHiddenClass(
curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));
// obj may be moved by GC due to recordHiddenClass
obj = objHandle.get();
}
gcScope.flushToSmallCount(KEEP_HANDLES);
#endif
auto clazzGCPtr = obj->getClassGCPtr();
// If we have a cache hit, reuse the cached offset and immediately
// return the property.
if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {
++NumPutByIdCacheHits;
CAPTURE_IP(JSObject::setNamedSlotValue<PropStorage::Inline::Yes>(
obj, runtime, cacheEntry->slot, O2REG(PutById)));
ip = nextIP;
DISPATCH;
}
auto id = ID(idVal);
NamedPropertyDescriptor desc;
CAPTURE_IP_ASSIGN(
OptValue<bool> hasOwnProp,
JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));
if (LLVM_LIKELY(hasOwnProp.hasValue() && hasOwnProp.getValue()) &&
!desc.flags.accessor && desc.flags.writable &&
!desc.flags.internalSetter) {
++NumPutByIdFastPaths;
// cacheIdx == 0 indicates no caching so don't update the cache in
// those cases.
auto *clazz = clazzGCPtr.getNonNull(runtime);
if (LLVM_LIKELY(!clazz->isDictionary()) &&
LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {
#ifdef HERMES_SLOW_DEBUG
if (cacheEntry->clazz &&
cacheEntry->clazz != clazzGCPtr.getStorageType())
++NumPutByIdCacheEvicts;
#else
(void)NumPutByIdCacheEvicts;
#endif
// Cache the class and property slot.
cacheEntry->clazz = clazzGCPtr.getStorageType();
cacheEntry->slot = desc.slot;
}
CAPTURE_IP(JSObject::setNamedSlotValue(
obj, runtime, desc.slot, O2REG(PutById)));
ip = nextIP;
DISPATCH;
}
CAPTURE_IP_ASSIGN(
auto putRes,
JSObject::putNamed_RJS(
Handle<JSObject>::vmcast(&O1REG(PutById)),
runtime,
id,
Handle<>(&O2REG(PutById)),
!tryProp ? defaultPropOpFlags
: defaultPropOpFlags.plusMustExist()));
if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {
goto exception;
}
} else {
++NumPutByIdTransient;
assert(!tryProp && "TryPutById can only be used on the global object");
CAPTURE_IP_ASSIGN(
auto retStatus,
Interpreter::putByIdTransient_RJS(
runtime,
Handle<>(&O1REG(PutById)),
ID(idVal),
Handle<>(&O2REG(PutById)),
strictMode));
if (retStatus == ExecutionStatus::EXCEPTION) {
goto exception;
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(GetByVal) {
CallResult<HermesValue> propRes{ExecutionStatus::EXCEPTION};
if (LLVM_LIKELY(O2REG(GetByVal).isObject())) {
CAPTURE_IP_ASSIGN(
resPH,
JSObject::getComputed_RJS(
Handle<JSObject>::vmcast(&O2REG(GetByVal)),
runtime,
Handle<>(&O3REG(GetByVal))));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
} else {
// This is the "slow path".
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::getByValTransient_RJS(
runtime,
Handle<>(&O2REG(GetByVal)),
Handle<>(&O3REG(GetByVal))));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(GetByVal) = resPH->get();
ip = NEXTINST(GetByVal);
DISPATCH;
}
CASE(PutByVal) {
if (LLVM_LIKELY(O1REG(PutByVal).isObject())) {
CAPTURE_IP_ASSIGN(
auto putRes,
JSObject::putComputed_RJS(
Handle<JSObject>::vmcast(&O1REG(PutByVal)),
runtime,
Handle<>(&O2REG(PutByVal)),
Handle<>(&O3REG(PutByVal)),
defaultPropOpFlags));
if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {
goto exception;
}
} else {
// This is the "slow path".
CAPTURE_IP_ASSIGN(
auto retStatus,
Interpreter::putByValTransient_RJS(
runtime,
Handle<>(&O1REG(PutByVal)),
Handle<>(&O2REG(PutByVal)),
Handle<>(&O3REG(PutByVal)),
strictMode));
if (LLVM_UNLIKELY(retStatus == ExecutionStatus::EXCEPTION)) {
goto exception;
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(PutByVal);
DISPATCH;
}
CASE(PutOwnByIndexL) {
nextIP = NEXTINST(PutOwnByIndexL);
idVal = ip->iPutOwnByIndexL.op3;
goto putOwnByIndex;
}
CASE(PutOwnByIndex) {
nextIP = NEXTINST(PutOwnByIndex);
idVal = ip->iPutOwnByIndex.op3;
}
putOwnByIndex : {
tmpHandle = HermesValue::encodeDoubleValue(idVal);
CAPTURE_IP(JSObject::defineOwnComputedPrimitive(
Handle<JSObject>::vmcast(&O1REG(PutOwnByIndex)),
runtime,
tmpHandle,
DefinePropertyFlags::getDefaultNewPropertyFlags(),
Handle<>(&O2REG(PutOwnByIndex))));
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = nextIP;
DISPATCH;
}
CASE(GetPNameList) {
CAPTURE_IP_ASSIGN(
auto pRes, handleGetPNameList(runtime, frameRegs, ip));
if (LLVM_UNLIKELY(pRes == ExecutionStatus::EXCEPTION)) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(GetPNameList);
DISPATCH;
}
CASE(GetNextPName) {
{
assert(
vmisa<BigStorage>(O2REG(GetNextPName)) &&
"GetNextPName's second op must be BigStorage");
auto obj = Handle<JSObject>::vmcast(&O3REG(GetNextPName));
auto arr = Handle<BigStorage>::vmcast(&O2REG(GetNextPName));
uint32_t idx = O4REG(GetNextPName).getNumber();
uint32_t size = O5REG(GetNextPName).getNumber();
MutableHandle<JSObject> propObj{runtime};
// Loop until we find a property which is present.
while (idx < size) {
tmpHandle = arr->at(idx);
ComputedPropertyDescriptor desc;
CAPTURE_IP(JSObject::getComputedPrimitiveDescriptor(
obj, runtime, tmpHandle, propObj, desc));
if (LLVM_LIKELY(propObj))
break;
++idx;
}
if (idx < size) {
// We must return the property as a string
if (tmpHandle->isNumber()) {
CAPTURE_IP_ASSIGN(auto status, toString_RJS(runtime, tmpHandle));
assert(
status == ExecutionStatus::RETURNED &&
"toString on number cannot fail");
tmpHandle = status->getHermesValue();
}
O1REG(GetNextPName) = tmpHandle.get();
O4REG(GetNextPName) = HermesValue::encodeNumberValue(idx + 1);
} else {
O1REG(GetNextPName) = HermesValue::encodeUndefinedValue();
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = NEXTINST(GetNextPName);
DISPATCH;
}
CASE(ToNumber) {
if (LLVM_LIKELY(O2REG(ToNumber).isNumber())) {
O1REG(ToNumber) = O2REG(ToNumber);
ip = NEXTINST(ToNumber);
} else {
CAPTURE_IP_ASSIGN(
res, toNumber_RJS(runtime, Handle<>(&O2REG(ToNumber))));
if (res == ExecutionStatus::EXCEPTION)
goto exception;
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(ToNumber) = res.getValue();
ip = NEXTINST(ToNumber);
}
DISPATCH;
}
CASE(ToInt32) {
CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(ToInt32))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
goto exception;
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(ToInt32) = res.getValue();
ip = NEXTINST(ToInt32);
DISPATCH;
}
CASE(AddEmptyString) {
if (LLVM_LIKELY(O2REG(AddEmptyString).isString())) {
O1REG(AddEmptyString) = O2REG(AddEmptyString);
ip = NEXTINST(AddEmptyString);
} else {
CAPTURE_IP_ASSIGN(
res,
toPrimitive_RJS(
runtime,
Handle<>(&O2REG(AddEmptyString)),
PreferredType::NONE));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
goto exception;
tmpHandle = res.getValue();
CAPTURE_IP_ASSIGN(auto strRes, toString_RJS(runtime, tmpHandle));
if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION))
goto exception;
tmpHandle.clear();
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(AddEmptyString) = strRes->getHermesValue();
ip = NEXTINST(AddEmptyString);
}
DISPATCH;
}
CASE(Jmp) {
ip = IPADD(ip->iJmp.op1);
DISPATCH;
}
CASE(JmpLong) {
ip = IPADD(ip->iJmpLong.op1);
DISPATCH;
}
CASE(JmpTrue) {
if (toBoolean(O2REG(JmpTrue)))
ip = IPADD(ip->iJmpTrue.op1);
else
ip = NEXTINST(JmpTrue);
DISPATCH;
}
CASE(JmpTrueLong) {
if (toBoolean(O2REG(JmpTrueLong)))
ip = IPADD(ip->iJmpTrueLong.op1);
else
ip = NEXTINST(JmpTrueLong);
DISPATCH;
}
CASE(JmpFalse) {
if (!toBoolean(O2REG(JmpFalse)))
ip = IPADD(ip->iJmpFalse.op1);
else
ip = NEXTINST(JmpFalse);
DISPATCH;
}
CASE(JmpFalseLong) {
if (!toBoolean(O2REG(JmpFalseLong)))
ip = IPADD(ip->iJmpFalseLong.op1);
else
ip = NEXTINST(JmpFalseLong);
DISPATCH;
}
CASE(JmpUndefined) {
if (O2REG(JmpUndefined).isUndefined())
ip = IPADD(ip->iJmpUndefined.op1);
else
ip = NEXTINST(JmpUndefined);
DISPATCH;
}
CASE(JmpUndefinedLong) {
if (O2REG(JmpUndefinedLong).isUndefined())
ip = IPADD(ip->iJmpUndefinedLong.op1);
else
ip = NEXTINST(JmpUndefinedLong);
DISPATCH;
}
CASE(Add) {
if (LLVM_LIKELY(
O2REG(Add).isNumber() &&
O3REG(Add).isNumber())) { /* Fast-path. */
CASE(AddN) {
O1REG(Add) = HermesValue::encodeDoubleValue(
O2REG(Add).getNumber() + O3REG(Add).getNumber());
ip = NEXTINST(Add);
DISPATCH;
}
}
CAPTURE_IP_ASSIGN(
res,
addOp_RJS(runtime, Handle<>(&O2REG(Add)), Handle<>(&O3REG(Add))));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(Add) = res.getValue();
ip = NEXTINST(Add);
DISPATCH;
}
CASE(BitNot) {
if (LLVM_LIKELY(O2REG(BitNot).isNumber())) { /* Fast-path. */
O1REG(BitNot) = HermesValue::encodeDoubleValue(
~hermes::truncateToInt32(O2REG(BitNot).getNumber()));
ip = NEXTINST(BitNot);
DISPATCH;
}
CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(BitNot))));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(BitNot) = HermesValue::encodeDoubleValue(
~static_cast<int32_t>(res->getNumber()));
ip = NEXTINST(BitNot);
DISPATCH;
}
CASE(GetArgumentsLength) {
// If the arguments object hasn't been created yet.
if (O2REG(GetArgumentsLength).isUndefined()) {
O1REG(GetArgumentsLength) =
HermesValue::encodeNumberValue(FRAME.getArgCount());
ip = NEXTINST(GetArgumentsLength);
DISPATCH;
}
// The arguments object has been created, so this is a regular property
// get.
assert(
O2REG(GetArgumentsLength).isObject() &&
"arguments lazy register is not an object");
CAPTURE_IP_ASSIGN(
resPH,
JSObject::getNamed_RJS(
Handle<JSObject>::vmcast(&O2REG(GetArgumentsLength)),
runtime,
Predefined::getSymbolID(Predefined::length)));
if (resPH == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(GetArgumentsLength) = resPH->get();
ip = NEXTINST(GetArgumentsLength);
DISPATCH;
}
CASE(GetArgumentsPropByVal) {
// If the arguments object hasn't been created yet and we have a
// valid integer index, we use the fast path.
if (O3REG(GetArgumentsPropByVal).isUndefined()) {
// If this is an integer index.
if (auto index = toArrayIndexFastPath(O2REG(GetArgumentsPropByVal))) {
// Is this an existing argument?
if (*index < FRAME.getArgCount()) {
O1REG(GetArgumentsPropByVal) = FRAME.getArgRef(*index);
ip = NEXTINST(GetArgumentsPropByVal);
DISPATCH;
}
}
}
// Slow path.
CAPTURE_IP_ASSIGN(
auto res,
getArgumentsPropByValSlowPath_RJS(
runtime,
&O3REG(GetArgumentsPropByVal),
&O2REG(GetArgumentsPropByVal),
FRAME.getCalleeClosureHandleUnsafe(),
strictMode));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(GetArgumentsPropByVal) = res->getHermesValue();
ip = NEXTINST(GetArgumentsPropByVal);
DISPATCH;
}
CASE(ReifyArguments) {
// If the arguments object was already created, do nothing.
if (!O1REG(ReifyArguments).isUndefined()) {
assert(
O1REG(ReifyArguments).isObject() &&
"arguments lazy register is not an object");
ip = NEXTINST(ReifyArguments);
DISPATCH;
}
CAPTURE_IP_ASSIGN(
resArgs,
reifyArgumentsSlowPath(
runtime, FRAME.getCalleeClosureHandleUnsafe(), strictMode));
if (LLVM_UNLIKELY(resArgs == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(ReifyArguments) = resArgs->getHermesValue();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(ReifyArguments);
DISPATCH;
}
CASE(NewObject) {
// Create a new object using the built-in constructor. Note that the
// built-in constructor is empty, so we don't actually need to call
// it.
CAPTURE_IP_ASSIGN(
O1REG(NewObject), JSObject::create(runtime).getHermesValue());
assert(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"Should not create handles.");
ip = NEXTINST(NewObject);
DISPATCH;
}
CASE(NewObjectWithParent) {
CAPTURE_IP_ASSIGN(
O1REG(NewObjectWithParent),
JSObject::create(
runtime,
O2REG(NewObjectWithParent).isObject()
? Handle<JSObject>::vmcast(&O2REG(NewObjectWithParent))
: O2REG(NewObjectWithParent).isNull()
? Runtime::makeNullHandle<JSObject>()
: Handle<JSObject>::vmcast(&runtime->objectPrototype))
.getHermesValue());
assert(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"Should not create handles.");
ip = NEXTINST(NewObjectWithParent);
DISPATCH;
}
CASE(NewObjectWithBuffer) {
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::createObjectFromBuffer(
runtime,
curCodeBlock,
ip->iNewObjectWithBuffer.op3,
ip->iNewObjectWithBuffer.op4,
ip->iNewObjectWithBuffer.op5));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(NewObjectWithBuffer) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(NewObjectWithBuffer);
DISPATCH;
}
CASE(NewObjectWithBufferLong) {
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::createObjectFromBuffer(
runtime,
curCodeBlock,
ip->iNewObjectWithBufferLong.op3,
ip->iNewObjectWithBufferLong.op4,
ip->iNewObjectWithBufferLong.op5));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(NewObjectWithBufferLong) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(NewObjectWithBufferLong);
DISPATCH;
}
CASE(NewArray) {
// Create a new array using the built-in constructor. Note that the
// built-in constructor is empty, so we don't actually need to call
// it.
CAPTURE_IP_ASSIGN(
auto createRes,
JSArray::create(runtime, ip->iNewArray.op2, ip->iNewArray.op2));
if (createRes == ExecutionStatus::EXCEPTION) {
goto exception;
}
O1REG(NewArray) = createRes->getHermesValue();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(NewArray);
DISPATCH;
}
CASE(NewArrayWithBuffer) {
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::createArrayFromBuffer(
runtime,
curCodeBlock,
ip->iNewArrayWithBuffer.op2,
ip->iNewArrayWithBuffer.op3,
ip->iNewArrayWithBuffer.op4));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(NewArrayWithBuffer) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = NEXTINST(NewArrayWithBuffer);
DISPATCH;
}
CASE(NewArrayWithBufferLong) {
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::createArrayFromBuffer(
runtime,
curCodeBlock,
ip->iNewArrayWithBufferLong.op2,
ip->iNewArrayWithBufferLong.op3,
ip->iNewArrayWithBufferLong.op4));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(NewArrayWithBufferLong) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = NEXTINST(NewArrayWithBufferLong);
DISPATCH;
}
CASE(CreateThis) {
// Registers: output, prototype, closure.
if (LLVM_UNLIKELY(!vmisa<Callable>(O3REG(CreateThis)))) {
CAPTURE_IP(runtime->raiseTypeError("constructor is not callable"));
goto exception;
}
CAPTURE_IP_ASSIGN(
auto res,
Callable::newObject(
Handle<Callable>::vmcast(&O3REG(CreateThis)),
runtime,
Handle<JSObject>::vmcast(
O2REG(CreateThis).isObject() ? &O2REG(CreateThis)
: &runtime->objectPrototype)));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(CreateThis) = res->getHermesValue();
ip = NEXTINST(CreateThis);
DISPATCH;
}
CASE(SelectObject) {
// Registers: output, thisObject, constructorReturnValue.
O1REG(SelectObject) = O3REG(SelectObject).isObject()
? O3REG(SelectObject)
: O2REG(SelectObject);
ip = NEXTINST(SelectObject);
DISPATCH;
}
CASE(Eq)
CASE(Neq) {
CAPTURE_IP_ASSIGN(
res,
abstractEqualityTest_RJS(
runtime, Handle<>(&O2REG(Eq)), Handle<>(&O3REG(Eq))));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(Eq) = ip->opCode == OpCode::Eq
? res.getValue()
: HermesValue::encodeBoolValue(!res->getBool());
ip = NEXTINST(Eq);
DISPATCH;
}
CASE(StrictEq) {
O1REG(StrictEq) = HermesValue::encodeBoolValue(
strictEqualityTest(O2REG(StrictEq), O3REG(StrictEq)));
ip = NEXTINST(StrictEq);
DISPATCH;
}
CASE(StrictNeq) {
O1REG(StrictNeq) = HermesValue::encodeBoolValue(
!strictEqualityTest(O2REG(StrictNeq), O3REG(StrictNeq)));
ip = NEXTINST(StrictNeq);
DISPATCH;
}
CASE(Not) {
O1REG(Not) = HermesValue::encodeBoolValue(!toBoolean(O2REG(Not)));
ip = NEXTINST(Not);
DISPATCH;
}
CASE(Negate) {
if (LLVM_LIKELY(O2REG(Negate).isNumber())) {
O1REG(Negate) =
HermesValue::encodeDoubleValue(-O2REG(Negate).getNumber());
} else {
CAPTURE_IP_ASSIGN(
res, toNumber_RJS(runtime, Handle<>(&O2REG(Negate))));
if (res == ExecutionStatus::EXCEPTION)
goto exception;
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(Negate) = HermesValue::encodeDoubleValue(-res->getNumber());
}
ip = NEXTINST(Negate);
DISPATCH;
}
CASE(TypeOf) {
CAPTURE_IP_ASSIGN(
O1REG(TypeOf), typeOf(runtime, Handle<>(&O2REG(TypeOf))));
ip = NEXTINST(TypeOf);
DISPATCH;
}
CASE(Mod) {
// We use fmod here for simplicity. Theoretically fmod behaves slightly
// differently than the ECMAScript Spec. fmod applies round-towards-zero
// for the remainder when it's not representable by a double; while the
// spec requires round-to-nearest. As an example, 5 % 0.7 will give
// 0.10000000000000031 using fmod, but using the rounding style
// described
// by the spec, the output should really be 0.10000000000000053.
// Such difference can be ignored in practice.
if (LLVM_LIKELY(O2REG(Mod).isNumber() && O3REG(Mod).isNumber())) {
/* Fast-path. */
O1REG(Mod) = HermesValue::encodeDoubleValue(
std::fmod(O2REG(Mod).getNumber(), O3REG(Mod).getNumber()));
ip = NEXTINST(Mod);
DISPATCH;
}
CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(Mod))));
if (res == ExecutionStatus::EXCEPTION)
goto exception;
double left = res->getDouble();
CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(Mod))));
if (res == ExecutionStatus::EXCEPTION)
goto exception;
O1REG(Mod) =
HermesValue::encodeDoubleValue(std::fmod(left, res->getDouble()));
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(Mod);
DISPATCH;
}
CASE(InstanceOf) {
CAPTURE_IP_ASSIGN(
auto result,
instanceOfOperator_RJS(
runtime,
Handle<>(&O2REG(InstanceOf)),
Handle<>(&O3REG(InstanceOf))));
if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(InstanceOf) = HermesValue::encodeBoolValue(*result);
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(InstanceOf);
DISPATCH;
}
CASE(IsIn) {
{
if (LLVM_UNLIKELY(!O3REG(IsIn).isObject())) {
CAPTURE_IP(runtime->raiseTypeError(
"right operand of 'in' is not an object"));
goto exception;
}
CAPTURE_IP_ASSIGN(
auto cr,
JSObject::hasComputed(
Handle<JSObject>::vmcast(&O3REG(IsIn)),
runtime,
Handle<>(&O2REG(IsIn))));
if (cr == ExecutionStatus::EXCEPTION) {
goto exception;
}
O1REG(IsIn) = HermesValue::encodeBoolValue(*cr);
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(IsIn);
DISPATCH;
}
CASE(PutNewOwnByIdShort) {
nextIP = NEXTINST(PutNewOwnByIdShort);
idVal = ip->iPutNewOwnByIdShort.op3;
goto putOwnById;
}
CASE(PutNewOwnNEByIdLong)
CASE(PutNewOwnByIdLong) {
nextIP = NEXTINST(PutNewOwnByIdLong);
idVal = ip->iPutNewOwnByIdLong.op3;
goto putOwnById;
}
CASE(PutNewOwnNEById)
CASE(PutNewOwnById) {
nextIP = NEXTINST(PutNewOwnById);
idVal = ip->iPutNewOwnById.op3;
}
putOwnById : {
assert(
O1REG(PutNewOwnById).isObject() &&
"Object argument of PutNewOwnById must be an object");
CAPTURE_IP_ASSIGN(
auto res,
JSObject::defineNewOwnProperty(
Handle<JSObject>::vmcast(&O1REG(PutNewOwnById)),
runtime,
ID(idVal),
ip->opCode <= OpCode::PutNewOwnByIdLong
? PropertyFlags::defaultNewNamedPropertyFlags()
: PropertyFlags::nonEnumerablePropertyFlags(),
Handle<>(&O2REG(PutNewOwnById))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(DelByIdLong) {
idVal = ip->iDelByIdLong.op3;
nextIP = NEXTINST(DelByIdLong);
goto DelById;
}
CASE(DelById) {
idVal = ip->iDelById.op3;
nextIP = NEXTINST(DelById);
}
DelById : {
if (LLVM_LIKELY(O2REG(DelById).isObject())) {
CAPTURE_IP_ASSIGN(
auto status,
JSObject::deleteNamed(
Handle<JSObject>::vmcast(&O2REG(DelById)),
runtime,
ID(idVal),
defaultPropOpFlags));
if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());
} else {
// This is the "slow path".
CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelById))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
// If an exception is thrown, likely we are trying to convert
// undefined/null to an object. Passing over the name of the property
// so that we could emit more meaningful error messages.
CAPTURE_IP(amendPropAccessErrorMsgWithPropName(
runtime, Handle<>(&O2REG(DelById)), "delete", ID(idVal)));
goto exception;
}
tmpHandle = res.getValue();
CAPTURE_IP_ASSIGN(
auto status,
JSObject::deleteNamed(
Handle<JSObject>::vmcast(tmpHandle),
runtime,
ID(idVal),
defaultPropOpFlags));
if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());
tmpHandle.clear();
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(DelByVal) {
if (LLVM_LIKELY(O2REG(DelByVal).isObject())) {
CAPTURE_IP_ASSIGN(
auto status,
JSObject::deleteComputed(
Handle<JSObject>::vmcast(&O2REG(DelByVal)),
runtime,
Handle<>(&O3REG(DelByVal)),
defaultPropOpFlags));
if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());
} else {
// This is the "slow path".
CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelByVal))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
tmpHandle = res.getValue();
CAPTURE_IP_ASSIGN(
auto status,
JSObject::deleteComputed(
Handle<JSObject>::vmcast(tmpHandle),
runtime,
Handle<>(&O3REG(DelByVal)),
defaultPropOpFlags));
if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());
}
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = NEXTINST(DelByVal);
DISPATCH;
}
CASE(CreateRegExp) {
{
// Create the RegExp object.
CAPTURE_IP_ASSIGN(auto re, JSRegExp::create(runtime));
// Initialize the regexp.
CAPTURE_IP_ASSIGN(
auto pattern,
runtime->makeHandle(curCodeBlock->getRuntimeModule()
->getStringPrimFromStringIDMayAllocate(
ip->iCreateRegExp.op2)));
CAPTURE_IP_ASSIGN(
auto flags,
runtime->makeHandle(curCodeBlock->getRuntimeModule()
->getStringPrimFromStringIDMayAllocate(
ip->iCreateRegExp.op3)));
CAPTURE_IP_ASSIGN(
auto bytecode,
curCodeBlock->getRuntimeModule()->getRegExpBytecodeFromRegExpID(
ip->iCreateRegExp.op4));
CAPTURE_IP_ASSIGN(
auto initRes,
JSRegExp::initialize(re, runtime, pattern, flags, bytecode));
if (LLVM_UNLIKELY(initRes == ExecutionStatus::EXCEPTION)) {
goto exception;
}
// Done, return the new object.
O1REG(CreateRegExp) = re.getHermesValue();
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateRegExp);
DISPATCH;
}
CASE(SwitchImm) {
if (LLVM_LIKELY(O1REG(SwitchImm).isNumber())) {
double numVal = O1REG(SwitchImm).getNumber();
uint32_t uintVal = (uint32_t)numVal;
if (LLVM_LIKELY(numVal == uintVal) && // Only integers.
LLVM_LIKELY(uintVal >= ip->iSwitchImm.op4) && // Bounds checking.
LLVM_LIKELY(uintVal <= ip->iSwitchImm.op5)) // Bounds checking.
{
// Calculate the offset into the bytecode where the jump table for
// this SwitchImm starts.
const uint8_t *tablestart = (const uint8_t *)llvh::alignAddr(
(const uint8_t *)ip + ip->iSwitchImm.op2, sizeof(uint32_t));
// Read the offset from the table.
// Must be signed to account for backwards branching.
const int32_t *loc =
(const int32_t *)tablestart + uintVal - ip->iSwitchImm.op4;
ip = IPADD(*loc);
DISPATCH;
}
}
// Wrong type or out of range, jump to default.
ip = IPADD(ip->iSwitchImm.op3);
DISPATCH;
}
LOAD_CONST(
LoadConstUInt8,
HermesValue::encodeDoubleValue(ip->iLoadConstUInt8.op2));
LOAD_CONST(
LoadConstInt, HermesValue::encodeDoubleValue(ip->iLoadConstInt.op2));
LOAD_CONST(
LoadConstDouble,
HermesValue::encodeDoubleValue(ip->iLoadConstDouble.op2));
LOAD_CONST_CAPTURE_IP(
LoadConstString,
HermesValue::encodeStringValue(
curCodeBlock->getRuntimeModule()
->getStringPrimFromStringIDMayAllocate(
ip->iLoadConstString.op2)));
LOAD_CONST_CAPTURE_IP(
LoadConstStringLongIndex,
HermesValue::encodeStringValue(
curCodeBlock->getRuntimeModule()
->getStringPrimFromStringIDMayAllocate(
ip->iLoadConstStringLongIndex.op2)));
LOAD_CONST(LoadConstUndefined, HermesValue::encodeUndefinedValue());
LOAD_CONST(LoadConstNull, HermesValue::encodeNullValue());
LOAD_CONST(LoadConstTrue, HermesValue::encodeBoolValue(true));
LOAD_CONST(LoadConstFalse, HermesValue::encodeBoolValue(false));
LOAD_CONST(LoadConstZero, HermesValue::encodeDoubleValue(0));
BINOP(Sub, doSub);
BINOP(Mul, doMult);
BINOP(Div, doDiv);
BITWISEBINOP(BitAnd, &);
BITWISEBINOP(BitOr, |);
BITWISEBINOP(BitXor, ^);
// For LShift, we need to use toUInt32 first because lshift on negative
// numbers is undefined behavior in theory.
SHIFTOP(LShift, <<, toUInt32_RJS, uint32_t, int32_t);
SHIFTOP(RShift, >>, toInt32_RJS, int32_t, int32_t);
SHIFTOP(URshift, >>, toUInt32_RJS, uint32_t, uint32_t);
CONDOP(Less, <, lessOp_RJS);
CONDOP(LessEq, <=, lessEqualOp_RJS);
CONDOP(Greater, >, greaterOp_RJS);
CONDOP(GreaterEq, >=, greaterEqualOp_RJS);
JCOND(Less, <, lessOp_RJS);
JCOND(LessEqual, <=, lessEqualOp_RJS);
JCOND(Greater, >, greaterOp_RJS);
JCOND(GreaterEqual, >=, greaterEqualOp_RJS);
JCOND_STRICT_EQ_IMPL(
JStrictEqual, , IPADD(ip->iJStrictEqual.op1), NEXTINST(JStrictEqual));
JCOND_STRICT_EQ_IMPL(
JStrictEqual,
Long,
IPADD(ip->iJStrictEqualLong.op1),
NEXTINST(JStrictEqualLong));
JCOND_STRICT_EQ_IMPL(
JStrictNotEqual,
,
NEXTINST(JStrictNotEqual),
IPADD(ip->iJStrictNotEqual.op1));
JCOND_STRICT_EQ_IMPL(
JStrictNotEqual,
Long,
NEXTINST(JStrictNotEqualLong),
IPADD(ip->iJStrictNotEqualLong.op1));
JCOND_EQ_IMPL(JEqual, , IPADD(ip->iJEqual.op1), NEXTINST(JEqual));
JCOND_EQ_IMPL(
JEqual, Long, IPADD(ip->iJEqualLong.op1), NEXTINST(JEqualLong));
JCOND_EQ_IMPL(
JNotEqual, , NEXTINST(JNotEqual), IPADD(ip->iJNotEqual.op1));
JCOND_EQ_IMPL(
JNotEqual,
Long,
NEXTINST(JNotEqualLong),
IPADD(ip->iJNotEqualLong.op1));
CASE_OUTOFLINE(PutOwnByVal);
CASE_OUTOFLINE(PutOwnGetterSetterByVal);
CASE_OUTOFLINE(DirectEval);
CASE_OUTOFLINE(IteratorBegin);
CASE_OUTOFLINE(IteratorNext);
CASE(IteratorClose) {
if (LLVM_UNLIKELY(O1REG(IteratorClose).isObject())) {
// The iterator must be closed if it's still an object.
// That means it was never an index and is not done iterating (a state
// which is indicated by `undefined`).
CAPTURE_IP_ASSIGN(
auto res,
iteratorClose(
runtime,
Handle<JSObject>::vmcast(&O1REG(IteratorClose)),
Runtime::getEmptyValue()));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
if (ip->iIteratorClose.op2 &&
!isUncatchableError(runtime->thrownValue_)) {
// Ignore inner exception.
runtime->clearThrownValue();
} else {
goto exception;
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
}
ip = NEXTINST(IteratorClose);
DISPATCH;
}
CASE(_last) {
llvm_unreachable("Invalid opcode _last");
}
}
llvm_unreachable("unreachable");
// We arrive here if we couldn't allocate the registers for the current frame.
stackOverflow:
CAPTURE_IP(runtime->raiseStackOverflow(
Runtime::StackOverflowKind::JSRegisterStack));
// We arrive here when we raised an exception in a callee, but we don't want
// the callee to be able to handle it.
handleExceptionInParent:
// Restore the caller code block and IP.
curCodeBlock = FRAME.getSavedCodeBlock();
ip = FRAME.getSavedIP();
// Pop to the previous frame where technically the error happened.
frameRegs =
&runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();
// If we are coming from native code, return.
if (!curCodeBlock)
return ExecutionStatus::EXCEPTION;
// Return because of recursive calling structure
#ifdef HERMESVM_PROFILER_EXTERN
return ExecutionStatus::EXCEPTION;
#endif
// Handle the exception.
exception:
UPDATE_OPCODE_TIME_SPENT;
assert(
!runtime->thrownValue_.isEmpty() &&
"thrownValue unavailable at exception");
bool catchable = true;
// If this is an Error object that was thrown internally, it didn't have
// access to the current codeblock and IP, so collect the stack trace here.
if (auto *jsError = dyn_vmcast<JSError>(runtime->thrownValue_)) {
catchable = jsError->catchable();
if (!jsError->getStackTrace()) {
// Temporarily clear the thrown value for following operations.
CAPTURE_IP_ASSIGN(
auto errorHandle,
runtime->makeHandle(vmcast<JSError>(runtime->thrownValue_)));
runtime->clearThrownValue();
CAPTURE_IP(JSError::recordStackTrace(
errorHandle, runtime, false, curCodeBlock, ip));
// Restore the thrown value.
runtime->setThrownValue(errorHandle.getHermesValue());
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
#ifdef HERMES_ENABLE_DEBUGGER
if (SingleStep) {
// If we're single stepping, don't bother with any more checks,
// and simply signal that we should continue execution with an exception.
state.codeBlock = curCodeBlock;
state.offset = CUROFFSET;
return ExecutionStatus::EXCEPTION;
}
using PauseOnThrowMode = facebook::hermes::debugger::PauseOnThrowMode;
auto mode = runtime->debugger_.getPauseOnThrowMode();
if (mode != PauseOnThrowMode::None) {
if (!runtime->debugger_.isDebugging()) {
// Determine whether the PauseOnThrowMode requires us to stop here.
bool caught =
runtime->debugger_
.findCatchTarget(InterpreterState(curCodeBlock, CUROFFSET))
.hasValue();
bool shouldStop = mode == PauseOnThrowMode::All ||
(mode == PauseOnThrowMode::Uncaught && !caught);
if (shouldStop) {
// When runDebugger is invoked after an exception,
// stepping should never happen internally.
// Any step is a step to an exception handler, which we do
// directly here in the interpreter.
// Thus, the result state should be the same as the input state.
InterpreterState tmpState{curCodeBlock, (uint32_t)CUROFFSET};
CAPTURE_IP_ASSIGN(
ExecutionStatus resultStatus,
runtime->debugger_.runDebugger(
Debugger::RunReason::Exception, tmpState));
(void)resultStatus;
assert(
tmpState == InterpreterState(curCodeBlock, CUROFFSET) &&
"not allowed to step internally in a pauseOnThrow");
gcScope.flushToSmallCount(KEEP_HANDLES);
}
}
}
#endif
int32_t handlerOffset = 0;
// If the exception is not catchable, skip found catch blocks.
while (((handlerOffset = curCodeBlock->findCatchTargetOffset(CUROFFSET)) ==
-1) ||
!catchable) {
PROFILER_EXIT_FUNCTION(curCodeBlock);
#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES
runtime->popCallStack();
#endif
// Restore the code block and IP.
curCodeBlock = FRAME.getSavedCodeBlock();
ip = FRAME.getSavedIP();
// Pop a stack frame.
frameRegs =
&runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();
SLOW_DEBUG(
dbgs() << "function exit with exception: restored stackLevel="
<< runtime->getStackLevel() << "\n");
// Are we returning to native code?
if (!curCodeBlock) {
SLOW_DEBUG(
dbgs()
<< "function exit with exception: returning to native code\n");
return ExecutionStatus::EXCEPTION;
}
assert(
isCallType(ip->opCode) &&
"return address is not Call-type instruction");
// Return because of recursive calling structure
#ifdef HERMESVM_PROFILER_EXTERN
return ExecutionStatus::EXCEPTION;
#endif
}
INIT_STATE_FOR_CODEBLOCK(curCodeBlock);
ip = IPADD(handlerOffset - CUROFFSET);
}
}
} // namespace vm
} // namespace hermes
| ./CrossVul/dataset_final_sorted/CWE-670/cpp/good_4258_2 |
crossvul-cpp_data_bad_1286_1 | /**
* Copyright 2017 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <stdio.h>
#include <base64.h>
#include <cJSON.h>
#include <openssl/hmac.h>
#include <openssl/err.h>
#include <openssl/sha.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include "cjwt.h"
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
//#define _DEBUG
#ifdef _DEBUG
#define cjwt_error(...) printf(__VA_ARGS__)
#define cjwt_warn(...) printf(__VA_ARGS__)
#define cjwt_info(...) printf(__VA_ARGS__)
#define cjwt_rsa_error() ERR_print_errors_fp(stdout)
#else
#define cjwt_error(...)
#define cjwt_warn(...)
#define cjwt_info(...)
#define cjwt_rsa_error()
#endif
#define IS_RSA_ALG(alg) ((alg) > alg_ps512)
/*----------------------------------------------------------------------------*/
/* Data Structures */
/*----------------------------------------------------------------------------*/
/* none */
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
/* none */
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
/* none */
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
extern char *strdup(const char *s);
extern size_t b64url_get_decoded_buffer_size( const size_t encoded_size );
extern size_t b64url_decode( const uint8_t *input, const size_t input_size, uint8_t *output );
/*----------------------------------------------------------------------------*/
/* Internal functions */
/*----------------------------------------------------------------------------*/
/* none */
int cjwt_alg_str_to_enum( const char *alg_str )
{
struct alg_map {
cjwt_alg_t alg;
const char *text;
};
const struct alg_map m[] = {
{ .alg = alg_none, .text = "none" },
{ .alg = alg_es256, .text = "ES256" },
{ .alg = alg_es384, .text = "ES384" },
{ .alg = alg_es512, .text = "ES512" },
{ .alg = alg_hs256, .text = "HS256" },
{ .alg = alg_hs384, .text = "HS384" },
{ .alg = alg_hs512, .text = "HS512" },
{ .alg = alg_ps256, .text = "PS256" },
{ .alg = alg_ps384, .text = "PS384" },
{ .alg = alg_ps512, .text = "PS512" },
{ .alg = alg_rs256, .text = "RS256" },
{ .alg = alg_rs384, .text = "RS384" },
{ .alg = alg_rs512, .text = "RS512" }
};
size_t count, i;
count = sizeof( m ) / sizeof( struct alg_map );
for( i = 0; i < count; i++ ) {
if( !strcasecmp( alg_str, m[i].text ) ) {
return m[i].alg;
}
}
return -1;
}
static cjwt_alg_t __cjwt_alg_str_to_enum( const char *alg_str )
{
int alg = cjwt_alg_str_to_enum (alg_str);
if (alg >= 0)
return alg;
else
return alg_none;
}
inline static void cjwt_delete_child_json( cJSON* j, const char* s )
{
if( j && cJSON_HasObjectItem( j, s ) ) {
cJSON_DeleteItemFromObject( j, s );
}
}
static void cjwt_delete_public_claims( cJSON* val )
{
cjwt_delete_child_json( val, "iss" );
cjwt_delete_child_json( val, "sub" );
cjwt_delete_child_json( val, "aud" );
cjwt_delete_child_json( val, "jti" );
cjwt_delete_child_json( val, "exp" );
cjwt_delete_child_json( val, "nbf" );
cjwt_delete_child_json( val, "iat" );
}
static int cjwt_sign_sha_hmac( cjwt_t *jwt, unsigned char **out, const EVP_MD *alg,
const char *in, int *out_len )
{
unsigned char res[EVP_MAX_MD_SIZE];
unsigned int res_len;
cjwt_info( "string for signing : %s \n", in );
HMAC( alg, jwt->header.key, jwt->header.key_len,
( const unsigned char * )in, strlen( in ), res, &res_len );
unsigned char *resptr = ( unsigned char * )malloc( res_len + 1 );
if( !resptr ) {
return ENOMEM;
}
memcpy( resptr, res, res_len );
resptr[res_len] = '\0';
*out = resptr;
*out_len = res_len;
return 0;
}
static int cjwt_sign( cjwt_t *cjwt, unsigned char **out, const char *in, int *out_len )
{
switch( cjwt->header.alg ) {
case alg_none:
return 0;
case alg_hs256:
return cjwt_sign_sha_hmac( cjwt, out, EVP_sha256(), in, out_len );
case alg_hs384:
return cjwt_sign_sha_hmac( cjwt, out, EVP_sha384(), in, out_len );
case alg_hs512:
return cjwt_sign_sha_hmac( cjwt, out, EVP_sha512(), in, out_len );
default :
return -1;
}//switch
return -1;
}
static RSA* cjwt_create_rsa( unsigned char *key, int key_len, int public )
{
RSA *rsa = NULL;
BIO *keybio ;
if( key == NULL ) {
cjwt_error( "invalid rsa key\n" );
goto rsa_end;
}
keybio = BIO_new_mem_buf( key, key_len );
if( keybio == NULL ) {
cjwt_error( "BIO creation for key failed\n" );
goto rsa_end;
}
if( public ) {
rsa = PEM_read_bio_RSA_PUBKEY( keybio, &rsa, NULL, NULL );
} else {
rsa = PEM_read_bio_RSAPrivateKey( keybio, &rsa, NULL, NULL );
}
if( rsa == NULL ) {
cjwt_rsa_error();
}
BIO_free (keybio);
rsa_end:
return rsa;
}
static int cjwt_verify_rsa( cjwt_t *jwt, const char *p_enc, const char *p_sigb64 )
{
int ret = EINVAL, sz_sigb64 = 0;
RSA *rsa = NULL;
size_t enc_len = 0, sig_desize = 0;
uint8_t *decoded_sig = NULL;
unsigned char digest[EVP_MAX_MD_SIZE];
if( jwt->header.key_len == 0 ) {
cjwt_error( "invalid rsa key\n" );
return EINVAL;
}
rsa = cjwt_create_rsa( jwt->header.key, jwt->header.key_len, 1 );
if( rsa == NULL ) {
cjwt_error( "key to rsa conversion failed\n" );
return EINVAL;
}
//decode p_sigb64
sz_sigb64 = strlen( ( char * )p_sigb64 );
sig_desize = b64url_get_decoded_buffer_size( sz_sigb64 );
//Because b64url_decode() always writes in blocks of 3 bytes for every 4
//characters even when the last 2 bytes are not used, we need up to 2
//extra bytes of output buffer to avoid a buffer overrun
decoded_sig = malloc( sig_desize + 2 );
if( !decoded_sig ) {
cjwt_error( "memory allocation failed\n" );
//free rsa
RSA_free( rsa );
cjwt_rsa_error();
return ENOMEM;
}
memset( decoded_sig, 0, sig_desize + 2 );
sig_desize = b64url_decode( ( uint8_t * )p_sigb64, sz_sigb64, decoded_sig );
cjwt_info( "----------------- signature ----------------- \n" );
cjwt_info( "Bytes = %d\n", ( int )sig_desize );
cjwt_info( "--------------------------------------------- \n" );
if( !sig_desize ) {
cjwt_error( "b64url_decode failed\n" );
goto end;
}
decoded_sig[sig_desize] = '\0';
//verify rsa
enc_len = strlen( p_enc );
switch( jwt->header.alg ) {
case alg_rs256:
SHA256( ( const unsigned char* ) p_enc, enc_len, digest );
ret = RSA_verify
( NID_sha256, digest, SHA256_DIGEST_LENGTH, decoded_sig,
( unsigned int ) sig_desize, rsa );
break;
case alg_rs384:
SHA384( ( const unsigned char * ) p_enc, enc_len, digest );
ret = RSA_verify
( NID_sha384, digest, SHA384_DIGEST_LENGTH, decoded_sig,
( unsigned int ) sig_desize, rsa );
break;
case alg_rs512:
SHA512( ( const unsigned char* ) p_enc, enc_len, digest );
ret = RSA_verify
( NID_sha512, digest, SHA512_DIGEST_LENGTH, decoded_sig,
( unsigned int ) sig_desize, rsa );
break;
default:
cjwt_error( "invalid rsa algorithm\n" );
ret = EINVAL;
break;
}
end:
RSA_free( rsa );
free( decoded_sig );
if( ret == 1 ) {
return 0;
}
cjwt_rsa_error();
return EINVAL;
}
static int cjwt_verify_signature( cjwt_t *p_jwt, char *p_in, const char *p_sign )
{
int ret = 0;
int sz_signed = 0;
unsigned char* signed_out = NULL;
if( !p_jwt || !p_in || !p_sign ) {
ret = EINVAL;
goto end;
}
if( IS_RSA_ALG( p_jwt->header.alg ) ) {
ret = cjwt_verify_rsa( p_jwt, p_in, p_sign );
goto end;
}
//sign
ret = cjwt_sign( p_jwt, &signed_out, p_in, &sz_signed );
if( ret ) {
ret = EINVAL;
goto end;
}
//decode signature from input token
size_t sz_p_sign = strlen( p_sign );
size_t sz_decoded = b64url_get_decoded_buffer_size( sz_p_sign );
uint8_t *signed_dec = malloc( sz_decoded + 1 );
if( !signed_dec ) {
ret = ENOMEM;
goto err_decode;
}
memset( signed_dec, 0, ( sz_decoded + 1 ) );
//decode
int out_size = b64url_decode( ( uint8_t * )p_sign, sz_p_sign, signed_dec );
if( !out_size ) {
ret = EINVAL;
goto err_match;
}
signed_dec[out_size] = '\0';
cjwt_info( "Signature length : enc %d, signature %d\n",
( int )sz_signed, ( int )out_size );
cjwt_info( "signed token : %s\n", signed_out );
cjwt_info( "expected token signature %s\n", signed_dec );
if( sz_signed != out_size ) {
cjwt_info( "Signature length mismatch: enc %d, signature %d\n",
( int )sz_signed, ( int )out_size );
ret = -1;
goto err_match;
}
ret = CRYPTO_memcmp(
( unsigned char* )signed_out, ( unsigned char* )signed_dec, out_size );
err_match:
free( signed_dec );
err_decode:
free( signed_out );
end:
return ret;
}
static int cjwt_update_payload( cjwt_t *p_cjwt, char *p_decpl )
{
cJSON* j_val = NULL;
if( !p_cjwt || !p_decpl ) {
return EINVAL;
}
//create cJSON object
cJSON *j_payload = cJSON_Parse( ( char* )p_decpl );
if( !j_payload ) {
return ENOMEM;
}
//extract data
cjwt_info( "Json = %s\n", cJSON_Print( j_payload ) );
cjwt_info( "--------------------------------------------- \n\n" );
//iss
j_val = cJSON_GetObjectItem( j_payload, "iss" );
if( j_val ) {
if( p_cjwt->iss ) {
free( p_cjwt->iss );
p_cjwt->iss = NULL;
}
p_cjwt->iss = strdup(j_val->valuestring);
if( !p_cjwt->iss ) {
cJSON_Delete( j_payload );
return ENOMEM;
}
}
//sub
j_val = cJSON_GetObjectItem( j_payload, "sub" );
if( j_val ) {
if( p_cjwt->sub ) {
free( p_cjwt->sub );
p_cjwt->sub = NULL;
}
p_cjwt->sub = strdup(j_val->valuestring);
if( !p_cjwt->sub ) {
cJSON_Delete( j_payload );
return ENOMEM;
}
}
//aud
j_val = cJSON_GetObjectItem( j_payload, "aud" );
if( j_val ) {
if( j_val->type == cJSON_Object ) {
//array of strings
cJSON* j_tmp = NULL;
int cnt, i = 0;
char **ptr_values = NULL;
char *str_val = NULL;
cnt = cJSON_GetArraySize( j_val->child );
ptr_values = ( char** ) malloc( ( cnt ) * sizeof( char* ) );
if( !ptr_values ) {
cJSON_Delete( j_payload );
return ENOMEM;
}
for( i = 0; i < cnt; i++ ) {
j_tmp = cJSON_GetArrayItem( j_val->child, i );
cjwt_info( "aud[%d] Json = %s,type=%d,val=%s\n", i, cJSON_Print( j_tmp ), j_tmp->type, j_tmp->valuestring );
if( j_tmp->type == cJSON_String ) {
str_val = strdup(j_tmp->valuestring);
if( !str_val ) {
cJSON_Delete( j_payload );
i--;
while( i ) {
free( ptr_values[--i] );
}
free (ptr_values);
return ENOMEM;
}
ptr_values[i] = str_val;
}
}//for
p_cjwt_aud_list aud_new = malloc( sizeof( cjwt_aud_list_t ) );
if( !aud_new ) {
cJSON_Delete( j_payload );
while( cnt ) {
free( ptr_values[--cnt] );
}
free (ptr_values);
return ENOMEM;
}
aud_new->count = cnt;
aud_new->names = ptr_values;
p_cjwt->aud = aud_new;
}
}
//jti
j_val = cJSON_GetObjectItem( j_payload, "jti" );
if( j_val ) {
if( p_cjwt->jti ) {
free( p_cjwt->jti );
p_cjwt->jti = NULL;
}
p_cjwt->jti = strdup(j_val->valuestring);
if( !p_cjwt->jti ) {
cJSON_Delete( j_payload );
return ENOMEM;
}
}
//exp
j_val = cJSON_GetObjectItem( j_payload, "exp" );
if( j_val ) {
cjwt_info( "exp Json = %s,type=%d,int=%d,double=%f\n", cJSON_Print( j_val ), j_val->type, j_val->valueint, j_val->valuedouble );
if( j_val->type == cJSON_Number ) {
p_cjwt->exp.tv_sec = j_val->valueint;
p_cjwt->exp.tv_nsec = 0;
}
}
//nbf
j_val = cJSON_GetObjectItem( j_payload, "nbf" );
if( j_val ) {
cjwt_info( "nbf Json = %s,type=%d,int=%d,double=%f\n", cJSON_Print( j_val ), j_val->type, j_val->valueint, j_val->valuedouble );
if( j_val->type == cJSON_Number ) {
p_cjwt->nbf.tv_sec = j_val->valueint;
p_cjwt->nbf.tv_nsec = 0;
}
}
//iat
j_val = cJSON_GetObjectItem( j_payload, "iat" );
if( j_val ) {
cjwt_info( "iat Json = %s,type=%d,int=%d,double=%f\n", cJSON_Print( j_val ), j_val->type, j_val->valueint, j_val->valuedouble );
if( j_val->type == cJSON_Number ) {
p_cjwt->iat.tv_sec = j_val->valueint;
p_cjwt->iat.tv_nsec = 0;
}
}
//private_claims
cJSON* j_new = cJSON_Duplicate( j_payload, 1 );
if( j_new ) {
cjwt_delete_public_claims( j_new );
cjwt_info( "private claims count = %d\n", cJSON_GetArraySize( j_new ) );
if( cJSON_GetArraySize( j_new ) ) {
//cjwt_info( "private claims = %s\n", cJSON_Print( j_new ) );
if( p_cjwt->private_claims ) {
cJSON_Delete( p_cjwt->private_claims );
}
p_cjwt->private_claims = j_new;
} else {
cJSON_Delete ( j_new );
}
}
//destroy cJSON object
cJSON_Delete( j_payload );
return 0;
}
static int cjwt_update_header( cjwt_t *p_cjwt, char *p_dechead )
{
if( !p_cjwt || !p_dechead ) {
return EINVAL;
}
//create cJSON object
cJSON *j_header = cJSON_Parse( ( char* )p_dechead );
if( !j_header ) {
return ENOMEM;
}
cjwt_info( "Json = %s\n", cJSON_Print( j_header ) );
cjwt_info( "--------------------------------------------- \n\n" );
//extract data
cJSON* j_typ = cJSON_GetObjectItem( j_header, "typ" );
if( !j_typ || strcmp( j_typ->valuestring, "JWT" ) ) {
cjwt_info( "may not be a JWT token\n" );
}
cJSON* j_alg = cJSON_GetObjectItem( j_header, "alg" );
if( j_alg ) {
p_cjwt->header.alg = __cjwt_alg_str_to_enum( j_alg->valuestring );
}
//destroy cJSON object
cJSON_Delete( j_header );
return 0;
}
static int cjwt_parse_payload( cjwt_t *p_cjwt, char *p_payload )
{
int ret, sz_payload;
size_t pl_desize;
size_t out_size = 0;
uint8_t *decoded_pl;
if( !p_cjwt || !p_payload ) {
return EINVAL;
}
sz_payload = strlen( ( char * )p_payload );
pl_desize = b64url_get_decoded_buffer_size( sz_payload );
cjwt_info( "----------------- payload ------------------- \n" );
cjwt_info( "Payload Size = %d , Decoded size = %d\n", sz_payload, ( int )pl_desize );
decoded_pl = malloc( pl_desize + 1 );
if( !decoded_pl ) {
return ENOMEM;
}
memset( decoded_pl, 0, ( pl_desize + 1 ) );
//decode payload
out_size = b64url_decode( ( uint8_t * )p_payload, sz_payload, decoded_pl );
cjwt_info( "Bytes = %d\n", ( int )out_size );
if( !out_size ) {
ret = EINVAL;
goto end;
}
decoded_pl[out_size] = '\0';
cjwt_info( "Raw data = %*s\n", ( int )out_size, decoded_pl );
ret = cjwt_update_payload( p_cjwt, ( char* )decoded_pl );
end:
free( decoded_pl );
return ret;
}
static int cjwt_parse_header( cjwt_t *p_cjwt, char *p_head )
{
int sz_head, ret = 0;
size_t head_desize;
uint8_t *decoded_head;
size_t out_size = 0;
if( !p_cjwt || !p_head ) {
return EINVAL;
}
sz_head = strlen( ( char * )p_head );
head_desize = b64url_get_decoded_buffer_size( sz_head );
cjwt_info( "----------------- header -------------------- \n" );
cjwt_info( "Header Size = %d , Decoded size = %d\n", sz_head, ( int )head_desize );
decoded_head = malloc( head_desize + 1 );
if( !decoded_head ) {
return ENOMEM;
}
memset( decoded_head, 0, head_desize + 1 );
//decode header
out_size = b64url_decode( ( uint8_t * )p_head, sz_head, decoded_head );
cjwt_info( "Bytes = %d\n", ( int )out_size );
if( !out_size ) {
ret = EINVAL;
goto end;
}
decoded_head[out_size] = '\0';
cjwt_info( "Raw data = %*s\n", ( int )out_size, decoded_head );
ret = cjwt_update_header( p_cjwt, ( char* )decoded_head );
end:
free( decoded_head );
return ret;
}
static int cjwt_update_key( cjwt_t *p_cjwt, const uint8_t *key, size_t key_len )
{
int ret = 0;
if( ( NULL != key ) && ( key_len > 0 ) ) {
p_cjwt->header.key = malloc( key_len );
if( !p_cjwt->header.key ) {
ret = ENOMEM;
return ret;
}
memcpy( p_cjwt->header.key, key, key_len );
p_cjwt->header.key_len = key_len;
}
return ret;
}
static cjwt_t* cjwt_create()
{
cjwt_t *init = malloc( sizeof( cjwt_t ) );
if( init ) {
memset (init, 0, sizeof(cjwt_t));
}
return init;
}
/**
* validates jwt token and extracts data
*/
int cjwt_decode( const char *encoded, unsigned int options, cjwt_t **jwt,
const uint8_t *key, size_t key_len )
{
int ret = 0;
char *payload, *signature;
( void )options; //suppressing unused parameter warning
( void ) options;
//validate inputs
if( !encoded || !jwt ) {
cjwt_error( "null parameter\n" );
ret = EINVAL;
goto error;
}
cjwt_info( "parameters cjwt_decode()\n encoded : %s\n options : %d\n", encoded, options );
//create copy
char *enc_token = malloc( strlen( encoded ) + 1 );
if( !enc_token ) {
cjwt_error( "memory alloc failed\n" );
ret = ENOMEM;
goto error;
}
strcpy( enc_token, encoded );
//tokenize the jwt token
for( payload = enc_token; payload[0] != '.'; payload++ ) {
if( payload[0] == '\0' ) {
cjwt_error( "Invalid jwt token,has only header\n" );
ret = EINVAL;
goto end;
}
}
payload[0] = '\0';
payload++;
for( signature = payload; signature[0] != '.'; signature++ ) {
if( signature[0] == '\0' ) {
cjwt_error( "Invalid jwt token,missing signature\n" );
ret = EINVAL;
goto end;
}
}
signature[0] = '\0';
signature++;
//create cjson
cjwt_t *out = cjwt_create();
if( !out ) {
cjwt_error( "cjwt memory alloc failed\n" );
ret = ENOMEM;
goto end;
}
//populate key
ret = cjwt_update_key( out, key, key_len );
if( ret ) {
cjwt_error( "Failed to update key\n" );
goto invalid;
}
//parse header
ret = cjwt_parse_header( out, enc_token );
if( ret ) {
cjwt_error( "Invalid header\n" );
goto invalid;
}
//parse payload
ret = cjwt_parse_payload( out, payload );
if( ret ) {
cjwt_error( "Invalid payload\n" );
goto invalid;
}
if( out->header.alg != alg_none ) {
enc_token[strlen( enc_token )] = '.';
//verify
ret = cjwt_verify_signature( out, enc_token, signature );
if( ret ) {
cjwt_error( "\nSignature authentication failed\n" );
goto invalid;
}
cjwt_info( "\nSignature authentication passed\n" );
}
invalid:
if( ret ) {
cjwt_destroy( &out );
*jwt = NULL;
} else {
*jwt = out;
}
end:
free( enc_token );
error:
return ret;
}
/**
* cleanup jwt object
*/
int cjwt_destroy( cjwt_t **jwt )
{
cjwt_t *del = *jwt;
*jwt = NULL;
if( !del ) {
return 0;
}
if(del->header.key)
{
free(del->header.key);
}
del->header.key = NULL;
if( del->iss ) {
free( del->iss );
}
del->iss = NULL;
if( del->sub ) {
free( del->sub );
}
del->sub = NULL;
if( del->aud ) {
char** tmp = del->aud->names;
int cnt_lst = del->aud->count;
free( del->aud );
del->aud = NULL;
while( cnt_lst ) {
free( tmp[--cnt_lst] );
}
}
if( del->jti ) {
free( del->jti );
}
del->jti = NULL;
if( del->private_claims ) {
cJSON_Delete( del->private_claims );
}
del->private_claims = NULL;
free (del);
return 0;
}
//end of file
| ./CrossVul/dataset_final_sorted/CWE-670/c/bad_1286_1 |
crossvul-cpp_data_good_1286_1 | /**
* Copyright 2017 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <stdio.h>
#include <base64.h>
#include <cJSON.h>
#include <openssl/hmac.h>
#include <openssl/err.h>
#include <openssl/sha.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include "cjwt.h"
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
//#define _DEBUG
#ifdef _DEBUG
#define cjwt_error(...) printf(__VA_ARGS__)
#define cjwt_warn(...) printf(__VA_ARGS__)
#define cjwt_info(...) printf(__VA_ARGS__)
#define cjwt_rsa_error() ERR_print_errors_fp(stdout)
#else
#define cjwt_error(...)
#define cjwt_warn(...)
#define cjwt_info(...)
#define cjwt_rsa_error()
#endif
#define IS_RSA_ALG(alg) ((alg) > alg_ps512)
/*----------------------------------------------------------------------------*/
/* Data Structures */
/*----------------------------------------------------------------------------*/
/* none */
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
/* none */
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
/* none */
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
extern char *strdup(const char *s);
extern size_t b64url_get_decoded_buffer_size( const size_t encoded_size );
extern size_t b64url_decode( const uint8_t *input, const size_t input_size, uint8_t *output );
/*----------------------------------------------------------------------------*/
/* Internal functions */
/*----------------------------------------------------------------------------*/
/* none */
int cjwt_alg_str_to_enum( const char *alg_str )
{
struct alg_map {
cjwt_alg_t alg;
const char *text;
};
const struct alg_map m[] = {
{ .alg = alg_none, .text = "none" },
{ .alg = alg_es256, .text = "ES256" },
{ .alg = alg_es384, .text = "ES384" },
{ .alg = alg_es512, .text = "ES512" },
{ .alg = alg_hs256, .text = "HS256" },
{ .alg = alg_hs384, .text = "HS384" },
{ .alg = alg_hs512, .text = "HS512" },
{ .alg = alg_ps256, .text = "PS256" },
{ .alg = alg_ps384, .text = "PS384" },
{ .alg = alg_ps512, .text = "PS512" },
{ .alg = alg_rs256, .text = "RS256" },
{ .alg = alg_rs384, .text = "RS384" },
{ .alg = alg_rs512, .text = "RS512" }
};
size_t count, i;
count = sizeof( m ) / sizeof( struct alg_map );
for( i = 0; i < count; i++ ) {
if( !strcasecmp( alg_str, m[i].text ) ) {
return m[i].alg;
}
}
return -1;
}
inline static void cjwt_delete_child_json( cJSON* j, const char* s )
{
if( j && cJSON_HasObjectItem( j, s ) ) {
cJSON_DeleteItemFromObject( j, s );
}
}
static void cjwt_delete_public_claims( cJSON* val )
{
cjwt_delete_child_json( val, "iss" );
cjwt_delete_child_json( val, "sub" );
cjwt_delete_child_json( val, "aud" );
cjwt_delete_child_json( val, "jti" );
cjwt_delete_child_json( val, "exp" );
cjwt_delete_child_json( val, "nbf" );
cjwt_delete_child_json( val, "iat" );
}
static int cjwt_sign_sha_hmac( cjwt_t *jwt, unsigned char **out, const EVP_MD *alg,
const char *in, int *out_len )
{
unsigned char res[EVP_MAX_MD_SIZE];
unsigned int res_len;
cjwt_info( "string for signing : %s \n", in );
HMAC( alg, jwt->header.key, jwt->header.key_len,
( const unsigned char * )in, strlen( in ), res, &res_len );
unsigned char *resptr = ( unsigned char * )malloc( res_len + 1 );
if( !resptr ) {
return ENOMEM;
}
memcpy( resptr, res, res_len );
resptr[res_len] = '\0';
*out = resptr;
*out_len = res_len;
return 0;
}
static int cjwt_sign( cjwt_t *cjwt, unsigned char **out, const char *in, int *out_len )
{
switch( cjwt->header.alg ) {
case alg_none:
return 0;
case alg_hs256:
return cjwt_sign_sha_hmac( cjwt, out, EVP_sha256(), in, out_len );
case alg_hs384:
return cjwt_sign_sha_hmac( cjwt, out, EVP_sha384(), in, out_len );
case alg_hs512:
return cjwt_sign_sha_hmac( cjwt, out, EVP_sha512(), in, out_len );
default :
return -1;
}//switch
return -1;
}
static RSA* cjwt_create_rsa( unsigned char *key, int key_len, int public )
{
RSA *rsa = NULL;
BIO *keybio ;
if( key == NULL ) {
cjwt_error( "invalid rsa key\n" );
goto rsa_end;
}
keybio = BIO_new_mem_buf( key, key_len );
if( keybio == NULL ) {
cjwt_error( "BIO creation for key failed\n" );
goto rsa_end;
}
if( public ) {
rsa = PEM_read_bio_RSA_PUBKEY( keybio, &rsa, NULL, NULL );
} else {
rsa = PEM_read_bio_RSAPrivateKey( keybio, &rsa, NULL, NULL );
}
if( rsa == NULL ) {
cjwt_rsa_error();
}
BIO_free (keybio);
rsa_end:
return rsa;
}
static int cjwt_verify_rsa( cjwt_t *jwt, const char *p_enc, const char *p_sigb64 )
{
int ret = EINVAL, sz_sigb64 = 0;
RSA *rsa = NULL;
size_t enc_len = 0, sig_desize = 0;
uint8_t *decoded_sig = NULL;
unsigned char digest[EVP_MAX_MD_SIZE];
if( jwt->header.key_len == 0 ) {
cjwt_error( "invalid rsa key\n" );
return EINVAL;
}
rsa = cjwt_create_rsa( jwt->header.key, jwt->header.key_len, 1 );
if( rsa == NULL ) {
cjwt_error( "key to rsa conversion failed\n" );
return EINVAL;
}
//decode p_sigb64
sz_sigb64 = strlen( ( char * )p_sigb64 );
sig_desize = b64url_get_decoded_buffer_size( sz_sigb64 );
//Because b64url_decode() always writes in blocks of 3 bytes for every 4
//characters even when the last 2 bytes are not used, we need up to 2
//extra bytes of output buffer to avoid a buffer overrun
decoded_sig = malloc( sig_desize + 2 );
if( !decoded_sig ) {
cjwt_error( "memory allocation failed\n" );
//free rsa
RSA_free( rsa );
cjwt_rsa_error();
return ENOMEM;
}
memset( decoded_sig, 0, sig_desize + 2 );
sig_desize = b64url_decode( ( uint8_t * )p_sigb64, sz_sigb64, decoded_sig );
cjwt_info( "----------------- signature ----------------- \n" );
cjwt_info( "Bytes = %d\n", ( int )sig_desize );
cjwt_info( "--------------------------------------------- \n" );
if( !sig_desize ) {
cjwt_error( "b64url_decode failed\n" );
goto end;
}
decoded_sig[sig_desize] = '\0';
//verify rsa
enc_len = strlen( p_enc );
switch( jwt->header.alg ) {
case alg_rs256:
SHA256( ( const unsigned char* ) p_enc, enc_len, digest );
ret = RSA_verify
( NID_sha256, digest, SHA256_DIGEST_LENGTH, decoded_sig,
( unsigned int ) sig_desize, rsa );
break;
case alg_rs384:
SHA384( ( const unsigned char * ) p_enc, enc_len, digest );
ret = RSA_verify
( NID_sha384, digest, SHA384_DIGEST_LENGTH, decoded_sig,
( unsigned int ) sig_desize, rsa );
break;
case alg_rs512:
SHA512( ( const unsigned char* ) p_enc, enc_len, digest );
ret = RSA_verify
( NID_sha512, digest, SHA512_DIGEST_LENGTH, decoded_sig,
( unsigned int ) sig_desize, rsa );
break;
default:
cjwt_error( "invalid rsa algorithm\n" );
ret = EINVAL;
break;
}
end:
RSA_free( rsa );
free( decoded_sig );
if( ret == 1 ) {
return 0;
}
cjwt_rsa_error();
return EINVAL;
}
static int cjwt_verify_signature( cjwt_t *p_jwt, char *p_in, const char *p_sign )
{
int ret = 0;
int sz_signed = 0;
unsigned char* signed_out = NULL;
if( !p_jwt || !p_in || !p_sign ) {
ret = EINVAL;
goto end;
}
if( IS_RSA_ALG( p_jwt->header.alg ) ) {
ret = cjwt_verify_rsa( p_jwt, p_in, p_sign );
goto end;
}
//sign
ret = cjwt_sign( p_jwt, &signed_out, p_in, &sz_signed );
if( ret ) {
ret = EINVAL;
goto end;
}
//decode signature from input token
size_t sz_p_sign = strlen( p_sign );
size_t sz_decoded = b64url_get_decoded_buffer_size( sz_p_sign );
uint8_t *signed_dec = malloc( sz_decoded + 1 );
if( !signed_dec ) {
ret = ENOMEM;
goto err_decode;
}
memset( signed_dec, 0, ( sz_decoded + 1 ) );
//decode
int out_size = b64url_decode( ( uint8_t * )p_sign, sz_p_sign, signed_dec );
if( !out_size ) {
ret = EINVAL;
goto err_match;
}
signed_dec[out_size] = '\0';
cjwt_info( "Signature length : enc %d, signature %d\n",
( int )sz_signed, ( int )out_size );
cjwt_info( "signed token : %s\n", signed_out );
cjwt_info( "expected token signature %s\n", signed_dec );
if( sz_signed != out_size ) {
cjwt_info( "Signature length mismatch: enc %d, signature %d\n",
( int )sz_signed, ( int )out_size );
ret = EINVAL;
goto err_match;
}
if( 0 != CRYPTO_memcmp(signed_out, signed_dec, out_size) ) {
ret = EINVAL;
}
err_match:
free( signed_dec );
err_decode:
free( signed_out );
end:
return ret;
}
static int cjwt_update_payload( cjwt_t *p_cjwt, char *p_decpl )
{
cJSON* j_val = NULL;
if( !p_cjwt || !p_decpl ) {
return EINVAL;
}
//create cJSON object
cJSON *j_payload = cJSON_Parse( ( char* )p_decpl );
if( !j_payload ) {
// The data is probably not json vs. memory allocation error.
return EINVAL;
}
//extract data
cjwt_info( "Json = %s\n", cJSON_Print( j_payload ) );
cjwt_info( "--------------------------------------------- \n\n" );
//iss
j_val = cJSON_GetObjectItem( j_payload, "iss" );
if( j_val ) {
if( p_cjwt->iss ) {
free( p_cjwt->iss );
p_cjwt->iss = NULL;
}
p_cjwt->iss = strdup(j_val->valuestring);
if( !p_cjwt->iss ) {
cJSON_Delete( j_payload );
return ENOMEM;
}
}
//sub
j_val = cJSON_GetObjectItem( j_payload, "sub" );
if( j_val ) {
if( p_cjwt->sub ) {
free( p_cjwt->sub );
p_cjwt->sub = NULL;
}
p_cjwt->sub = strdup(j_val->valuestring);
if( !p_cjwt->sub ) {
cJSON_Delete( j_payload );
return ENOMEM;
}
}
//aud
j_val = cJSON_GetObjectItem( j_payload, "aud" );
if( j_val ) {
if( j_val->type == cJSON_Object ) {
//array of strings
cJSON* j_tmp = NULL;
int cnt, i = 0;
char **ptr_values = NULL;
char *str_val = NULL;
cnt = cJSON_GetArraySize( j_val->child );
ptr_values = ( char** ) malloc( ( cnt ) * sizeof( char* ) );
if( !ptr_values ) {
cJSON_Delete( j_payload );
return ENOMEM;
}
for( i = 0; i < cnt; i++ ) {
j_tmp = cJSON_GetArrayItem( j_val->child, i );
cjwt_info( "aud[%d] Json = %s,type=%d,val=%s\n", i, cJSON_Print( j_tmp ), j_tmp->type, j_tmp->valuestring );
if( j_tmp->type == cJSON_String ) {
str_val = strdup(j_tmp->valuestring);
if( !str_val ) {
cJSON_Delete( j_payload );
i--;
while( i ) {
free( ptr_values[--i] );
}
free (ptr_values);
return ENOMEM;
}
ptr_values[i] = str_val;
}
}//for
p_cjwt_aud_list aud_new = malloc( sizeof( cjwt_aud_list_t ) );
if( !aud_new ) {
cJSON_Delete( j_payload );
while( cnt ) {
free( ptr_values[--cnt] );
}
free (ptr_values);
return ENOMEM;
}
aud_new->count = cnt;
aud_new->names = ptr_values;
p_cjwt->aud = aud_new;
}
}
//jti
j_val = cJSON_GetObjectItem( j_payload, "jti" );
if( j_val ) {
if( p_cjwt->jti ) {
free( p_cjwt->jti );
p_cjwt->jti = NULL;
}
p_cjwt->jti = strdup(j_val->valuestring);
if( !p_cjwt->jti ) {
cJSON_Delete( j_payload );
return ENOMEM;
}
}
//exp
j_val = cJSON_GetObjectItem( j_payload, "exp" );
if( j_val ) {
cjwt_info( "exp Json = %s,type=%d,int=%d,double=%f\n", cJSON_Print( j_val ), j_val->type, j_val->valueint, j_val->valuedouble );
if( j_val->type == cJSON_Number ) {
p_cjwt->exp.tv_sec = j_val->valueint;
p_cjwt->exp.tv_nsec = 0;
}
}
//nbf
j_val = cJSON_GetObjectItem( j_payload, "nbf" );
if( j_val ) {
cjwt_info( "nbf Json = %s,type=%d,int=%d,double=%f\n", cJSON_Print( j_val ), j_val->type, j_val->valueint, j_val->valuedouble );
if( j_val->type == cJSON_Number ) {
p_cjwt->nbf.tv_sec = j_val->valueint;
p_cjwt->nbf.tv_nsec = 0;
}
}
//iat
j_val = cJSON_GetObjectItem( j_payload, "iat" );
if( j_val ) {
cjwt_info( "iat Json = %s,type=%d,int=%d,double=%f\n", cJSON_Print( j_val ), j_val->type, j_val->valueint, j_val->valuedouble );
if( j_val->type == cJSON_Number ) {
p_cjwt->iat.tv_sec = j_val->valueint;
p_cjwt->iat.tv_nsec = 0;
}
}
//private_claims
cJSON* j_new = cJSON_Duplicate( j_payload, 1 );
if( j_new ) {
cjwt_delete_public_claims( j_new );
cjwt_info( "private claims count = %d\n", cJSON_GetArraySize( j_new ) );
if( cJSON_GetArraySize( j_new ) ) {
//cjwt_info( "private claims = %s\n", cJSON_Print( j_new ) );
if( p_cjwt->private_claims ) {
cJSON_Delete( p_cjwt->private_claims );
}
p_cjwt->private_claims = j_new;
} else {
cJSON_Delete ( j_new );
}
}
//destroy cJSON object
cJSON_Delete( j_payload );
return 0;
}
static int cjwt_update_header( cjwt_t *p_cjwt, char *p_dechead )
// The data is probably not json vs. memory allocation error.
{
if( !p_cjwt || !p_dechead ) {
return EINVAL;
}
//create cJSON object
cJSON *j_header = cJSON_Parse( ( char* )p_dechead );
if( !j_header ) {
// The data is probably not json vs. memory allocation error.
return EINVAL;
}
cjwt_info( "Json = %s\n", cJSON_Print( j_header ) );
cjwt_info( "--------------------------------------------- \n\n" );
//extract data
cJSON* j_typ = cJSON_GetObjectItem( j_header, "typ" );
if( !j_typ || strcmp( j_typ->valuestring, "JWT" ) ) {
cjwt_info( "may not be a JWT token\n" );
}
cJSON* j_alg = cJSON_GetObjectItem( j_header, "alg" );
if( j_alg ) {
int alg;
alg = cjwt_alg_str_to_enum( j_alg->valuestring );
if( -1 == alg ) {
cJSON_Delete( j_header );
return ENOTSUP;
}
p_cjwt->header.alg = alg;
}
//destroy cJSON object
cJSON_Delete( j_header );
return 0;
}
static int cjwt_parse_payload( cjwt_t *p_cjwt, char *p_payload )
{
int ret, sz_payload;
size_t pl_desize;
size_t out_size = 0;
uint8_t *decoded_pl;
if( !p_cjwt || !p_payload ) {
return EINVAL;
}
sz_payload = strlen( ( char * )p_payload );
pl_desize = b64url_get_decoded_buffer_size( sz_payload );
cjwt_info( "----------------- payload ------------------- \n" );
cjwt_info( "Payload Size = %d , Decoded size = %d\n", sz_payload, ( int )pl_desize );
decoded_pl = malloc( pl_desize + 1 );
if( !decoded_pl ) {
return ENOMEM;
}
memset( decoded_pl, 0, ( pl_desize + 1 ) );
//decode payload
out_size = b64url_decode( ( uint8_t * )p_payload, sz_payload, decoded_pl );
cjwt_info( "Bytes = %d\n", ( int )out_size );
if( !out_size ) {
ret = EINVAL;
goto end;
}
decoded_pl[out_size] = '\0';
cjwt_info( "Raw data = %*s\n", ( int )out_size, decoded_pl );
ret = cjwt_update_payload( p_cjwt, ( char* )decoded_pl );
end:
free( decoded_pl );
return ret;
}
static int cjwt_parse_header( cjwt_t *p_cjwt, char *p_head )
{
int sz_head, ret = 0;
size_t head_desize;
uint8_t *decoded_head;
size_t out_size = 0;
if( !p_cjwt || !p_head ) {
return EINVAL;
}
sz_head = strlen( ( char * )p_head );
head_desize = b64url_get_decoded_buffer_size( sz_head );
cjwt_info( "----------------- header -------------------- \n" );
cjwt_info( "Header Size = %d , Decoded size = %d\n", sz_head, ( int )head_desize );
decoded_head = malloc( head_desize + 1 );
if( !decoded_head ) {
return ENOMEM;
}
memset( decoded_head, 0, head_desize + 1 );
//decode header
out_size = b64url_decode( ( uint8_t * )p_head, sz_head, decoded_head );
cjwt_info( "Bytes = %d\n", ( int )out_size );
if( !out_size ) {
ret = EINVAL;
goto end;
}
decoded_head[out_size] = '\0';
cjwt_info( "Raw data = %*s\n", ( int )out_size, decoded_head );
ret = cjwt_update_header( p_cjwt, ( char* )decoded_head );
end:
free( decoded_head );
return ret;
}
static int cjwt_update_key( cjwt_t *p_cjwt, const uint8_t *key, size_t key_len )
{
int ret = 0;
if( ( NULL != key ) && ( key_len > 0 ) ) {
p_cjwt->header.key = malloc( key_len );
if( !p_cjwt->header.key ) {
ret = ENOMEM;
return ret;
}
memcpy( p_cjwt->header.key, key, key_len );
p_cjwt->header.key_len = key_len;
}
return ret;
}
static cjwt_t* cjwt_create()
{
cjwt_t *init = malloc( sizeof( cjwt_t ) );
if( init ) {
memset (init, 0, sizeof(cjwt_t));
}
return init;
}
/**
* validates jwt token and extracts data
*/
int cjwt_decode( const char *encoded, unsigned int options, cjwt_t **jwt,
const uint8_t *key, size_t key_len )
{
int ret = 0;
char *payload, *signature;
( void )options; //suppressing unused parameter warning
//validate inputs
if( !encoded || !jwt ) {
cjwt_error( "null parameter\n" );
ret = EINVAL;
goto error;
}
cjwt_info( "parameters cjwt_decode()\n encoded : %s\n options : %d\n", encoded, options );
//create copy
char *enc_token = malloc( strlen( encoded ) + 1 );
if( !enc_token ) {
cjwt_error( "memory alloc failed\n" );
ret = ENOMEM;
goto error;
}
strcpy( enc_token, encoded );
//tokenize the jwt token
for( payload = enc_token; payload[0] != '.'; payload++ ) {
if( payload[0] == '\0' ) {
cjwt_error( "Invalid jwt token,has only header\n" );
ret = EINVAL;
goto end;
}
}
payload[0] = '\0';
payload++;
for( signature = payload; signature[0] != '.'; signature++ ) {
if( signature[0] == '\0' ) {
cjwt_error( "Invalid jwt token,missing signature\n" );
ret = EINVAL;
goto end;
}
}
signature[0] = '\0';
signature++;
//create cjson
cjwt_t *out = cjwt_create();
if( !out ) {
cjwt_error( "cjwt memory alloc failed\n" );
ret = ENOMEM;
goto end;
}
//populate key
ret = cjwt_update_key( out, key, key_len );
if( ret ) {
cjwt_error( "Failed to update key\n" );
goto invalid;
}
//parse header
ret = cjwt_parse_header( out, enc_token );
if( ret ) {
cjwt_error( "Invalid header\n" );
goto invalid;
}
//parse payload
ret = cjwt_parse_payload( out, payload );
if( ret ) {
cjwt_error( "Invalid payload\n" );
goto invalid;
}
if( out->header.alg != alg_none ) {
enc_token[strlen( enc_token )] = '.';
//verify
ret = cjwt_verify_signature( out, enc_token, signature );
if( ret ) {
cjwt_error( "\nSignature authentication failed\n" );
goto invalid;
}
cjwt_info( "\nSignature authentication passed\n" );
}
invalid:
if( ret ) {
cjwt_destroy( &out );
*jwt = NULL;
} else {
*jwt = out;
}
end:
free( enc_token );
error:
return ret;
}
/**
* cleanup jwt object
*/
int cjwt_destroy( cjwt_t **jwt )
{
cjwt_t *del = *jwt;
*jwt = NULL;
if( !del ) {
return 0;
}
if(del->header.key)
{
free(del->header.key);
}
del->header.key = NULL;
if( del->iss ) {
free( del->iss );
}
del->iss = NULL;
if( del->sub ) {
free( del->sub );
}
del->sub = NULL;
if( del->aud ) {
char** tmp = del->aud->names;
int cnt_lst = del->aud->count;
free( del->aud );
del->aud = NULL;
while( cnt_lst ) {
free( tmp[--cnt_lst] );
}
}
if( del->jti ) {
free( del->jti );
}
del->jti = NULL;
if( del->private_claims ) {
cJSON_Delete( del->private_claims );
}
del->private_claims = NULL;
free (del);
return 0;
}
//end of file
| ./CrossVul/dataset_final_sorted/CWE-670/c/good_1286_1 |
crossvul-cpp_data_good_1052_1 | /* $OpenBSD: doas.c,v 1.57 2016/06/19 19:29:43 martijn Exp $ */
/*
* Copyright (c) 2015 Ted Unangst <tedu@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#if defined(HAVE_INTTYPES_H)
#include <inttypes.h>
#endif
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <syslog.h>
#include <errno.h>
#include <fcntl.h>
#if defined(HAVE_LOGIN_CAP_H)
#include <login_cap.h>
#endif
#if defined(USE_BSD_AUTH)
#include <bsd_auth.h>
#include <readpassphrase.h>
#endif
#if defined(USE_PAM)
#include <security/pam_appl.h>
#if defined(OPENPAM) /* BSD, MacOS & certain Linux distros */
#include <security/openpam.h>
static struct pam_conv pamc = { openpam_ttyconv, NULL };
#elif defined(__LINUX_PAM__) /* Linux */
#include <security/pam_misc.h>
static struct pam_conv pamc = { misc_conv, NULL };
#elif defined(SOLARIS_PAM) /* illumos & Solaris */
#include "pm_pam_conv.h"
static struct pam_conv pamc = { pam_tty_conv, NULL };
#endif /* OPENPAM */
#endif /* USE_PAM */
#include "doas.h"
static void
usage(void)
{
fprintf(stderr, "usage: doas [-ns] [-a style] [-C config] [-u user]"
" command [args]\n");
exit(1);
}
#ifdef linux
void
errc(int eval, int code, const char *format)
{
fprintf(stderr, "%s", format);
exit(code);
}
#endif
static int
parseuid(const char *s, uid_t *uid)
{
struct passwd *pw;
#if !defined(__linux__) && !defined(__NetBSD__)
const char *errstr = NULL;
#else
int status;
#endif
if ((pw = getpwnam(s)) != NULL) {
*uid = pw->pw_uid;
return 0;
}
#if !defined(__linux__) && !defined(__NetBSD__)
*uid = strtonum(s, 0, UID_MAX, &errstr);
if (errstr)
return -1;
#else
status = sscanf(s, "%d", uid);
if (status != 1)
return -1;
#endif
return 0;
}
static int
uidcheck(const char *s, uid_t desired)
{
uid_t uid;
if (parseuid(s, &uid) != 0)
return -1;
if (uid != desired)
return -1;
return 0;
}
static int
parsegid(const char *s, gid_t *gid)
{
struct group *gr;
#if !defined(__linux__) && !defined(__NetBSD__)
const char *errstr = NULL;
#else
int status;
#endif
if ((gr = getgrnam(s)) != NULL) {
*gid = gr->gr_gid;
return 0;
}
#if !defined(__linux__) && !defined(__NetBSD__)
*gid = strtonum(s, 0, GID_MAX, &errstr);
if (errstr)
return -1;
#else
status = sscanf(s, "%d", gid);
if (status != 1)
return -1;
#endif
return 0;
}
static int
match(uid_t uid, gid_t *groups, int ngroups, uid_t target, const char *cmd,
const char **cmdargs, struct rule *r)
{
int i;
if (r->ident[0] == ':') {
gid_t rgid;
if (parsegid(r->ident + 1, &rgid) == -1)
return 0;
for (i = 0; i < ngroups; i++) {
if (rgid == groups[i])
break;
}
if (i == ngroups)
return 0;
} else {
if (uidcheck(r->ident, uid) != 0)
return 0;
}
if (r->target && uidcheck(r->target, target) != 0)
return 0;
if (r->cmd) {
if (strcmp(r->cmd, cmd))
return 0;
if (r->cmdargs) {
/* if arguments were given, they should match explicitly */
for (i = 0; r->cmdargs[i]; i++) {
if (!cmdargs[i])
return 0;
if (strcmp(r->cmdargs[i], cmdargs[i]))
return 0;
}
if (cmdargs[i])
return 0;
}
}
return 1;
}
static int
permit(uid_t uid, gid_t *groups, int ngroups, struct rule **lastr,
uid_t target, const char *cmd, const char **cmdargs)
{
int i;
*lastr = NULL;
for (i = 0; i < nrules; i++) {
if (match(uid, groups, ngroups, target, cmd,
cmdargs, rules[i]))
*lastr = rules[i];
}
if (!*lastr)
return 0;
return (*lastr)->action == PERMIT;
}
static void
parseconfig(const char *filename, int checkperms)
{
extern FILE *yyfp;
extern int yyparse(void);
struct stat sb;
yyfp = fopen(filename, "r");
if (!yyfp)
err(1, checkperms ? "doas is not enabled, %s" :
"could not open config file %s", filename);
if (checkperms) {
if (fstat(fileno(yyfp), &sb) != 0)
err(1, "fstat(\"%s\")", filename);
if ((sb.st_mode & (S_IWGRP|S_IWOTH)) != 0)
errx(1, "%s is writable by group or other", filename);
if (sb.st_uid != 0)
errx(1, "%s is not owned by root", filename);
}
yyparse();
fclose(yyfp);
if (parse_errors)
exit(1);
}
static void
checkconfig(const char *confpath, int argc, char **argv,
uid_t uid, gid_t *groups, int ngroups, uid_t target)
{
struct rule *rule;
int status;
#if defined(__linux__) || defined(__FreeBSD__)
status = setresuid(uid, uid, uid);
#else
status = setreuid(uid, uid);
#endif
if (status == -1)
{
printf("doas: Unable to set UID\n");
exit(1);
}
parseconfig(confpath, 0);
if (!argc)
exit(0);
if (permit(uid, groups, ngroups, &rule, target, argv[0],
(const char **)argv + 1)) {
printf("permit%s\n", (rule->options & NOPASS) ? " nopass" : "");
exit(0);
} else {
printf("deny\n");
exit(1);
}
}
#if defined(USE_BSD_AUTH)
static void
authuser(char *myname, char *login_style, int persist)
{
char *challenge = NULL, *response, rbuf[1024], cbuf[128];
auth_session_t *as;
int fd = -1;
if (persist)
fd = open("/dev/tty", O_RDWR);
if (fd != -1) {
if (ioctl(fd, TIOCCHKVERAUTH) == 0)
goto good;
}
if (!(as = auth_userchallenge(myname, login_style, "auth-doas",
&challenge)))
errx(1, "Authorization failed");
if (!challenge) {
char host[HOST_NAME_MAX + 1];
if (gethostname(host, sizeof(host)))
snprintf(host, sizeof(host), "?");
snprintf(cbuf, sizeof(cbuf),
"\rdoas (%.32s@%.32s) password: ", myname, host);
challenge = cbuf;
}
response = readpassphrase(challenge, rbuf, sizeof(rbuf),
RPP_REQUIRE_TTY);
if (response == NULL && errno == ENOTTY) {
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"tty required for %s", myname);
errx(1, "a tty is required");
}
if (!auth_userresponse(as, response, 0)) {
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"failed auth for %s", myname);
errc(1, EPERM, NULL);
}
explicit_bzero(rbuf, sizeof(rbuf));
good:
if (fd != -1) {
int secs = 5 * 60;
ioctl(fd, TIOCSETVERAUTH, &secs);
close(fd);
}
}
#endif
int
main(int argc, char **argv)
{
const char *safepath = SAFE_PATH;
const char *confpath = NULL;
char *shargv[] = { NULL, NULL };
char *sh;
const char *cmd;
char cmdline[LINE_MAX];
char myname[_PW_NAME_LEN + 1];
struct passwd *original_pw, *target_pw;
struct rule *rule;
uid_t uid;
uid_t target = 0;
gid_t groups[NGROUPS_MAX + 1];
int ngroups;
int i, ch;
int sflag = 0;
int nflag = 0;
char cwdpath[PATH_MAX];
const char *cwd;
char *login_style = NULL;
char **envp;
#ifndef linux
setprogname("doas");
#endif
#ifndef linux
closefrom(STDERR_FILENO + 1);
#endif
uid = getuid();
while ((ch = getopt(argc, argv, "a:C:nsu:")) != -1) {
/* while ((ch = getopt(argc, argv, "a:C:Lnsu:")) != -1) { */
switch (ch) {
case 'a':
login_style = optarg;
break;
case 'C':
confpath = optarg;
break;
/* case 'L':
i = open("/dev/tty", O_RDWR);
if (i != -1)
ioctl(i, TIOCCLRVERAUTH);
exit(i != -1);
*/
case 'u':
if (parseuid(optarg, &target) != 0)
errx(1, "unknown user");
break;
case 'n':
nflag = 1;
break;
case 's':
sflag = 1;
break;
default:
usage();
break;
}
}
argv += optind;
argc -= optind;
if (confpath) {
if (sflag)
usage();
} else if ((!sflag && !argc) || (sflag && argc))
usage();
original_pw = getpwuid(uid);
if (! original_pw)
err(1, "getpwuid failed");
if (strlcpy(myname, original_pw->pw_name, sizeof(myname)) >= sizeof(myname))
errx(1, "pw_name too long");
ngroups = getgroups(NGROUPS_MAX, groups);
if (ngroups == -1)
err(1, "can't get groups");
groups[ngroups++] = getgid();
if (sflag) {
sh = getenv("SHELL");
if (sh == NULL || *sh == '\0') {
shargv[0] = strdup(original_pw->pw_shell);
if (shargv[0] == NULL)
err(1, NULL);
} else
shargv[0] = sh;
argv = shargv;
argc = 1;
}
if (confpath) {
checkconfig(confpath, argc, argv, uid, groups, ngroups,
target);
exit(1); /* fail safe */
}
if (geteuid())
errx(1, "not installed setuid");
parseconfig(DOAS_CONF, 1);
/* cmdline is used only for logging, no need to abort on truncate */
(void)strlcpy(cmdline, argv[0], sizeof(cmdline));
for (i = 1; i < argc; i++) {
if (strlcat(cmdline, " ", sizeof(cmdline)) >= sizeof(cmdline))
break;
if (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))
break;
}
cmd = argv[0];
if (!permit(uid, groups, ngroups, &rule, target, cmd,
(const char **)argv + 1)) {
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"failed command for %s: %s", myname, cmdline);
errc(1, EPERM, NULL);
}
if (!(rule->options & NOPASS)) {
if (nflag)
errx(1, "Authorization required");
#if defined(USE_BSD_AUTH)
authuser(myname, login_style, rule->options & PERSIST);
#elif defined(USE_PAM)
#define PAM_END(msg) do { \
syslog(LOG_ERR, "%s: %s", msg, pam_strerror(pamh, pam_err)); \
warnx("%s: %s", msg, pam_strerror(pamh, pam_err)); \
pam_end(pamh, pam_err); \
exit(EXIT_FAILURE); \
} while (/*CONSTCOND*/0)
pam_handle_t *pamh = NULL;
int pam_err;
/* #ifndef linux */
int temp_stdin;
/* openpam_ttyconv checks if stdin is a terminal and
* if it is then does not bother to open /dev/tty.
* The result is that PAM writes the password prompt
* directly to stdout. In scenarios where stdin is a
* terminal, but stdout is redirected to a file
* e.g. by running doas ls &> ls.out interactively,
* the password prompt gets written to ls.out as well.
* By closing stdin first we forces PAM to read/write
* to/from the terminal directly. We restore stdin
* after authenticating. */
temp_stdin = dup(STDIN_FILENO);
if (temp_stdin == -1)
err(1, "dup");
close(STDIN_FILENO);
/* #else */
/* force password prompt to display on stderr, not stdout */
int temp_stdout = dup(1);
if (temp_stdout == -1)
err(1, "dup");
close(1);
if (dup2(2, 1) == -1)
err(1, "dup2");
/* #endif */
pam_err = pam_start("doas", myname, &pamc, &pamh);
if (pam_err != PAM_SUCCESS) {
if (pamh != NULL)
PAM_END("pam_start");
syslog(LOG_ERR, "pam_start failed: %s",
pam_strerror(pamh, pam_err));
errx(EXIT_FAILURE, "pam_start failed");
}
switch (pam_err = pam_authenticate(pamh, PAM_SILENT)) {
case PAM_SUCCESS:
switch (pam_err = pam_acct_mgmt(pamh, PAM_SILENT)) {
case PAM_SUCCESS:
break;
case PAM_NEW_AUTHTOK_REQD:
pam_err = pam_chauthtok(pamh,
PAM_SILENT|PAM_CHANGE_EXPIRED_AUTHTOK);
if (pam_err != PAM_SUCCESS)
PAM_END("pam_chauthtok");
break;
case PAM_AUTH_ERR:
case PAM_USER_UNKNOWN:
case PAM_MAXTRIES:
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"failed auth for %s", myname);
errx(EXIT_FAILURE, "second authentication failed");
break;
default:
PAM_END("pam_acct_mgmt");
break;
}
break;
case PAM_AUTH_ERR:
case PAM_USER_UNKNOWN:
case PAM_MAXTRIES:
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"failed auth for %s", myname);
errx(EXIT_FAILURE, "authentication failed");
break;
default:
PAM_END("pam_authenticate");
break;
}
pam_end(pamh, pam_err);
#ifndef linux
/* Re-establish stdin */
if (dup2(temp_stdin, STDIN_FILENO) == -1)
err(1, "dup2");
close(temp_stdin);
#else
/* Re-establish stdout */
close(1);
if (dup2(temp_stdout, 1) == -1)
err(1, "dup2");
#endif
#else
#error No auth module!
#endif
}
/*
if (pledge("stdio rpath getpw exec id", NULL) == -1)
err(1, "pledge");
*/
target_pw = getpwuid(target);
if (! target_pw)
errx(1, "no passwd entry for target");
#if defined(HAVE_LOGIN_CAP_H)
if (setusercontext(NULL, target_pw, target, LOGIN_SETGROUP |
LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |
LOGIN_SETUSER) != 0)
errx(1, "failed to set user context for target");
#else
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
if (setresgid(target_pw->pw_gid, target_pw->pw_gid, target_pw->pw_gid) == -1)
err(1, "setresgid");
#else
if (setregid(target_pw->pw_gid, target_pw->pw_gid) == -1)
err(1, "setregid");
#endif
if (initgroups(target_pw->pw_name, target_pw->pw_gid) == -1)
err(1, "initgroups");
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
if (setresuid(target, target, target) == -1)
err(1, "setresuid");
#else
if (setreuid(target, target) == -1)
err(1, "setreuid");
#endif
#endif
/*
if (pledge("stdio rpath exec", NULL) == -1)
err(1, "pledge");
*/
if (getcwd(cwdpath, sizeof(cwdpath)) == NULL)
cwd = "(failed)";
else
cwd = cwdpath;
/*
if (pledge("stdio exec", NULL) == -1)
err(1, "pledge");
*/
syslog(LOG_AUTHPRIV | LOG_INFO, "%s ran command %s as %s from %s",
myname, cmdline, target_pw->pw_name, cwd);
envp = prepenv(rule, original_pw, target_pw);
if (rule->cmd) {
if (setenv("PATH", safepath, 1) == -1)
err(1, "failed to set PATH '%s'", safepath);
}
execvpe(cmd, argv, envp);
if (errno == ENOENT)
errx(1, "%s: command not found", cmd);
err(1, "%s", cmd);
}
| ./CrossVul/dataset_final_sorted/CWE-1187/c/good_1052_1 |
crossvul-cpp_data_bad_1052_1 | /* $OpenBSD: doas.c,v 1.57 2016/06/19 19:29:43 martijn Exp $ */
/*
* Copyright (c) 2015 Ted Unangst <tedu@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#if defined(HAVE_INTTYPES_H)
#include <inttypes.h>
#endif
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <syslog.h>
#include <errno.h>
#include <fcntl.h>
#if defined(HAVE_LOGIN_CAP_H)
#include <login_cap.h>
#endif
#if defined(USE_BSD_AUTH)
#include <bsd_auth.h>
#include <readpassphrase.h>
#endif
#if defined(USE_PAM)
#include <security/pam_appl.h>
#if defined(OPENPAM) /* BSD, MacOS & certain Linux distros */
#include <security/openpam.h>
static struct pam_conv pamc = { openpam_ttyconv, NULL };
#elif defined(__LINUX_PAM__) /* Linux */
#include <security/pam_misc.h>
static struct pam_conv pamc = { misc_conv, NULL };
#elif defined(SOLARIS_PAM) /* illumos & Solaris */
#include "pm_pam_conv.h"
static struct pam_conv pamc = { pam_tty_conv, NULL };
#endif /* OPENPAM */
#endif /* USE_PAM */
#include "doas.h"
static void
usage(void)
{
fprintf(stderr, "usage: doas [-ns] [-a style] [-C config] [-u user]"
" command [args]\n");
exit(1);
}
#ifdef linux
void
errc(int eval, int code, const char *format)
{
fprintf(stderr, "%s", format);
exit(code);
}
#endif
static int
parseuid(const char *s, uid_t *uid)
{
struct passwd *pw;
const char *errstr;
if ((pw = getpwnam(s)) != NULL) {
*uid = pw->pw_uid;
return 0;
}
#if !defined(__linux__) && !defined(__NetBSD__)
*uid = strtonum(s, 0, UID_MAX, &errstr);
#else
sscanf(s, "%d", uid);
#endif
if (errstr)
return -1;
return 0;
}
static int
uidcheck(const char *s, uid_t desired)
{
uid_t uid;
if (parseuid(s, &uid) != 0)
return -1;
if (uid != desired)
return -1;
return 0;
}
static int
parsegid(const char *s, gid_t *gid)
{
struct group *gr;
const char *errstr;
if ((gr = getgrnam(s)) != NULL) {
*gid = gr->gr_gid;
return 0;
}
#if !defined(__linux__) && !defined(__NetBSD__)
*gid = strtonum(s, 0, GID_MAX, &errstr);
#else
sscanf(s, "%d", gid);
#endif
if (errstr)
return -1;
return 0;
}
static int
match(uid_t uid, gid_t *groups, int ngroups, uid_t target, const char *cmd,
const char **cmdargs, struct rule *r)
{
int i;
if (r->ident[0] == ':') {
gid_t rgid;
if (parsegid(r->ident + 1, &rgid) == -1)
return 0;
for (i = 0; i < ngroups; i++) {
if (rgid == groups[i])
break;
}
if (i == ngroups)
return 0;
} else {
if (uidcheck(r->ident, uid) != 0)
return 0;
}
if (r->target && uidcheck(r->target, target) != 0)
return 0;
if (r->cmd) {
if (strcmp(r->cmd, cmd))
return 0;
if (r->cmdargs) {
/* if arguments were given, they should match explicitly */
for (i = 0; r->cmdargs[i]; i++) {
if (!cmdargs[i])
return 0;
if (strcmp(r->cmdargs[i], cmdargs[i]))
return 0;
}
if (cmdargs[i])
return 0;
}
}
return 1;
}
static int
permit(uid_t uid, gid_t *groups, int ngroups, struct rule **lastr,
uid_t target, const char *cmd, const char **cmdargs)
{
int i;
*lastr = NULL;
for (i = 0; i < nrules; i++) {
if (match(uid, groups, ngroups, target, cmd,
cmdargs, rules[i]))
*lastr = rules[i];
}
if (!*lastr)
return 0;
return (*lastr)->action == PERMIT;
}
static void
parseconfig(const char *filename, int checkperms)
{
extern FILE *yyfp;
extern int yyparse(void);
struct stat sb;
yyfp = fopen(filename, "r");
if (!yyfp)
err(1, checkperms ? "doas is not enabled, %s" :
"could not open config file %s", filename);
if (checkperms) {
if (fstat(fileno(yyfp), &sb) != 0)
err(1, "fstat(\"%s\")", filename);
if ((sb.st_mode & (S_IWGRP|S_IWOTH)) != 0)
errx(1, "%s is writable by group or other", filename);
if (sb.st_uid != 0)
errx(1, "%s is not owned by root", filename);
}
yyparse();
fclose(yyfp);
if (parse_errors)
exit(1);
}
static void
checkconfig(const char *confpath, int argc, char **argv,
uid_t uid, gid_t *groups, int ngroups, uid_t target)
{
struct rule *rule;
int status;
#if defined(__linux__) || defined(__FreeBSD__)
status = setresuid(uid, uid, uid);
#else
status = setreuid(uid, uid);
#endif
if (status == -1)
{
printf("doas: Unable to set UID\n");
exit(1);
}
parseconfig(confpath, 0);
if (!argc)
exit(0);
if (permit(uid, groups, ngroups, &rule, target, argv[0],
(const char **)argv + 1)) {
printf("permit%s\n", (rule->options & NOPASS) ? " nopass" : "");
exit(0);
} else {
printf("deny\n");
exit(1);
}
}
#if defined(USE_BSD_AUTH)
static void
authuser(char *myname, char *login_style, int persist)
{
char *challenge = NULL, *response, rbuf[1024], cbuf[128];
auth_session_t *as;
int fd = -1;
if (persist)
fd = open("/dev/tty", O_RDWR);
if (fd != -1) {
if (ioctl(fd, TIOCCHKVERAUTH) == 0)
goto good;
}
if (!(as = auth_userchallenge(myname, login_style, "auth-doas",
&challenge)))
errx(1, "Authorization failed");
if (!challenge) {
char host[HOST_NAME_MAX + 1];
if (gethostname(host, sizeof(host)))
snprintf(host, sizeof(host), "?");
snprintf(cbuf, sizeof(cbuf),
"\rdoas (%.32s@%.32s) password: ", myname, host);
challenge = cbuf;
}
response = readpassphrase(challenge, rbuf, sizeof(rbuf),
RPP_REQUIRE_TTY);
if (response == NULL && errno == ENOTTY) {
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"tty required for %s", myname);
errx(1, "a tty is required");
}
if (!auth_userresponse(as, response, 0)) {
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"failed auth for %s", myname);
errc(1, EPERM, NULL);
}
explicit_bzero(rbuf, sizeof(rbuf));
good:
if (fd != -1) {
int secs = 5 * 60;
ioctl(fd, TIOCSETVERAUTH, &secs);
close(fd);
}
}
#endif
int
main(int argc, char **argv)
{
const char *safepath = SAFE_PATH;
const char *confpath = NULL;
char *shargv[] = { NULL, NULL };
char *sh;
const char *cmd;
char cmdline[LINE_MAX];
char myname[_PW_NAME_LEN + 1];
struct passwd *original_pw, *target_pw;
struct rule *rule;
uid_t uid;
uid_t target = 0;
gid_t groups[NGROUPS_MAX + 1];
int ngroups;
int i, ch;
int sflag = 0;
int nflag = 0;
char cwdpath[PATH_MAX];
const char *cwd;
char *login_style = NULL;
char **envp;
#ifndef linux
setprogname("doas");
#endif
#ifndef linux
closefrom(STDERR_FILENO + 1);
#endif
uid = getuid();
while ((ch = getopt(argc, argv, "a:C:nsu:")) != -1) {
/* while ((ch = getopt(argc, argv, "a:C:Lnsu:")) != -1) { */
switch (ch) {
case 'a':
login_style = optarg;
break;
case 'C':
confpath = optarg;
break;
/* case 'L':
i = open("/dev/tty", O_RDWR);
if (i != -1)
ioctl(i, TIOCCLRVERAUTH);
exit(i != -1);
*/
case 'u':
if (parseuid(optarg, &target) != 0)
errx(1, "unknown user");
break;
case 'n':
nflag = 1;
break;
case 's':
sflag = 1;
break;
default:
usage();
break;
}
}
argv += optind;
argc -= optind;
if (confpath) {
if (sflag)
usage();
} else if ((!sflag && !argc) || (sflag && argc))
usage();
original_pw = getpwuid(uid);
if (! original_pw)
err(1, "getpwuid failed");
if (strlcpy(myname, original_pw->pw_name, sizeof(myname)) >= sizeof(myname))
errx(1, "pw_name too long");
ngroups = getgroups(NGROUPS_MAX, groups);
if (ngroups == -1)
err(1, "can't get groups");
groups[ngroups++] = getgid();
if (sflag) {
sh = getenv("SHELL");
if (sh == NULL || *sh == '\0') {
shargv[0] = strdup(original_pw->pw_shell);
if (shargv[0] == NULL)
err(1, NULL);
} else
shargv[0] = sh;
argv = shargv;
argc = 1;
}
if (confpath) {
checkconfig(confpath, argc, argv, uid, groups, ngroups,
target);
exit(1); /* fail safe */
}
if (geteuid())
errx(1, "not installed setuid");
parseconfig(DOAS_CONF, 1);
/* cmdline is used only for logging, no need to abort on truncate */
(void)strlcpy(cmdline, argv[0], sizeof(cmdline));
for (i = 1; i < argc; i++) {
if (strlcat(cmdline, " ", sizeof(cmdline)) >= sizeof(cmdline))
break;
if (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))
break;
}
cmd = argv[0];
if (!permit(uid, groups, ngroups, &rule, target, cmd,
(const char **)argv + 1)) {
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"failed command for %s: %s", myname, cmdline);
errc(1, EPERM, NULL);
}
if (!(rule->options & NOPASS)) {
if (nflag)
errx(1, "Authorization required");
#if defined(USE_BSD_AUTH)
authuser(myname, login_style, rule->options & PERSIST);
#elif defined(USE_PAM)
#define PAM_END(msg) do { \
syslog(LOG_ERR, "%s: %s", msg, pam_strerror(pamh, pam_err)); \
warnx("%s: %s", msg, pam_strerror(pamh, pam_err)); \
pam_end(pamh, pam_err); \
exit(EXIT_FAILURE); \
} while (/*CONSTCOND*/0)
pam_handle_t *pamh = NULL;
int pam_err;
/* #ifndef linux */
int temp_stdin;
/* openpam_ttyconv checks if stdin is a terminal and
* if it is then does not bother to open /dev/tty.
* The result is that PAM writes the password prompt
* directly to stdout. In scenarios where stdin is a
* terminal, but stdout is redirected to a file
* e.g. by running doas ls &> ls.out interactively,
* the password prompt gets written to ls.out as well.
* By closing stdin first we forces PAM to read/write
* to/from the terminal directly. We restore stdin
* after authenticating. */
temp_stdin = dup(STDIN_FILENO);
if (temp_stdin == -1)
err(1, "dup");
close(STDIN_FILENO);
/* #else */
/* force password prompt to display on stderr, not stdout */
int temp_stdout = dup(1);
if (temp_stdout == -1)
err(1, "dup");
close(1);
if (dup2(2, 1) == -1)
err(1, "dup2");
/* #endif */
pam_err = pam_start("doas", myname, &pamc, &pamh);
if (pam_err != PAM_SUCCESS) {
if (pamh != NULL)
PAM_END("pam_start");
syslog(LOG_ERR, "pam_start failed: %s",
pam_strerror(pamh, pam_err));
errx(EXIT_FAILURE, "pam_start failed");
}
switch (pam_err = pam_authenticate(pamh, PAM_SILENT)) {
case PAM_SUCCESS:
switch (pam_err = pam_acct_mgmt(pamh, PAM_SILENT)) {
case PAM_SUCCESS:
break;
case PAM_NEW_AUTHTOK_REQD:
pam_err = pam_chauthtok(pamh,
PAM_SILENT|PAM_CHANGE_EXPIRED_AUTHTOK);
if (pam_err != PAM_SUCCESS)
PAM_END("pam_chauthtok");
break;
case PAM_AUTH_ERR:
case PAM_USER_UNKNOWN:
case PAM_MAXTRIES:
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"failed auth for %s", myname);
errx(EXIT_FAILURE, "second authentication failed");
break;
default:
PAM_END("pam_acct_mgmt");
break;
}
break;
case PAM_AUTH_ERR:
case PAM_USER_UNKNOWN:
case PAM_MAXTRIES:
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"failed auth for %s", myname);
errx(EXIT_FAILURE, "authentication failed");
break;
default:
PAM_END("pam_authenticate");
break;
}
pam_end(pamh, pam_err);
#ifndef linux
/* Re-establish stdin */
if (dup2(temp_stdin, STDIN_FILENO) == -1)
err(1, "dup2");
close(temp_stdin);
#else
/* Re-establish stdout */
close(1);
if (dup2(temp_stdout, 1) == -1)
err(1, "dup2");
#endif
#else
#error No auth module!
#endif
}
/*
if (pledge("stdio rpath getpw exec id", NULL) == -1)
err(1, "pledge");
*/
target_pw = getpwuid(target);
if (! target_pw)
errx(1, "no passwd entry for target");
#if defined(HAVE_LOGIN_CAP_H)
if (setusercontext(NULL, target_pw, target, LOGIN_SETGROUP |
LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |
LOGIN_SETUSER) != 0)
errx(1, "failed to set user context for target");
#else
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
if (setresgid(target_pw->pw_gid, target_pw->pw_gid, target_pw->pw_gid) == -1)
err(1, "setresgid");
#else
if (setregid(target_pw->pw_gid, target_pw->pw_gid) == -1)
err(1, "setregid");
#endif
if (initgroups(target_pw->pw_name, target_pw->pw_gid) == -1)
err(1, "initgroups");
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
if (setresuid(target, target, target) == -1)
err(1, "setresuid");
#else
if (setreuid(target, target) == -1)
err(1, "setreuid");
#endif
#endif
/*
if (pledge("stdio rpath exec", NULL) == -1)
err(1, "pledge");
*/
if (getcwd(cwdpath, sizeof(cwdpath)) == NULL)
cwd = "(failed)";
else
cwd = cwdpath;
/*
if (pledge("stdio exec", NULL) == -1)
err(1, "pledge");
*/
syslog(LOG_AUTHPRIV | LOG_INFO, "%s ran command %s as %s from %s",
myname, cmdline, target_pw->pw_name, cwd);
envp = prepenv(rule, original_pw, target_pw);
if (rule->cmd) {
if (setenv("PATH", safepath, 1) == -1)
err(1, "failed to set PATH '%s'", safepath);
}
execvpe(cmd, argv, envp);
if (errno == ENOENT)
errx(1, "%s: command not found", cmd);
err(1, "%s", cmd);
}
| ./CrossVul/dataset_final_sorted/CWE-1187/c/bad_1052_1 |
crossvul-cpp_data_good_3128_0 | /*
* tasks.cpp - basic tasks
* Copyright (C) 2001, 2002 Justin Karneges
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <QRegExp>
#include <QList>
#include <QTimer>
#include "xmpp_tasks.h"
#include "xmpp_xmlcommon.h"
#include "xmpp_vcard.h"
#include "xmpp_bitsofbinary.h"
#include "xmpp_captcha.h"
#include "xmpp/base/timezone.h"
#include "xmpp_caps.h"
using namespace XMPP;
static QString lineEncode(QString str)
{
str.replace(QRegExp("\\\\"), "\\\\"); // backslash to double-backslash
str.replace(QRegExp("\\|"), "\\p"); // pipe to \p
str.replace(QRegExp("\n"), "\\n"); // newline to \n
return str;
}
static QString lineDecode(const QString &str)
{
QString ret;
for(int n = 0; n < str.length(); ++n) {
if(str.at(n) == '\\') {
++n;
if(n >= str.length())
break;
if(str.at(n) == 'n')
ret.append('\n');
if(str.at(n) == 'p')
ret.append('|');
if(str.at(n) == '\\')
ret.append('\\');
}
else {
ret.append(str.at(n));
}
}
return ret;
}
static Roster xmlReadRoster(const QDomElement &q, bool push)
{
Roster r;
for(QDomNode n = q.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if(i.tagName() == "item") {
RosterItem item;
item.fromXml(i);
if(push)
item.setIsPush(true);
r += item;
}
}
return r;
}
//----------------------------------------------------------------------------
// JT_Session
//----------------------------------------------------------------------------
//
#include "protocol.h"
JT_Session::JT_Session(Task *parent) : Task(parent)
{
}
void JT_Session::onGo()
{
QDomElement iq = createIQ(doc(), "set", "", id());
QDomElement session = doc()->createElement("session");
session.setAttribute("xmlns",NS_SESSION);
iq.appendChild(session);
send(iq);
}
bool JT_Session::take(const QDomElement& x)
{
QString from = x.attribute("from");
if (!from.endsWith("chat.facebook.com")) {
// remove this code when chat.facebook.com is disabled completely
from.clear();
}
if(!iqVerify(x, from, id()))
return false;
if(x.attribute("type") == "result") {
setSuccess();
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_Register
//----------------------------------------------------------------------------
class JT_Register::Private
{
public:
Private() {}
Form form;
XData xdata;
bool hasXData;
Jid jid;
int type;
};
JT_Register::JT_Register(Task *parent)
:Task(parent)
{
d = new Private;
d->type = -1;
d->hasXData = false;
}
JT_Register::~JT_Register()
{
delete d;
}
void JT_Register::reg(const QString &user, const QString &pass)
{
d->type = 0;
to = client()->host();
iq = createIQ(doc(), "set", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:register");
iq.appendChild(query);
query.appendChild(textTag(doc(), "username", user));
query.appendChild(textTag(doc(), "password", pass));
}
void JT_Register::changepw(const QString &pass)
{
d->type = 1;
to = client()->host();
iq = createIQ(doc(), "set", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:register");
iq.appendChild(query);
query.appendChild(textTag(doc(), "username", client()->user()));
query.appendChild(textTag(doc(), "password", pass));
}
void JT_Register::unreg(const Jid &j)
{
d->type = 2;
to = j.isEmpty() ? client()->host() : j.full();
iq = createIQ(doc(), "set", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:register");
iq.appendChild(query);
// this may be useful
if(!d->form.key().isEmpty())
query.appendChild(textTag(doc(), "key", d->form.key()));
query.appendChild(doc()->createElement("remove"));
}
void JT_Register::getForm(const Jid &j)
{
d->type = 3;
to = j;
iq = createIQ(doc(), "get", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:register");
iq.appendChild(query);
}
void JT_Register::setForm(const Form &form)
{
d->type = 4;
to = form.jid();
iq = createIQ(doc(), "set", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:register");
iq.appendChild(query);
// key?
if(!form.key().isEmpty())
query.appendChild(textTag(doc(), "key", form.key()));
// fields
for(Form::ConstIterator it = form.begin(); it != form.end(); ++it) {
const FormField &f = *it;
query.appendChild(textTag(doc(), f.realName(), f.value()));
}
}
void JT_Register::setForm(const Jid& to, const XData& xdata)
{
d->type = 4;
iq = createIQ(doc(), "set", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:register");
iq.appendChild(query);
query.appendChild(xdata.toXml(doc(), true));
}
const Form & JT_Register::form() const
{
return d->form;
}
bool JT_Register::hasXData() const
{
return d->hasXData;
}
const XData& JT_Register::xdata() const
{
return d->xdata;
}
void JT_Register::onGo()
{
send(iq);
}
bool JT_Register::take(const QDomElement &x)
{
if(!iqVerify(x, to, id()))
return false;
Jid from(x.attribute("from"));
if(x.attribute("type") == "result") {
if(d->type == 3) {
d->form.clear();
d->form.setJid(from);
QDomElement q = queryTag(x);
for(QDomNode n = q.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if(i.tagName() == "instructions")
d->form.setInstructions(tagContent(i));
else if(i.tagName() == "key")
d->form.setKey(tagContent(i));
else if(i.tagName() == "x" && i.attribute("xmlns") == "jabber:x:data") {
d->xdata.fromXml(i);
d->hasXData = true;
}
else if(i.tagName() == "data" && i.attribute("xmlns") == "urn:xmpp:bob") {
client()->bobManager()->append(BoBData(i)); // xep-0231
}
else {
FormField f;
if(f.setType(i.tagName())) {
f.setValue(tagContent(i));
d->form += f;
}
}
}
}
setSuccess();
}
else
setError(x);
return true;
}
//----------------------------------------------------------------------------
// JT_UnRegister
//----------------------------------------------------------------------------
class JT_UnRegister::Private
{
public:
Private() { }
Jid j;
JT_Register *jt_reg;
};
JT_UnRegister::JT_UnRegister(Task *parent)
: Task(parent)
{
d = new Private;
d->jt_reg = 0;
}
JT_UnRegister::~JT_UnRegister()
{
delete d->jt_reg;
delete d;
}
void JT_UnRegister::unreg(const Jid &j)
{
d->j = j;
}
void JT_UnRegister::onGo()
{
delete d->jt_reg;
d->jt_reg = new JT_Register(this);
d->jt_reg->getForm(d->j);
connect(d->jt_reg, SIGNAL(finished()), SLOT(getFormFinished()));
d->jt_reg->go(false);
}
void JT_UnRegister::getFormFinished()
{
disconnect(d->jt_reg, 0, this, 0);
d->jt_reg->unreg(d->j);
connect(d->jt_reg, SIGNAL(finished()), SLOT(unregFinished()));
d->jt_reg->go(false);
}
void JT_UnRegister::unregFinished()
{
if ( d->jt_reg->success() )
setSuccess();
else
setError(d->jt_reg->statusCode(), d->jt_reg->statusString());
delete d->jt_reg;
d->jt_reg = 0;
}
//----------------------------------------------------------------------------
// JT_Roster
//----------------------------------------------------------------------------
class JT_Roster::Private
{
public:
Private() {}
Roster roster;
QList<QDomElement> itemList;
};
JT_Roster::JT_Roster(Task *parent)
:Task(parent)
{
type = -1;
d = new Private;
}
JT_Roster::~JT_Roster()
{
delete d;
}
void JT_Roster::get()
{
type = 0;
//to = client()->host();
iq = createIQ(doc(), "get", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:roster");
iq.appendChild(query);
}
void JT_Roster::set(const Jid &jid, const QString &name, const QStringList &groups)
{
type = 1;
//to = client()->host();
QDomElement item = doc()->createElement("item");
item.setAttribute("jid", jid.full());
if(!name.isEmpty())
item.setAttribute("name", name);
for(QStringList::ConstIterator it = groups.begin(); it != groups.end(); ++it)
item.appendChild(textTag(doc(), "group", *it));
d->itemList += item;
}
void JT_Roster::remove(const Jid &jid)
{
type = 1;
//to = client()->host();
QDomElement item = doc()->createElement("item");
item.setAttribute("jid", jid.full());
item.setAttribute("subscription", "remove");
d->itemList += item;
}
void JT_Roster::onGo()
{
if(type == 0)
send(iq);
else if(type == 1) {
//to = client()->host();
iq = createIQ(doc(), "set", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:roster");
iq.appendChild(query);
foreach (const QDomElement& it, d->itemList)
query.appendChild(it);
send(iq);
}
}
const Roster & JT_Roster::roster() const
{
return d->roster;
}
QString JT_Roster::toString() const
{
if(type != 1)
return "";
QDomElement i = doc()->createElement("request");
i.setAttribute("type", "JT_Roster");
foreach (const QDomElement& it, d->itemList)
i.appendChild(it);
return lineEncode(Stream::xmlToString(i));
return "";
}
bool JT_Roster::fromString(const QString &str)
{
QDomDocument *dd = new QDomDocument;
if(!dd->setContent(lineDecode(str).toUtf8()))
return false;
QDomElement e = doc()->importNode(dd->documentElement(), true).toElement();
delete dd;
if(e.tagName() != "request" || e.attribute("type") != "JT_Roster")
return false;
type = 1;
d->itemList.clear();
for(QDomNode n = e.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
d->itemList += i;
}
return true;
}
bool JT_Roster::take(const QDomElement &x)
{
if(!iqVerify(x, client()->host(), id()))
return false;
// get
if(type == 0) {
if(x.attribute("type") == "result") {
QDomElement q = queryTag(x);
d->roster = xmlReadRoster(q, false);
setSuccess();
}
else {
setError(x);
}
return true;
}
// set
else if(type == 1) {
if(x.attribute("type") == "result")
setSuccess();
else
setError(x);
return true;
}
// remove
else if(type == 2) {
setSuccess();
return true;
}
return false;
}
//----------------------------------------------------------------------------
// JT_PushRoster
//----------------------------------------------------------------------------
JT_PushRoster::JT_PushRoster(Task *parent)
:Task(parent)
{
}
JT_PushRoster::~JT_PushRoster()
{
}
bool JT_PushRoster::take(const QDomElement &e)
{
// must be an iq-set tag
if(e.tagName() != "iq" || e.attribute("type") != "set")
return false;
if(!iqVerify(e, client()->host(), "", "jabber:iq:roster"))
return false;
roster(xmlReadRoster(queryTag(e), true));
send(createIQ(doc(), "result", e.attribute("from"), e.attribute("id")));
return true;
}
//----------------------------------------------------------------------------
// JT_Presence
//----------------------------------------------------------------------------
JT_Presence::JT_Presence(Task *parent)
:Task(parent)
{
type = -1;
}
JT_Presence::~JT_Presence()
{
}
void JT_Presence::pres(const Status &s)
{
type = 0;
tag = doc()->createElement("presence");
if(!s.isAvailable()) {
tag.setAttribute("type", "unavailable");
if(!s.status().isEmpty())
tag.appendChild(textTag(doc(), "status", s.status()));
}
else {
if(s.isInvisible())
tag.setAttribute("type", "invisible");
if(!s.show().isEmpty())
tag.appendChild(textTag(doc(), "show", s.show()));
if(!s.status().isEmpty())
tag.appendChild(textTag(doc(), "status", s.status()));
tag.appendChild( textTag(doc(), "priority", QString("%1").arg(s.priority()) ) );
if(!s.keyID().isEmpty()) {
QDomElement x = textTag(doc(), "x", s.keyID());
x.setAttribute("xmlns", "http://jabber.org/protocol/e2e");
tag.appendChild(x);
}
if(!s.xsigned().isEmpty()) {
QDomElement x = textTag(doc(), "x", s.xsigned());
x.setAttribute("xmlns", "jabber:x:signed");
tag.appendChild(x);
}
if (client()->capsManager()->isEnabled()) {
CapsSpec cs = client()->caps();
if (cs.isValid()) {
tag.appendChild(cs.toXml(doc()));
}
}
if(s.isMUC()) {
QDomElement m = doc()->createElement("x");
m.setAttribute("xmlns","http://jabber.org/protocol/muc");
if (!s.mucPassword().isEmpty()) {
m.appendChild(textTag(doc(),"password",s.mucPassword()));
}
if (s.hasMUCHistory()) {
QDomElement h = doc()->createElement("history");
if (s.mucHistoryMaxChars() >= 0)
h.setAttribute("maxchars",s.mucHistoryMaxChars());
if (s.mucHistoryMaxStanzas() >= 0)
h.setAttribute("maxstanzas",s.mucHistoryMaxStanzas());
if (s.mucHistorySeconds() >= 0)
h.setAttribute("seconds",s.mucHistorySeconds());
if (!s.mucHistorySince().isNull())
h.setAttribute("since", s.mucHistorySince().toUTC().addSecs(1).toString(Qt::ISODate));
m.appendChild(h);
}
tag.appendChild(m);
}
if(s.hasPhotoHash()) {
QDomElement m = doc()->createElement("x");
m.setAttribute("xmlns", "vcard-temp:x:update");
m.appendChild(textTag(doc(), "photo", s.photoHash()));
tag.appendChild(m);
}
// bits of binary
foreach(const BoBData &bd, s.bobDataList()) {
tag.appendChild(bd.toXml(doc()));
}
}
}
void JT_Presence::pres(const Jid &to, const Status &s)
{
pres(s);
tag.setAttribute("to", to.full());
}
void JT_Presence::sub(const Jid &to, const QString &subType, const QString& nick)
{
type = 1;
tag = doc()->createElement("presence");
tag.setAttribute("to", to.full());
tag.setAttribute("type", subType);
if (!nick.isEmpty()) {
QDomElement nick_tag = textTag(doc(),"nick",nick);
nick_tag.setAttribute("xmlns","http://jabber.org/protocol/nick");
tag.appendChild(nick_tag);
}
}
void JT_Presence::probe(const Jid &to)
{
type = 2;
tag = doc()->createElement("presence");
tag.setAttribute("to", to.full());
tag.setAttribute("type", "probe");
}
void JT_Presence::onGo()
{
send(tag);
setSuccess();
}
//----------------------------------------------------------------------------
// JT_PushPresence
//----------------------------------------------------------------------------
JT_PushPresence::JT_PushPresence(Task *parent)
:Task(parent)
{
}
JT_PushPresence::~JT_PushPresence()
{
}
bool JT_PushPresence::take(const QDomElement &e)
{
if(e.tagName() != "presence")
return false;
Jid j(e.attribute("from"));
Status p;
if(e.hasAttribute("type")) {
QString type = e.attribute("type");
if(type == "unavailable") {
p.setIsAvailable(false);
}
else if(type == "error") {
QString str = "";
int code = 0;
getErrorFromElement(e, client()->stream().baseNS(), &code, &str);
p.setError(code, str);
}
else if(type == "subscribe" || type == "subscribed" || type == "unsubscribe" || type == "unsubscribed") {
QString nick;
QDomElement tag = e.firstChildElement("nick");
if (!tag.isNull() && tag.attribute("xmlns") == "http://jabber.org/protocol/nick") {
nick = tagContent(tag);
}
subscription(j, type, nick);
return true;
}
}
QDomElement tag;
tag = e.firstChildElement("status");
if(!tag.isNull())
p.setStatus(tagContent(tag));
tag = e.firstChildElement("show");
if(!tag.isNull())
p.setShow(tagContent(tag));
tag = e.firstChildElement("priority");
if(!tag.isNull())
p.setPriority(tagContent(tag).toInt());
QDateTime stamp;
for(QDomNode n = e.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if(i.tagName() == "x" && i.attribute("xmlns") == "jabber:x:delay") {
if(i.hasAttribute("stamp") && !stamp.isValid()) {
stamp = stamp2TS(i.attribute("stamp"));
}
}
else if(i.tagName() == "delay" && i.attribute("xmlns") == "urn:xmpp:delay") {
if(i.hasAttribute("stamp") && !stamp.isValid()) {
stamp = QDateTime::fromString(i.attribute("stamp").left(19), Qt::ISODate);
}
}
else if(i.tagName() == "x" && i.attribute("xmlns") == "gabber:x:music:info") {
QDomElement t;
QString title, state;
t = i.firstChildElement("title");
if(!t.isNull())
title = tagContent(t);
t = i.firstChildElement("state");
if(!t.isNull())
state = tagContent(t);
if(!title.isEmpty() && state == "playing")
p.setSongTitle(title);
}
else if(i.tagName() == "x" && i.attribute("xmlns") == "jabber:x:signed") {
p.setXSigned(tagContent(i));
}
else if(i.tagName() == "x" && i.attribute("xmlns") == "http://jabber.org/protocol/e2e") {
p.setKeyID(tagContent(i));
}
else if(i.tagName() == "c" && i.attribute("xmlns") == NS_CAPS) {
p.setCaps(CapsSpec::fromXml(i));
if(!e.hasAttribute("type") && p.caps().isValid()) {
client()->capsManager()->updateCaps(j, p.caps());
}
}
else if(i.tagName() == "x" && i.attribute("xmlns") == "vcard-temp:x:update") {
QDomElement t;
t = i.firstChildElement("photo");
if (!t.isNull())
p.setPhotoHash(tagContent(t));
else
p.setPhotoHash("");
}
else if(i.tagName() == "x" && i.attribute("xmlns") == "http://jabber.org/protocol/muc#user") {
for(QDomNode muc_n = i.firstChild(); !muc_n.isNull(); muc_n = muc_n.nextSibling()) {
QDomElement muc_e = muc_n.toElement();
if(muc_e.isNull())
continue;
if (muc_e.tagName() == "item")
p.setMUCItem(MUCItem(muc_e));
else if (muc_e.tagName() == "status")
p.addMUCStatus(muc_e.attribute("code").toInt());
else if (muc_e.tagName() == "destroy")
p.setMUCDestroy(MUCDestroy(muc_e));
}
}
else if (i.tagName() == "data" && i.attribute("xmlns") == "urn:xmpp:bob") {
BoBData bd(i);
client()->bobManager()->append(bd);
p.addBoBData(bd);
}
}
if (stamp.isValid()) {
if (client()->manualTimeZoneOffset()) {
stamp = stamp.addSecs(client()->timeZoneOffset() * 3600);
} else {
stamp.setTimeSpec(Qt::UTC);
stamp = stamp.toLocalTime();
}
p.setTimeStamp(stamp);
}
presence(j, p);
return true;
}
//----------------------------------------------------------------------------
// JT_Message
//----------------------------------------------------------------------------
static QDomElement oldStyleNS(const QDomElement &e)
{
// find closest parent with a namespace
QDomNode par = e.parentNode();
while(!par.isNull() && par.namespaceURI().isNull())
par = par.parentNode();
bool noShowNS = false;
if(!par.isNull() && par.namespaceURI() == e.namespaceURI())
noShowNS = true;
QDomElement i;
int x;
//if(noShowNS)
i = e.ownerDocument().createElement(e.tagName());
//else
// i = e.ownerDocument().createElementNS(e.namespaceURI(), e.tagName());
// copy attributes
QDomNamedNodeMap al = e.attributes();
for(x = 0; x < al.count(); ++x)
i.setAttributeNode(al.item(x).cloneNode().toAttr());
if(!noShowNS)
i.setAttribute("xmlns", e.namespaceURI());
// copy children
QDomNodeList nl = e.childNodes();
for(x = 0; x < nl.count(); ++x) {
QDomNode n = nl.item(x);
if(n.isElement())
i.appendChild(oldStyleNS(n.toElement()));
else
i.appendChild(n.cloneNode());
}
return i;
}
JT_Message::JT_Message(Task *parent, const Message &msg)
:Task(parent)
{
m = msg;
if (m.id().isEmpty())
m.setId(id());
}
JT_Message::~JT_Message()
{
}
void JT_Message::onGo()
{
Stanza s = m.toStanza(&(client()->stream()));
QDomElement e = oldStyleNS(s.element());
send(e);
setSuccess();
}
//----------------------------------------------------------------------------
// JT_PushMessage
//----------------------------------------------------------------------------
JT_PushMessage::JT_PushMessage(Task *parent)
:Task(parent)
{
}
JT_PushMessage::~JT_PushMessage()
{
}
bool JT_PushMessage::take(const QDomElement &e)
{
if(e.tagName() != "message")
return false;
QDomElement e1 = e;
QDomElement forward;
Message::CarbonDir cd = Message::NoCarbon;
Jid fromJid = Jid(e1.attribute(QLatin1String("from")));
// Check for Carbon
QDomNodeList list = e1.childNodes();
for (int i = 0; i < list.size(); ++i) {
QDomElement el = list.at(i).toElement();
if (el.attribute("xmlns") == QLatin1String("urn:xmpp:carbons:2")
&& (el.tagName() == QLatin1String("received") || el.tagName() == QLatin1String("sent"))
&& fromJid.compare(Jid(e1.attribute(QLatin1String("to"))), false)) {
QDomElement el1 = el.firstChildElement();
if (el1.tagName() == QLatin1String("forwarded")
&& el1.attribute(QLatin1String("xmlns")) == QLatin1String("urn:xmpp:forward:0")) {
QDomElement el2 = el1.firstChildElement(QLatin1String("message"));
if (!el2.isNull()) {
forward = el2;
cd = el.tagName() == QLatin1String("received")? Message::Received : Message::Sent;
break;
}
}
}
else if (el.tagName() == QLatin1String("forwarded")
&& el.attribute(QLatin1String("xmlns")) == QLatin1String("urn:xmpp:forward:0")) {
forward = el.firstChildElement(QLatin1String("message")); // currently only messages are supportted
// TODO <delay> element support
if (!forward.isNull()) {
break;
}
}
}
Stanza s = client()->stream().createStanza(addCorrectNS(forward.isNull()? e1 : forward));
if(s.isNull()) {
//printf("take: bad stanza??\n");
return false;
}
Message m;
if(!m.fromStanza(s, client()->manualTimeZoneOffset(), client()->timeZoneOffset())) {
//printf("bad message\n");
return false;
}
if (!forward.isNull()) {
m.setForwardedFrom(fromJid);
m.setCarbonDirection(cd);
}
emit message(m);
return true;
}
//----------------------------------------------------------------------------
// JT_GetServices
//----------------------------------------------------------------------------
JT_GetServices::JT_GetServices(Task *parent)
:Task(parent)
{
}
void JT_GetServices::get(const Jid &j)
{
agentList.clear();
jid = j;
iq = createIQ(doc(), "get", jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:agents");
iq.appendChild(query);
}
const AgentList & JT_GetServices::agents() const
{
return agentList;
}
void JT_GetServices::onGo()
{
send(iq);
}
bool JT_GetServices::take(const QDomElement &x)
{
if(!iqVerify(x, jid, id()))
return false;
if(x.attribute("type") == "result") {
QDomElement q = queryTag(x);
// agents
for(QDomNode n = q.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if(i.tagName() == "agent") {
AgentItem a;
a.setJid(Jid(i.attribute("jid")));
QDomElement tag;
tag = i.firstChildElement("name");
if(!tag.isNull())
a.setName(tagContent(tag));
// determine which namespaces does item support
QStringList ns;
tag = i.firstChildElement("register");
if(!tag.isNull())
ns << "jabber:iq:register";
tag = i.firstChildElement("search");
if(!tag.isNull())
ns << "jabber:iq:search";
tag = i.firstChildElement("groupchat");
if(!tag.isNull())
ns << "jabber:iq:conference";
tag = i.firstChildElement("transport");
if(!tag.isNull())
ns << "jabber:iq:gateway";
a.setFeatures(ns);
agentList += a;
}
}
setSuccess(true);
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_VCard
//----------------------------------------------------------------------------
class JT_VCard::Private
{
public:
Private() {}
QDomElement iq;
Jid jid;
VCard vcard;
};
JT_VCard::JT_VCard(Task *parent)
:Task(parent)
{
type = -1;
d = new Private;
}
JT_VCard::~JT_VCard()
{
delete d;
}
void JT_VCard::get(const Jid &_jid)
{
type = 0;
d->jid = _jid;
d->iq = createIQ(doc(), "get", type == 1 ? Jid().full() : d->jid.full(), id());
QDomElement v = doc()->createElement("vCard");
v.setAttribute("xmlns", "vcard-temp");
d->iq.appendChild(v);
}
const Jid & JT_VCard::jid() const
{
return d->jid;
}
const VCard & JT_VCard::vcard() const
{
return d->vcard;
}
void JT_VCard::set(const VCard &card)
{
type = 1;
d->vcard = card;
d->jid = "";
d->iq = createIQ(doc(), "set", d->jid.full(), id());
d->iq.appendChild(card.toXml(doc()) );
}
// isTarget is when we setting target's vcard. for example in case of muc own vcard
void JT_VCard::set(const Jid &j, const VCard &card, bool isTarget)
{
type = 1;
d->vcard = card;
d->jid = j;
d->iq = createIQ(doc(), "set", isTarget? j.full() : "", id());
d->iq.appendChild(card.toXml(doc()) );
}
void JT_VCard::onGo()
{
send(d->iq);
}
bool JT_VCard::take(const QDomElement &x)
{
Jid to = d->jid;
if (to.bare() == client()->jid().bare())
to = client()->host();
if(!iqVerify(x, to, id()))
return false;
if(x.attribute("type") == "result") {
if(type == 0) {
for(QDomNode n = x.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement q = n.toElement();
if(q.isNull())
continue;
if(q.tagName().toUpper() == "VCARD") {
d->vcard = VCard::fromXml(q);
if(d->vcard) {
setSuccess();
return true;
}
}
}
setError(ErrDisc + 1, tr("No VCard available"));
return true;
}
else {
setSuccess();
return true;
}
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_Search
//----------------------------------------------------------------------------
class JT_Search::Private
{
public:
Private() {}
Jid jid;
Form form;
bool hasXData;
XData xdata;
QList<SearchResult> resultList;
};
JT_Search::JT_Search(Task *parent)
:Task(parent)
{
d = new Private;
type = -1;
}
JT_Search::~JT_Search()
{
delete d;
}
void JT_Search::get(const Jid &jid)
{
type = 0;
d->jid = jid;
d->hasXData = false;
d->xdata = XData();
iq = createIQ(doc(), "get", d->jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:search");
iq.appendChild(query);
}
void JT_Search::set(const Form &form)
{
type = 1;
d->jid = form.jid();
d->hasXData = false;
d->xdata = XData();
iq = createIQ(doc(), "set", d->jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:search");
iq.appendChild(query);
// key?
if(!form.key().isEmpty())
query.appendChild(textTag(doc(), "key", form.key()));
// fields
for(Form::ConstIterator it = form.begin(); it != form.end(); ++it) {
const FormField &f = *it;
query.appendChild(textTag(doc(), f.realName(), f.value()));
}
}
void JT_Search::set(const Jid &jid, const XData &form)
{
type = 1;
d->jid = jid;
d->hasXData = false;
d->xdata = XData();
iq = createIQ(doc(), "set", d->jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:search");
iq.appendChild(query);
query.appendChild(form.toXml(doc(), true));
}
const Form & JT_Search::form() const
{
return d->form;
}
const QList<SearchResult> & JT_Search::results() const
{
return d->resultList;
}
bool JT_Search::hasXData() const
{
return d->hasXData;
}
const XData & JT_Search::xdata() const
{
return d->xdata;
}
void JT_Search::onGo()
{
send(iq);
}
bool JT_Search::take(const QDomElement &x)
{
if(!iqVerify(x, d->jid, id()))
return false;
Jid from(x.attribute("from"));
if(x.attribute("type") == "result") {
if(type == 0) {
d->form.clear();
d->form.setJid(from);
QDomElement q = queryTag(x);
for(QDomNode n = q.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if(i.tagName() == "instructions")
d->form.setInstructions(tagContent(i));
else if(i.tagName() == "key")
d->form.setKey(tagContent(i));
else if(i.tagName() == "x" && i.attribute("xmlns") == "jabber:x:data") {
d->xdata.fromXml(i);
d->hasXData = true;
}
else {
FormField f;
if(f.setType(i.tagName())) {
f.setValue(tagContent(i));
d->form += f;
}
}
}
}
else {
d->resultList.clear();
QDomElement q = queryTag(x);
for(QDomNode n = q.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if(i.tagName() == "item") {
SearchResult r(Jid(i.attribute("jid")));
QDomElement tag;
tag = i.firstChildElement("nick");
if(!tag.isNull())
r.setNick(tagContent(tag));
tag = i.firstChildElement("first");
if(!tag.isNull())
r.setFirst(tagContent(tag));
tag = i.firstChildElement("last");
if(!tag.isNull())
r.setLast(tagContent(tag));
tag = i.firstChildElement("email");
if(!tag.isNull())
r.setEmail(tagContent(tag));
d->resultList += r;
}
else if(i.tagName() == "x" && i.attribute("xmlns") == "jabber:x:data") {
d->xdata.fromXml(i);
d->hasXData = true;
}
}
}
setSuccess();
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_ClientVersion
//----------------------------------------------------------------------------
JT_ClientVersion::JT_ClientVersion(Task *parent)
:Task(parent)
{
}
void JT_ClientVersion::get(const Jid &jid)
{
j = jid;
iq = createIQ(doc(), "get", j.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:version");
iq.appendChild(query);
}
void JT_ClientVersion::onGo()
{
send(iq);
}
bool JT_ClientVersion::take(const QDomElement &x)
{
if(!iqVerify(x, j, id()))
return false;
if(x.attribute("type") == "result") {
QDomElement q = queryTag(x);
QDomElement tag;
tag = q.firstChildElement("name");
if(!tag.isNull())
v_name = tagContent(tag);
tag = q.firstChildElement("version");
if(!tag.isNull())
v_ver = tagContent(tag);
tag = q.firstChildElement("os");
if(!tag.isNull())
v_os = tagContent(tag);
setSuccess();
}
else {
setError(x);
}
return true;
}
const Jid & JT_ClientVersion::jid() const
{
return j;
}
const QString & JT_ClientVersion::name() const
{
return v_name;
}
const QString & JT_ClientVersion::version() const
{
return v_ver;
}
const QString & JT_ClientVersion::os() const
{
return v_os;
}
//----------------------------------------------------------------------------
// JT_EntityTime
//----------------------------------------------------------------------------
JT_EntityTime::JT_EntityTime(Task* parent) : Task(parent)
{
}
/**
* \brief Queried entity's JID.
*/
const Jid & JT_EntityTime::jid() const
{
return j;
}
/**
* \brief Prepares the task to get information from JID.
*/
void JT_EntityTime::get(const Jid &jid)
{
j = jid;
iq = createIQ(doc(), "get", jid.full(), id());
QDomElement time = doc()->createElement("time");
time.setAttribute("xmlns", "urn:xmpp:time");
iq.appendChild(time);
}
void JT_EntityTime::onGo()
{
send(iq);
}
bool JT_EntityTime::take(const QDomElement &x)
{
if (!iqVerify(x, j, id()))
return false;
if (x.attribute("type") == "result") {
QDomElement q = x.firstChildElement("time");
QDomElement tag;
tag = q.firstChildElement("utc");
do {
if (tag.isNull()) {
break;
}
utc = QDateTime::fromString(tagContent(tag), Qt::ISODate);
tag = q.firstChildElement("tzo");
if (!utc.isValid() || tag.isNull()) {
break;
}
tzo = TimeZone::tzdToInt(tagContent(tag));
if (tzo == -1) {
break;
}
setSuccess();
return true;
}
while (false);
setError(406);
}
else {
setError(x);
}
return true;
}
const QDateTime & JT_EntityTime::dateTime() const
{
return utc;
}
int JT_EntityTime::timezoneOffset() const
{
return tzo;
}
//----------------------------------------------------------------------------
// JT_ServInfo
//----------------------------------------------------------------------------
JT_ServInfo::JT_ServInfo(Task *parent)
:Task(parent)
{
}
JT_ServInfo::~JT_ServInfo()
{
}
bool JT_ServInfo::take(const QDomElement &e)
{
if(e.tagName() != "iq" || e.attribute("type") != "get")
return false;
QString ns = queryNS(e);
if(ns == "jabber:iq:version") {
QDomElement iq = createIQ(doc(), "result", e.attribute("from"), e.attribute("id"));
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:version");
iq.appendChild(query);
query.appendChild(textTag(doc(), "name", client()->clientName()));
query.appendChild(textTag(doc(), "version", client()->clientVersion()));
query.appendChild(textTag(doc(), "os", client()->OSName() + ' ' + client()->OSVersion()));
send(iq);
return true;
}
else if(ns == "http://jabber.org/protocol/disco#info") {
// Find out the node
QString node;
QDomElement q = e.firstChildElement("query");
if(!q.isNull()) // NOTE: Should always be true, since a NS was found above
node = q.attribute("node");
if (node.isEmpty() || node == client()->caps().flatten()) {
QDomElement iq = createIQ(doc(), "result", e.attribute("from"), e.attribute("id"));
DiscoItem item = client()->makeDiscoResult(node);
iq.appendChild(item.toDiscoInfoResult(doc()));
send(iq);
}
else {
// Create error reply
QDomElement error_reply = createIQ(doc(), "result", e.attribute("from"), e.attribute("id"));
// Copy children
for (QDomNode n = e.firstChild(); !n.isNull(); n = n.nextSibling()) {
error_reply.appendChild(n.cloneNode());
}
// Add error
QDomElement error = doc()->createElement("error");
error.setAttribute("type","cancel");
error_reply.appendChild(error);
QDomElement error_type = doc()->createElement("item-not-found");
error_type.setAttribute("xmlns","urn:ietf:params:xml:ns:xmpp-stanzas");
error.appendChild(error_type);
send(error_reply);
}
return true;
}
if (!ns.isEmpty()) {
return false;
}
ns = e.firstChildElement("time").attribute("xmlns");
if (ns == "urn:xmpp:time") {
QDomElement iq = createIQ(doc(), "result", e.attribute("from"), e.attribute("id"));
QDomElement time = doc()->createElement("time");
time.setAttribute("xmlns", ns);
iq.appendChild(time);
QDateTime local = QDateTime::currentDateTime();
int off = TimeZone::offsetFromUtc();
QTime t = QTime(0, 0).addSecs(qAbs(off)*60);
QString tzo = (off < 0 ? "-" : "+") + t.toString("HH:mm");
time.appendChild(textTag(doc(), "tzo", tzo));
QString localTimeStr = local.toUTC().toString(Qt::ISODate);
if (!localTimeStr.endsWith("Z"))
localTimeStr.append("Z");
time.appendChild(textTag(doc(), "utc", localTimeStr));
send(iq);
return true;
}
return false;
}
//----------------------------------------------------------------------------
// JT_Gateway
//----------------------------------------------------------------------------
JT_Gateway::JT_Gateway(Task *parent)
:Task(parent)
{
type = -1;
}
void JT_Gateway::get(const Jid &jid)
{
type = 0;
v_jid = jid;
iq = createIQ(doc(), "get", v_jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:gateway");
iq.appendChild(query);
}
void JT_Gateway::set(const Jid &jid, const QString &prompt)
{
type = 1;
v_jid = jid;
v_prompt = prompt;
iq = createIQ(doc(), "set", v_jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:gateway");
iq.appendChild(query);
query.appendChild(textTag(doc(), "prompt", v_prompt));
}
void JT_Gateway::onGo()
{
send(iq);
}
Jid JT_Gateway::jid() const
{
return v_jid;
}
QString JT_Gateway::desc() const
{
return v_desc;
}
QString JT_Gateway::prompt() const
{
return v_prompt;
}
Jid JT_Gateway::translatedJid() const
{
return v_translatedJid;
}
bool JT_Gateway::take(const QDomElement &x)
{
if(!iqVerify(x, v_jid, id()))
return false;
if(x.attribute("type") == "result") {
if(type == 0) {
QDomElement query = queryTag(x);
QDomElement tag;
tag = query.firstChildElement("desc");
if (!tag.isNull()) {
v_desc = tagContent(tag);
}
tag = query.firstChildElement("prompt");
if (!tag.isNull()) {
v_prompt = tagContent(tag);
}
}
else {
QDomElement query = queryTag(x);
QDomElement tag;
tag = query.firstChildElement("jid");
if (!tag.isNull()) {
v_translatedJid = tagContent(tag);
}
// we used to read 'prompt' in the past
// and some gateways still send it
tag = query.firstChildElement("prompt");
if (!tag.isNull()) {
v_prompt = tagContent(tag);
}
}
setSuccess();
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_Browse
//----------------------------------------------------------------------------
class JT_Browse::Private
{
public:
QDomElement iq;
Jid jid;
AgentList agentList;
AgentItem root;
};
JT_Browse::JT_Browse (Task *parent)
:Task (parent)
{
d = new Private;
}
JT_Browse::~JT_Browse ()
{
delete d;
}
void JT_Browse::get (const Jid &j)
{
d->agentList.clear();
d->jid = j;
d->iq = createIQ(doc(), "get", d->jid.full(), id());
QDomElement query = doc()->createElement("item");
query.setAttribute("xmlns", "jabber:iq:browse");
d->iq.appendChild(query);
}
const AgentList & JT_Browse::agents() const
{
return d->agentList;
}
const AgentItem & JT_Browse::root() const
{
return d->root;
}
void JT_Browse::onGo ()
{
send(d->iq);
}
AgentItem JT_Browse::browseHelper (const QDomElement &i)
{
AgentItem a;
if ( i.tagName() == "ns" )
return a;
a.setName ( i.attribute("name") );
a.setJid ( i.attribute("jid") );
// there are two types of category/type specification:
//
// 1. <item category="category_name" type="type_name" />
// 2. <category_name type="type_name" />
if ( i.tagName() == "item" || i.tagName() == "query" )
a.setCategory ( i.attribute("category") );
else
a.setCategory ( i.tagName() );
a.setType ( i.attribute("type") );
QStringList ns;
for(QDomNode n = i.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if ( i.tagName() == "ns" )
ns << i.text();
}
// For now, conference.jabber.org returns proper namespace only
// when browsing individual rooms. So it's a quick client-side fix.
if ( !a.features().canGroupchat() && a.category() == "conference" )
ns << "jabber:iq:conference";
a.setFeatures (ns);
return a;
}
bool JT_Browse::take(const QDomElement &x)
{
if(!iqVerify(x, d->jid, id()))
return false;
if(x.attribute("type") == "result") {
for(QDomNode n = x.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
d->root = browseHelper (i);
for(QDomNode nn = i.firstChild(); !nn.isNull(); nn = nn.nextSibling()) {
QDomElement e = nn.toElement();
if ( e.isNull() )
continue;
if ( e.tagName() == "ns" )
continue;
d->agentList += browseHelper (e);
}
}
setSuccess(true);
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_DiscoItems
//----------------------------------------------------------------------------
class JT_DiscoItems::Private
{
public:
Private() { }
QDomElement iq;
Jid jid;
DiscoList items;
};
JT_DiscoItems::JT_DiscoItems(Task *parent)
: Task(parent)
{
d = new Private;
}
JT_DiscoItems::~JT_DiscoItems()
{
delete d;
}
void JT_DiscoItems::get(const DiscoItem &item)
{
get(item.jid(), item.node());
}
void JT_DiscoItems::get (const Jid &j, const QString &node)
{
d->items.clear();
d->jid = j;
d->iq = createIQ(doc(), "get", d->jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "http://jabber.org/protocol/disco#items");
if ( !node.isEmpty() )
query.setAttribute("node", node);
d->iq.appendChild(query);
}
const DiscoList &JT_DiscoItems::items() const
{
return d->items;
}
void JT_DiscoItems::onGo ()
{
send(d->iq);
}
bool JT_DiscoItems::take(const QDomElement &x)
{
if(!iqVerify(x, d->jid, id()))
return false;
if(x.attribute("type") == "result") {
QDomElement q = queryTag(x);
for(QDomNode n = q.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement e = n.toElement();
if( e.isNull() )
continue;
if ( e.tagName() == "item" ) {
DiscoItem item;
item.setJid ( e.attribute("jid") );
item.setName( e.attribute("name") );
item.setNode( e.attribute("node") );
item.setAction( DiscoItem::string2action(e.attribute("action")) );
d->items.append( item );
}
}
setSuccess(true);
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_DiscoPublish
//----------------------------------------------------------------------------
class JT_DiscoPublish::Private
{
public:
Private() { }
QDomElement iq;
Jid jid;
DiscoList list;
};
JT_DiscoPublish::JT_DiscoPublish(Task *parent)
: Task(parent)
{
d = new Private;
}
JT_DiscoPublish::~JT_DiscoPublish()
{
delete d;
}
void JT_DiscoPublish::set(const Jid &j, const DiscoList &list)
{
d->list = list;
d->jid = j;
d->iq = createIQ(doc(), "set", d->jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "http://jabber.org/protocol/disco#items");
// FIXME: unsure about this
//if ( !node.isEmpty() )
// query.setAttribute("node", node);
DiscoList::ConstIterator it = list.begin();
for ( ; it != list.end(); ++it) {
QDomElement w = doc()->createElement("item");
w.setAttribute("jid", (*it).jid().full());
if ( !(*it).name().isEmpty() )
w.setAttribute("name", (*it).name());
if ( !(*it).node().isEmpty() )
w.setAttribute("node", (*it).node());
w.setAttribute("action", DiscoItem::action2string((*it).action()));
query.appendChild( w );
}
d->iq.appendChild(query);
}
void JT_DiscoPublish::onGo ()
{
send(d->iq);
}
bool JT_DiscoPublish::take(const QDomElement &x)
{
if(!iqVerify(x, d->jid, id()))
return false;
if(x.attribute("type") == "result") {
setSuccess(true);
}
else {
setError(x);
}
return true;
}
// ---------------------------------------------------------
// JT_BoBServer
// ---------------------------------------------------------
JT_BoBServer::JT_BoBServer(Task *parent)
: Task(parent)
{
}
bool JT_BoBServer::take(const QDomElement &e)
{
if (e.tagName() != "iq" || e.attribute("type") != "get")
return false;
QDomElement data = e.firstChildElement("data");
if (data.attribute("xmlns") == "urn:xmpp:bob") {
QDomElement iq;
BoBData bd = client()->bobManager()->bobData(data.attribute("cid"));
if (bd.isNull()) {
iq = createIQ(client()->doc(), "error",
e.attribute("from"), e.attribute("id"));
Stanza::Error error(Stanza::Error::Cancel,
Stanza::Error::ItemNotFound);
iq.appendChild(error.toXml(*doc(), client()->stream().baseNS()));
}
else {
iq = createIQ(doc(), "result", e.attribute("from"), e.attribute("id"));
iq.appendChild(bd.toXml(doc()));
}
send(iq);
return true;
}
return false;
}
//----------------------------------------------------------------------------
// JT_BitsOfBinary
//----------------------------------------------------------------------------
class JT_BitsOfBinary::Private
{
public:
Private() { }
QDomElement iq;
Jid jid;
QString cid;
BoBData data;
};
JT_BitsOfBinary::JT_BitsOfBinary(Task *parent)
: Task(parent)
{
d = new Private;
}
JT_BitsOfBinary::~JT_BitsOfBinary()
{
delete d;
}
void JT_BitsOfBinary::get(const Jid &j, const QString &cid)
{
d->jid = j;
d->cid = cid;
d->data = client()->bobManager()->bobData(cid);
if (d->data.isNull()) {
d->iq = createIQ(doc(), "get", d->jid.full(), id());
QDomElement data = doc()->createElement("data");
data.setAttribute("xmlns", "urn:xmpp:bob");
data.setAttribute("cid", cid);
d->iq.appendChild(data);
}
}
void JT_BitsOfBinary::onGo()
{
if (d->data.isNull()) {
send(d->iq);
}
else {
setSuccess();
}
}
bool JT_BitsOfBinary::take(const QDomElement &x)
{
if (!iqVerify(x, d->jid, id())) {
return false;
}
if (x.attribute("type") == "result") {
QDomElement data = x.firstChildElement("data");
if (!data.isNull() && data.attribute("cid") == d->cid) { // check xmlns?
d->data.fromXml(data);
client()->bobManager()->append(d->data);
}
setSuccess();
}
else {
setError(x);
}
return true;
}
BoBData &JT_BitsOfBinary::data()
{
return d->data;
}
//----------------------------------------------------------------------------
// JT_PongServer
//----------------------------------------------------------------------------
/**
* \class JT_PongServer
* \brief Answers XMPP Pings
*/
JT_PongServer::JT_PongServer(Task *parent)
:Task(parent)
{
}
bool JT_PongServer::take(const QDomElement &e)
{
if (e.tagName() != "iq" || e.attribute("type") != "get")
return false;
QDomElement ping = e.firstChildElement("ping");
if (!e.isNull() && ping.attribute("xmlns") == "urn:xmpp:ping") {
QDomElement iq = createIQ(doc(), "result", e.attribute("from"), e.attribute("id"));
send(iq);
return true;
}
return false;
}
//---------------------------------------------------------------------------
// JT_CaptchaChallenger
//---------------------------------------------------------------------------
class JT_CaptchaChallenger::Private
{
public:
Jid j;
CaptchaChallenge challenge;
};
JT_CaptchaChallenger::JT_CaptchaChallenger(Task *parent) :
Task(parent),
d(new Private)
{
}
JT_CaptchaChallenger::~JT_CaptchaChallenger()
{
delete d;
}
void JT_CaptchaChallenger::set(const Jid &j, const CaptchaChallenge &c)
{
d->j = j;
d->challenge = c;
}
void JT_CaptchaChallenger::onGo()
{
setTimeout(CaptchaValidTimeout);
Message m;
m.setId(id());
m.setBody(d->challenge.explanation());
m.setUrlList(d->challenge.urls());
XData form = d->challenge.form();
XData::FieldList fl = form.fields();
XData::FieldList::Iterator it;
for (it = fl.begin(); it < fl.end(); ++it) {
if (it->var() == "challenge" && it->type() == XData::Field::Field_Hidden) {
it->setValue(QStringList() << id());
}
}
if (it == fl.end()) {
XData::Field f;
f.setType(XData::Field::Field_Hidden);
f.setVar("challenge");
f.setValue(QStringList() << id());
fl.append(f);
}
form.setFields(fl);
m.setForm(form);
m.setTo(d->j);
client()->sendMessage(m);
}
bool JT_CaptchaChallenger::take(const QDomElement &x)
{
if(x.tagName() == "message" && x.attribute("id") == id() &&
Jid(x.attribute("from")) == d->j && !x.firstChildElement("error").isNull())
{
setError(x);
return true;
}
XDomNodeList nl;
XData xd;
QString rid = x.attribute("id");
if (rid.isEmpty() || x.tagName() != "iq" ||
Jid(x.attribute("from")) != d->j || x.attribute("type") != "set" ||
(nl = childElementsByTagNameNS(x, "urn:xmpp:captcha", "captcha")).isEmpty() ||
(nl = childElementsByTagNameNS(nl.item(0).toElement(), "jabber:x:data", "x")).isEmpty() ||
(xd.fromXml(nl.item(0).toElement()), xd.getField("challenge").value().value(0) != id()))
{
return false;
}
CaptchaChallenge::Result r = d->challenge.validateResponse(xd);
QDomElement iq;
if (r == CaptchaChallenge::Passed) {
iq = createIQ(doc(), "result", d->j.full(), rid);
} else {
Stanza::Error::ErrorCond ec;
if (r == CaptchaChallenge::Unavailable) {
ec = Stanza::Error::ServiceUnavailable;
} else {
ec = Stanza::Error::NotAcceptable;
}
iq = createIQ(doc(), "error", d->j.full(), rid);
Stanza::Error error(Stanza::Error::Cancel, ec);
iq.appendChild(error.toXml(*doc(), client()->stream().baseNS()));
}
send(iq);
setSuccess();
return true;
}
//---------------------------------------------------------------------------
// JT_CaptchaSender
//---------------------------------------------------------------------------
JT_CaptchaSender::JT_CaptchaSender(Task *parent) :
Task(parent)
{}
void JT_CaptchaSender::set(const Jid &j, const XData &xd)
{
to = j;
iq = createIQ(doc(), "set", to.full(), id());
iq.appendChild(doc()->createElementNS("urn:xmpp:captcha", "captcha"))
.appendChild(xd.toXml(doc(), true));
}
void JT_CaptchaSender::onGo()
{
send(iq);
}
bool JT_CaptchaSender::take(const QDomElement &x)
{
if (!iqVerify(x, to, id())) {
return false;
}
if (x.attribute("type") == "result") {
setSuccess();
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_MessageCarbons
//----------------------------------------------------------------------------
JT_MessageCarbons::JT_MessageCarbons(Task *parent)
: Task(parent)
{
}
void JT_MessageCarbons::enable()
{
_iq = createIQ(doc(), "set", "", id());
QDomElement enable = doc()->createElement("enable");
enable.setAttribute("xmlns", "urn:xmpp:carbons:2");
_iq.appendChild(enable);
}
void JT_MessageCarbons::disable()
{
_iq = createIQ(doc(), "set", "", id());
QDomElement disable = doc()->createElement("disable");
disable.setAttribute("xmlns", "urn:xmpp:carbons:2");
_iq.appendChild(disable);
}
void JT_MessageCarbons::onGo()
{
send(_iq);
setSuccess();
}
bool JT_MessageCarbons::take(const QDomElement &e)
{
if (e.tagName() != "iq" || e.attribute("type") != "result")
return false;
bool res = iqVerify(e, Jid(), id());
return res;
}
| ./CrossVul/dataset_final_sorted/CWE-346/cpp/good_3128_0 |
crossvul-cpp_data_bad_3128_0 | /*
* tasks.cpp - basic tasks
* Copyright (C) 2001, 2002 Justin Karneges
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <QRegExp>
#include <QList>
#include <QTimer>
#include "xmpp_tasks.h"
#include "xmpp_xmlcommon.h"
#include "xmpp_vcard.h"
#include "xmpp_bitsofbinary.h"
#include "xmpp_captcha.h"
#include "xmpp/base/timezone.h"
#include "xmpp_caps.h"
using namespace XMPP;
static QString lineEncode(QString str)
{
str.replace(QRegExp("\\\\"), "\\\\"); // backslash to double-backslash
str.replace(QRegExp("\\|"), "\\p"); // pipe to \p
str.replace(QRegExp("\n"), "\\n"); // newline to \n
return str;
}
static QString lineDecode(const QString &str)
{
QString ret;
for(int n = 0; n < str.length(); ++n) {
if(str.at(n) == '\\') {
++n;
if(n >= str.length())
break;
if(str.at(n) == 'n')
ret.append('\n');
if(str.at(n) == 'p')
ret.append('|');
if(str.at(n) == '\\')
ret.append('\\');
}
else {
ret.append(str.at(n));
}
}
return ret;
}
static Roster xmlReadRoster(const QDomElement &q, bool push)
{
Roster r;
for(QDomNode n = q.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if(i.tagName() == "item") {
RosterItem item;
item.fromXml(i);
if(push)
item.setIsPush(true);
r += item;
}
}
return r;
}
//----------------------------------------------------------------------------
// JT_Session
//----------------------------------------------------------------------------
//
#include "protocol.h"
JT_Session::JT_Session(Task *parent) : Task(parent)
{
}
void JT_Session::onGo()
{
QDomElement iq = createIQ(doc(), "set", "", id());
QDomElement session = doc()->createElement("session");
session.setAttribute("xmlns",NS_SESSION);
iq.appendChild(session);
send(iq);
}
bool JT_Session::take(const QDomElement& x)
{
QString from = x.attribute("from");
if (!from.endsWith("chat.facebook.com")) {
// remove this code when chat.facebook.com is disabled completely
from.clear();
}
if(!iqVerify(x, from, id()))
return false;
if(x.attribute("type") == "result") {
setSuccess();
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_Register
//----------------------------------------------------------------------------
class JT_Register::Private
{
public:
Private() {}
Form form;
XData xdata;
bool hasXData;
Jid jid;
int type;
};
JT_Register::JT_Register(Task *parent)
:Task(parent)
{
d = new Private;
d->type = -1;
d->hasXData = false;
}
JT_Register::~JT_Register()
{
delete d;
}
void JT_Register::reg(const QString &user, const QString &pass)
{
d->type = 0;
to = client()->host();
iq = createIQ(doc(), "set", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:register");
iq.appendChild(query);
query.appendChild(textTag(doc(), "username", user));
query.appendChild(textTag(doc(), "password", pass));
}
void JT_Register::changepw(const QString &pass)
{
d->type = 1;
to = client()->host();
iq = createIQ(doc(), "set", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:register");
iq.appendChild(query);
query.appendChild(textTag(doc(), "username", client()->user()));
query.appendChild(textTag(doc(), "password", pass));
}
void JT_Register::unreg(const Jid &j)
{
d->type = 2;
to = j.isEmpty() ? client()->host() : j.full();
iq = createIQ(doc(), "set", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:register");
iq.appendChild(query);
// this may be useful
if(!d->form.key().isEmpty())
query.appendChild(textTag(doc(), "key", d->form.key()));
query.appendChild(doc()->createElement("remove"));
}
void JT_Register::getForm(const Jid &j)
{
d->type = 3;
to = j;
iq = createIQ(doc(), "get", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:register");
iq.appendChild(query);
}
void JT_Register::setForm(const Form &form)
{
d->type = 4;
to = form.jid();
iq = createIQ(doc(), "set", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:register");
iq.appendChild(query);
// key?
if(!form.key().isEmpty())
query.appendChild(textTag(doc(), "key", form.key()));
// fields
for(Form::ConstIterator it = form.begin(); it != form.end(); ++it) {
const FormField &f = *it;
query.appendChild(textTag(doc(), f.realName(), f.value()));
}
}
void JT_Register::setForm(const Jid& to, const XData& xdata)
{
d->type = 4;
iq = createIQ(doc(), "set", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:register");
iq.appendChild(query);
query.appendChild(xdata.toXml(doc(), true));
}
const Form & JT_Register::form() const
{
return d->form;
}
bool JT_Register::hasXData() const
{
return d->hasXData;
}
const XData& JT_Register::xdata() const
{
return d->xdata;
}
void JT_Register::onGo()
{
send(iq);
}
bool JT_Register::take(const QDomElement &x)
{
if(!iqVerify(x, to, id()))
return false;
Jid from(x.attribute("from"));
if(x.attribute("type") == "result") {
if(d->type == 3) {
d->form.clear();
d->form.setJid(from);
QDomElement q = queryTag(x);
for(QDomNode n = q.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if(i.tagName() == "instructions")
d->form.setInstructions(tagContent(i));
else if(i.tagName() == "key")
d->form.setKey(tagContent(i));
else if(i.tagName() == "x" && i.attribute("xmlns") == "jabber:x:data") {
d->xdata.fromXml(i);
d->hasXData = true;
}
else if(i.tagName() == "data" && i.attribute("xmlns") == "urn:xmpp:bob") {
client()->bobManager()->append(BoBData(i)); // xep-0231
}
else {
FormField f;
if(f.setType(i.tagName())) {
f.setValue(tagContent(i));
d->form += f;
}
}
}
}
setSuccess();
}
else
setError(x);
return true;
}
//----------------------------------------------------------------------------
// JT_UnRegister
//----------------------------------------------------------------------------
class JT_UnRegister::Private
{
public:
Private() { }
Jid j;
JT_Register *jt_reg;
};
JT_UnRegister::JT_UnRegister(Task *parent)
: Task(parent)
{
d = new Private;
d->jt_reg = 0;
}
JT_UnRegister::~JT_UnRegister()
{
delete d->jt_reg;
delete d;
}
void JT_UnRegister::unreg(const Jid &j)
{
d->j = j;
}
void JT_UnRegister::onGo()
{
delete d->jt_reg;
d->jt_reg = new JT_Register(this);
d->jt_reg->getForm(d->j);
connect(d->jt_reg, SIGNAL(finished()), SLOT(getFormFinished()));
d->jt_reg->go(false);
}
void JT_UnRegister::getFormFinished()
{
disconnect(d->jt_reg, 0, this, 0);
d->jt_reg->unreg(d->j);
connect(d->jt_reg, SIGNAL(finished()), SLOT(unregFinished()));
d->jt_reg->go(false);
}
void JT_UnRegister::unregFinished()
{
if ( d->jt_reg->success() )
setSuccess();
else
setError(d->jt_reg->statusCode(), d->jt_reg->statusString());
delete d->jt_reg;
d->jt_reg = 0;
}
//----------------------------------------------------------------------------
// JT_Roster
//----------------------------------------------------------------------------
class JT_Roster::Private
{
public:
Private() {}
Roster roster;
QList<QDomElement> itemList;
};
JT_Roster::JT_Roster(Task *parent)
:Task(parent)
{
type = -1;
d = new Private;
}
JT_Roster::~JT_Roster()
{
delete d;
}
void JT_Roster::get()
{
type = 0;
//to = client()->host();
iq = createIQ(doc(), "get", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:roster");
iq.appendChild(query);
}
void JT_Roster::set(const Jid &jid, const QString &name, const QStringList &groups)
{
type = 1;
//to = client()->host();
QDomElement item = doc()->createElement("item");
item.setAttribute("jid", jid.full());
if(!name.isEmpty())
item.setAttribute("name", name);
for(QStringList::ConstIterator it = groups.begin(); it != groups.end(); ++it)
item.appendChild(textTag(doc(), "group", *it));
d->itemList += item;
}
void JT_Roster::remove(const Jid &jid)
{
type = 1;
//to = client()->host();
QDomElement item = doc()->createElement("item");
item.setAttribute("jid", jid.full());
item.setAttribute("subscription", "remove");
d->itemList += item;
}
void JT_Roster::onGo()
{
if(type == 0)
send(iq);
else if(type == 1) {
//to = client()->host();
iq = createIQ(doc(), "set", to.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:roster");
iq.appendChild(query);
foreach (const QDomElement& it, d->itemList)
query.appendChild(it);
send(iq);
}
}
const Roster & JT_Roster::roster() const
{
return d->roster;
}
QString JT_Roster::toString() const
{
if(type != 1)
return "";
QDomElement i = doc()->createElement("request");
i.setAttribute("type", "JT_Roster");
foreach (const QDomElement& it, d->itemList)
i.appendChild(it);
return lineEncode(Stream::xmlToString(i));
return "";
}
bool JT_Roster::fromString(const QString &str)
{
QDomDocument *dd = new QDomDocument;
if(!dd->setContent(lineDecode(str).toUtf8()))
return false;
QDomElement e = doc()->importNode(dd->documentElement(), true).toElement();
delete dd;
if(e.tagName() != "request" || e.attribute("type") != "JT_Roster")
return false;
type = 1;
d->itemList.clear();
for(QDomNode n = e.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
d->itemList += i;
}
return true;
}
bool JT_Roster::take(const QDomElement &x)
{
if(!iqVerify(x, client()->host(), id()))
return false;
// get
if(type == 0) {
if(x.attribute("type") == "result") {
QDomElement q = queryTag(x);
d->roster = xmlReadRoster(q, false);
setSuccess();
}
else {
setError(x);
}
return true;
}
// set
else if(type == 1) {
if(x.attribute("type") == "result")
setSuccess();
else
setError(x);
return true;
}
// remove
else if(type == 2) {
setSuccess();
return true;
}
return false;
}
//----------------------------------------------------------------------------
// JT_PushRoster
//----------------------------------------------------------------------------
JT_PushRoster::JT_PushRoster(Task *parent)
:Task(parent)
{
}
JT_PushRoster::~JT_PushRoster()
{
}
bool JT_PushRoster::take(const QDomElement &e)
{
// must be an iq-set tag
if(e.tagName() != "iq" || e.attribute("type") != "set")
return false;
if(!iqVerify(e, client()->host(), "", "jabber:iq:roster"))
return false;
roster(xmlReadRoster(queryTag(e), true));
send(createIQ(doc(), "result", e.attribute("from"), e.attribute("id")));
return true;
}
//----------------------------------------------------------------------------
// JT_Presence
//----------------------------------------------------------------------------
JT_Presence::JT_Presence(Task *parent)
:Task(parent)
{
type = -1;
}
JT_Presence::~JT_Presence()
{
}
void JT_Presence::pres(const Status &s)
{
type = 0;
tag = doc()->createElement("presence");
if(!s.isAvailable()) {
tag.setAttribute("type", "unavailable");
if(!s.status().isEmpty())
tag.appendChild(textTag(doc(), "status", s.status()));
}
else {
if(s.isInvisible())
tag.setAttribute("type", "invisible");
if(!s.show().isEmpty())
tag.appendChild(textTag(doc(), "show", s.show()));
if(!s.status().isEmpty())
tag.appendChild(textTag(doc(), "status", s.status()));
tag.appendChild( textTag(doc(), "priority", QString("%1").arg(s.priority()) ) );
if(!s.keyID().isEmpty()) {
QDomElement x = textTag(doc(), "x", s.keyID());
x.setAttribute("xmlns", "http://jabber.org/protocol/e2e");
tag.appendChild(x);
}
if(!s.xsigned().isEmpty()) {
QDomElement x = textTag(doc(), "x", s.xsigned());
x.setAttribute("xmlns", "jabber:x:signed");
tag.appendChild(x);
}
if (client()->capsManager()->isEnabled()) {
CapsSpec cs = client()->caps();
if (cs.isValid()) {
tag.appendChild(cs.toXml(doc()));
}
}
if(s.isMUC()) {
QDomElement m = doc()->createElement("x");
m.setAttribute("xmlns","http://jabber.org/protocol/muc");
if (!s.mucPassword().isEmpty()) {
m.appendChild(textTag(doc(),"password",s.mucPassword()));
}
if (s.hasMUCHistory()) {
QDomElement h = doc()->createElement("history");
if (s.mucHistoryMaxChars() >= 0)
h.setAttribute("maxchars",s.mucHistoryMaxChars());
if (s.mucHistoryMaxStanzas() >= 0)
h.setAttribute("maxstanzas",s.mucHistoryMaxStanzas());
if (s.mucHistorySeconds() >= 0)
h.setAttribute("seconds",s.mucHistorySeconds());
if (!s.mucHistorySince().isNull())
h.setAttribute("since", s.mucHistorySince().toUTC().addSecs(1).toString(Qt::ISODate));
m.appendChild(h);
}
tag.appendChild(m);
}
if(s.hasPhotoHash()) {
QDomElement m = doc()->createElement("x");
m.setAttribute("xmlns", "vcard-temp:x:update");
m.appendChild(textTag(doc(), "photo", s.photoHash()));
tag.appendChild(m);
}
// bits of binary
foreach(const BoBData &bd, s.bobDataList()) {
tag.appendChild(bd.toXml(doc()));
}
}
}
void JT_Presence::pres(const Jid &to, const Status &s)
{
pres(s);
tag.setAttribute("to", to.full());
}
void JT_Presence::sub(const Jid &to, const QString &subType, const QString& nick)
{
type = 1;
tag = doc()->createElement("presence");
tag.setAttribute("to", to.full());
tag.setAttribute("type", subType);
if (!nick.isEmpty()) {
QDomElement nick_tag = textTag(doc(),"nick",nick);
nick_tag.setAttribute("xmlns","http://jabber.org/protocol/nick");
tag.appendChild(nick_tag);
}
}
void JT_Presence::probe(const Jid &to)
{
type = 2;
tag = doc()->createElement("presence");
tag.setAttribute("to", to.full());
tag.setAttribute("type", "probe");
}
void JT_Presence::onGo()
{
send(tag);
setSuccess();
}
//----------------------------------------------------------------------------
// JT_PushPresence
//----------------------------------------------------------------------------
JT_PushPresence::JT_PushPresence(Task *parent)
:Task(parent)
{
}
JT_PushPresence::~JT_PushPresence()
{
}
bool JT_PushPresence::take(const QDomElement &e)
{
if(e.tagName() != "presence")
return false;
Jid j(e.attribute("from"));
Status p;
if(e.hasAttribute("type")) {
QString type = e.attribute("type");
if(type == "unavailable") {
p.setIsAvailable(false);
}
else if(type == "error") {
QString str = "";
int code = 0;
getErrorFromElement(e, client()->stream().baseNS(), &code, &str);
p.setError(code, str);
}
else if(type == "subscribe" || type == "subscribed" || type == "unsubscribe" || type == "unsubscribed") {
QString nick;
QDomElement tag = e.firstChildElement("nick");
if (!tag.isNull() && tag.attribute("xmlns") == "http://jabber.org/protocol/nick") {
nick = tagContent(tag);
}
subscription(j, type, nick);
return true;
}
}
QDomElement tag;
tag = e.firstChildElement("status");
if(!tag.isNull())
p.setStatus(tagContent(tag));
tag = e.firstChildElement("show");
if(!tag.isNull())
p.setShow(tagContent(tag));
tag = e.firstChildElement("priority");
if(!tag.isNull())
p.setPriority(tagContent(tag).toInt());
QDateTime stamp;
for(QDomNode n = e.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if(i.tagName() == "x" && i.attribute("xmlns") == "jabber:x:delay") {
if(i.hasAttribute("stamp") && !stamp.isValid()) {
stamp = stamp2TS(i.attribute("stamp"));
}
}
else if(i.tagName() == "delay" && i.attribute("xmlns") == "urn:xmpp:delay") {
if(i.hasAttribute("stamp") && !stamp.isValid()) {
stamp = QDateTime::fromString(i.attribute("stamp").left(19), Qt::ISODate);
}
}
else if(i.tagName() == "x" && i.attribute("xmlns") == "gabber:x:music:info") {
QDomElement t;
QString title, state;
t = i.firstChildElement("title");
if(!t.isNull())
title = tagContent(t);
t = i.firstChildElement("state");
if(!t.isNull())
state = tagContent(t);
if(!title.isEmpty() && state == "playing")
p.setSongTitle(title);
}
else if(i.tagName() == "x" && i.attribute("xmlns") == "jabber:x:signed") {
p.setXSigned(tagContent(i));
}
else if(i.tagName() == "x" && i.attribute("xmlns") == "http://jabber.org/protocol/e2e") {
p.setKeyID(tagContent(i));
}
else if(i.tagName() == "c" && i.attribute("xmlns") == NS_CAPS) {
p.setCaps(CapsSpec::fromXml(i));
if(!e.hasAttribute("type") && p.caps().isValid()) {
client()->capsManager()->updateCaps(j, p.caps());
}
}
else if(i.tagName() == "x" && i.attribute("xmlns") == "vcard-temp:x:update") {
QDomElement t;
t = i.firstChildElement("photo");
if (!t.isNull())
p.setPhotoHash(tagContent(t));
else
p.setPhotoHash("");
}
else if(i.tagName() == "x" && i.attribute("xmlns") == "http://jabber.org/protocol/muc#user") {
for(QDomNode muc_n = i.firstChild(); !muc_n.isNull(); muc_n = muc_n.nextSibling()) {
QDomElement muc_e = muc_n.toElement();
if(muc_e.isNull())
continue;
if (muc_e.tagName() == "item")
p.setMUCItem(MUCItem(muc_e));
else if (muc_e.tagName() == "status")
p.addMUCStatus(muc_e.attribute("code").toInt());
else if (muc_e.tagName() == "destroy")
p.setMUCDestroy(MUCDestroy(muc_e));
}
}
else if (i.tagName() == "data" && i.attribute("xmlns") == "urn:xmpp:bob") {
BoBData bd(i);
client()->bobManager()->append(bd);
p.addBoBData(bd);
}
}
if (stamp.isValid()) {
if (client()->manualTimeZoneOffset()) {
stamp = stamp.addSecs(client()->timeZoneOffset() * 3600);
} else {
stamp.setTimeSpec(Qt::UTC);
stamp = stamp.toLocalTime();
}
p.setTimeStamp(stamp);
}
presence(j, p);
return true;
}
//----------------------------------------------------------------------------
// JT_Message
//----------------------------------------------------------------------------
static QDomElement oldStyleNS(const QDomElement &e)
{
// find closest parent with a namespace
QDomNode par = e.parentNode();
while(!par.isNull() && par.namespaceURI().isNull())
par = par.parentNode();
bool noShowNS = false;
if(!par.isNull() && par.namespaceURI() == e.namespaceURI())
noShowNS = true;
QDomElement i;
int x;
//if(noShowNS)
i = e.ownerDocument().createElement(e.tagName());
//else
// i = e.ownerDocument().createElementNS(e.namespaceURI(), e.tagName());
// copy attributes
QDomNamedNodeMap al = e.attributes();
for(x = 0; x < al.count(); ++x)
i.setAttributeNode(al.item(x).cloneNode().toAttr());
if(!noShowNS)
i.setAttribute("xmlns", e.namespaceURI());
// copy children
QDomNodeList nl = e.childNodes();
for(x = 0; x < nl.count(); ++x) {
QDomNode n = nl.item(x);
if(n.isElement())
i.appendChild(oldStyleNS(n.toElement()));
else
i.appendChild(n.cloneNode());
}
return i;
}
JT_Message::JT_Message(Task *parent, const Message &msg)
:Task(parent)
{
m = msg;
if (m.id().isEmpty())
m.setId(id());
}
JT_Message::~JT_Message()
{
}
void JT_Message::onGo()
{
Stanza s = m.toStanza(&(client()->stream()));
QDomElement e = oldStyleNS(s.element());
send(e);
setSuccess();
}
//----------------------------------------------------------------------------
// JT_PushMessage
//----------------------------------------------------------------------------
JT_PushMessage::JT_PushMessage(Task *parent)
:Task(parent)
{
}
JT_PushMessage::~JT_PushMessage()
{
}
bool JT_PushMessage::take(const QDomElement &e)
{
if(e.tagName() != "message")
return false;
QDomElement e1 = e;
QDomElement forward;
Message::CarbonDir cd = Message::NoCarbon;
// Check for Carbon
QDomNodeList list = e1.childNodes();
for (int i = 0; i < list.size(); ++i) {
QDomElement el = list.at(i).toElement();
if (el.attribute("xmlns") == QLatin1String("urn:xmpp:carbons:2") && (el.tagName() == QLatin1String("received") || el.tagName() == QLatin1String("sent"))) {
QDomElement el1 = el.firstChildElement();
if (el1.tagName() == QLatin1String("forwarded") && el1.attribute(QLatin1String("xmlns")) == QLatin1String("urn:xmpp:forward:0")) {
QDomElement el2 = el1.firstChildElement(QLatin1String("message"));
if (!el2.isNull()) {
forward = el2;
cd = el.tagName() == QLatin1String("received")? Message::Received : Message::Sent;
break;
}
}
}
else if (el.tagName() == QLatin1String("forwarded") && el.attribute(QLatin1String("xmlns")) == QLatin1String("urn:xmpp:forward:0")) {
forward = el.firstChildElement(QLatin1String("message")); // currently only messages are supportted
// TODO <delay> element support
if (!forward.isNull()) {
break;
}
}
}
QString from = e1.attribute(QLatin1String("from"));
Stanza s = client()->stream().createStanza(addCorrectNS(forward.isNull()? e1 : forward));
if(s.isNull()) {
//printf("take: bad stanza??\n");
return false;
}
Message m;
if(!m.fromStanza(s, client()->manualTimeZoneOffset(), client()->timeZoneOffset())) {
//printf("bad message\n");
return false;
}
if (!forward.isNull()) {
m.setForwardedFrom(Jid(from));
m.setCarbonDirection(cd);
}
emit message(m);
return true;
}
//----------------------------------------------------------------------------
// JT_GetServices
//----------------------------------------------------------------------------
JT_GetServices::JT_GetServices(Task *parent)
:Task(parent)
{
}
void JT_GetServices::get(const Jid &j)
{
agentList.clear();
jid = j;
iq = createIQ(doc(), "get", jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:agents");
iq.appendChild(query);
}
const AgentList & JT_GetServices::agents() const
{
return agentList;
}
void JT_GetServices::onGo()
{
send(iq);
}
bool JT_GetServices::take(const QDomElement &x)
{
if(!iqVerify(x, jid, id()))
return false;
if(x.attribute("type") == "result") {
QDomElement q = queryTag(x);
// agents
for(QDomNode n = q.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if(i.tagName() == "agent") {
AgentItem a;
a.setJid(Jid(i.attribute("jid")));
QDomElement tag;
tag = i.firstChildElement("name");
if(!tag.isNull())
a.setName(tagContent(tag));
// determine which namespaces does item support
QStringList ns;
tag = i.firstChildElement("register");
if(!tag.isNull())
ns << "jabber:iq:register";
tag = i.firstChildElement("search");
if(!tag.isNull())
ns << "jabber:iq:search";
tag = i.firstChildElement("groupchat");
if(!tag.isNull())
ns << "jabber:iq:conference";
tag = i.firstChildElement("transport");
if(!tag.isNull())
ns << "jabber:iq:gateway";
a.setFeatures(ns);
agentList += a;
}
}
setSuccess(true);
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_VCard
//----------------------------------------------------------------------------
class JT_VCard::Private
{
public:
Private() {}
QDomElement iq;
Jid jid;
VCard vcard;
};
JT_VCard::JT_VCard(Task *parent)
:Task(parent)
{
type = -1;
d = new Private;
}
JT_VCard::~JT_VCard()
{
delete d;
}
void JT_VCard::get(const Jid &_jid)
{
type = 0;
d->jid = _jid;
d->iq = createIQ(doc(), "get", type == 1 ? Jid().full() : d->jid.full(), id());
QDomElement v = doc()->createElement("vCard");
v.setAttribute("xmlns", "vcard-temp");
d->iq.appendChild(v);
}
const Jid & JT_VCard::jid() const
{
return d->jid;
}
const VCard & JT_VCard::vcard() const
{
return d->vcard;
}
void JT_VCard::set(const VCard &card)
{
type = 1;
d->vcard = card;
d->jid = "";
d->iq = createIQ(doc(), "set", d->jid.full(), id());
d->iq.appendChild(card.toXml(doc()) );
}
// isTarget is when we setting target's vcard. for example in case of muc own vcard
void JT_VCard::set(const Jid &j, const VCard &card, bool isTarget)
{
type = 1;
d->vcard = card;
d->jid = j;
d->iq = createIQ(doc(), "set", isTarget? j.full() : "", id());
d->iq.appendChild(card.toXml(doc()) );
}
void JT_VCard::onGo()
{
send(d->iq);
}
bool JT_VCard::take(const QDomElement &x)
{
Jid to = d->jid;
if (to.bare() == client()->jid().bare())
to = client()->host();
if(!iqVerify(x, to, id()))
return false;
if(x.attribute("type") == "result") {
if(type == 0) {
for(QDomNode n = x.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement q = n.toElement();
if(q.isNull())
continue;
if(q.tagName().toUpper() == "VCARD") {
d->vcard = VCard::fromXml(q);
if(d->vcard) {
setSuccess();
return true;
}
}
}
setError(ErrDisc + 1, tr("No VCard available"));
return true;
}
else {
setSuccess();
return true;
}
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_Search
//----------------------------------------------------------------------------
class JT_Search::Private
{
public:
Private() {}
Jid jid;
Form form;
bool hasXData;
XData xdata;
QList<SearchResult> resultList;
};
JT_Search::JT_Search(Task *parent)
:Task(parent)
{
d = new Private;
type = -1;
}
JT_Search::~JT_Search()
{
delete d;
}
void JT_Search::get(const Jid &jid)
{
type = 0;
d->jid = jid;
d->hasXData = false;
d->xdata = XData();
iq = createIQ(doc(), "get", d->jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:search");
iq.appendChild(query);
}
void JT_Search::set(const Form &form)
{
type = 1;
d->jid = form.jid();
d->hasXData = false;
d->xdata = XData();
iq = createIQ(doc(), "set", d->jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:search");
iq.appendChild(query);
// key?
if(!form.key().isEmpty())
query.appendChild(textTag(doc(), "key", form.key()));
// fields
for(Form::ConstIterator it = form.begin(); it != form.end(); ++it) {
const FormField &f = *it;
query.appendChild(textTag(doc(), f.realName(), f.value()));
}
}
void JT_Search::set(const Jid &jid, const XData &form)
{
type = 1;
d->jid = jid;
d->hasXData = false;
d->xdata = XData();
iq = createIQ(doc(), "set", d->jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:search");
iq.appendChild(query);
query.appendChild(form.toXml(doc(), true));
}
const Form & JT_Search::form() const
{
return d->form;
}
const QList<SearchResult> & JT_Search::results() const
{
return d->resultList;
}
bool JT_Search::hasXData() const
{
return d->hasXData;
}
const XData & JT_Search::xdata() const
{
return d->xdata;
}
void JT_Search::onGo()
{
send(iq);
}
bool JT_Search::take(const QDomElement &x)
{
if(!iqVerify(x, d->jid, id()))
return false;
Jid from(x.attribute("from"));
if(x.attribute("type") == "result") {
if(type == 0) {
d->form.clear();
d->form.setJid(from);
QDomElement q = queryTag(x);
for(QDomNode n = q.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if(i.tagName() == "instructions")
d->form.setInstructions(tagContent(i));
else if(i.tagName() == "key")
d->form.setKey(tagContent(i));
else if(i.tagName() == "x" && i.attribute("xmlns") == "jabber:x:data") {
d->xdata.fromXml(i);
d->hasXData = true;
}
else {
FormField f;
if(f.setType(i.tagName())) {
f.setValue(tagContent(i));
d->form += f;
}
}
}
}
else {
d->resultList.clear();
QDomElement q = queryTag(x);
for(QDomNode n = q.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if(i.tagName() == "item") {
SearchResult r(Jid(i.attribute("jid")));
QDomElement tag;
tag = i.firstChildElement("nick");
if(!tag.isNull())
r.setNick(tagContent(tag));
tag = i.firstChildElement("first");
if(!tag.isNull())
r.setFirst(tagContent(tag));
tag = i.firstChildElement("last");
if(!tag.isNull())
r.setLast(tagContent(tag));
tag = i.firstChildElement("email");
if(!tag.isNull())
r.setEmail(tagContent(tag));
d->resultList += r;
}
else if(i.tagName() == "x" && i.attribute("xmlns") == "jabber:x:data") {
d->xdata.fromXml(i);
d->hasXData = true;
}
}
}
setSuccess();
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_ClientVersion
//----------------------------------------------------------------------------
JT_ClientVersion::JT_ClientVersion(Task *parent)
:Task(parent)
{
}
void JT_ClientVersion::get(const Jid &jid)
{
j = jid;
iq = createIQ(doc(), "get", j.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:version");
iq.appendChild(query);
}
void JT_ClientVersion::onGo()
{
send(iq);
}
bool JT_ClientVersion::take(const QDomElement &x)
{
if(!iqVerify(x, j, id()))
return false;
if(x.attribute("type") == "result") {
QDomElement q = queryTag(x);
QDomElement tag;
tag = q.firstChildElement("name");
if(!tag.isNull())
v_name = tagContent(tag);
tag = q.firstChildElement("version");
if(!tag.isNull())
v_ver = tagContent(tag);
tag = q.firstChildElement("os");
if(!tag.isNull())
v_os = tagContent(tag);
setSuccess();
}
else {
setError(x);
}
return true;
}
const Jid & JT_ClientVersion::jid() const
{
return j;
}
const QString & JT_ClientVersion::name() const
{
return v_name;
}
const QString & JT_ClientVersion::version() const
{
return v_ver;
}
const QString & JT_ClientVersion::os() const
{
return v_os;
}
//----------------------------------------------------------------------------
// JT_EntityTime
//----------------------------------------------------------------------------
JT_EntityTime::JT_EntityTime(Task* parent) : Task(parent)
{
}
/**
* \brief Queried entity's JID.
*/
const Jid & JT_EntityTime::jid() const
{
return j;
}
/**
* \brief Prepares the task to get information from JID.
*/
void JT_EntityTime::get(const Jid &jid)
{
j = jid;
iq = createIQ(doc(), "get", jid.full(), id());
QDomElement time = doc()->createElement("time");
time.setAttribute("xmlns", "urn:xmpp:time");
iq.appendChild(time);
}
void JT_EntityTime::onGo()
{
send(iq);
}
bool JT_EntityTime::take(const QDomElement &x)
{
if (!iqVerify(x, j, id()))
return false;
if (x.attribute("type") == "result") {
QDomElement q = x.firstChildElement("time");
QDomElement tag;
tag = q.firstChildElement("utc");
do {
if (tag.isNull()) {
break;
}
utc = QDateTime::fromString(tagContent(tag), Qt::ISODate);
tag = q.firstChildElement("tzo");
if (!utc.isValid() || tag.isNull()) {
break;
}
tzo = TimeZone::tzdToInt(tagContent(tag));
if (tzo == -1) {
break;
}
setSuccess();
return true;
}
while (false);
setError(406);
}
else {
setError(x);
}
return true;
}
const QDateTime & JT_EntityTime::dateTime() const
{
return utc;
}
int JT_EntityTime::timezoneOffset() const
{
return tzo;
}
//----------------------------------------------------------------------------
// JT_ServInfo
//----------------------------------------------------------------------------
JT_ServInfo::JT_ServInfo(Task *parent)
:Task(parent)
{
}
JT_ServInfo::~JT_ServInfo()
{
}
bool JT_ServInfo::take(const QDomElement &e)
{
if(e.tagName() != "iq" || e.attribute("type") != "get")
return false;
QString ns = queryNS(e);
if(ns == "jabber:iq:version") {
QDomElement iq = createIQ(doc(), "result", e.attribute("from"), e.attribute("id"));
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:version");
iq.appendChild(query);
query.appendChild(textTag(doc(), "name", client()->clientName()));
query.appendChild(textTag(doc(), "version", client()->clientVersion()));
query.appendChild(textTag(doc(), "os", client()->OSName() + ' ' + client()->OSVersion()));
send(iq);
return true;
}
else if(ns == "http://jabber.org/protocol/disco#info") {
// Find out the node
QString node;
QDomElement q = e.firstChildElement("query");
if(!q.isNull()) // NOTE: Should always be true, since a NS was found above
node = q.attribute("node");
if (node.isEmpty() || node == client()->caps().flatten()) {
QDomElement iq = createIQ(doc(), "result", e.attribute("from"), e.attribute("id"));
DiscoItem item = client()->makeDiscoResult(node);
iq.appendChild(item.toDiscoInfoResult(doc()));
send(iq);
}
else {
// Create error reply
QDomElement error_reply = createIQ(doc(), "result", e.attribute("from"), e.attribute("id"));
// Copy children
for (QDomNode n = e.firstChild(); !n.isNull(); n = n.nextSibling()) {
error_reply.appendChild(n.cloneNode());
}
// Add error
QDomElement error = doc()->createElement("error");
error.setAttribute("type","cancel");
error_reply.appendChild(error);
QDomElement error_type = doc()->createElement("item-not-found");
error_type.setAttribute("xmlns","urn:ietf:params:xml:ns:xmpp-stanzas");
error.appendChild(error_type);
send(error_reply);
}
return true;
}
if (!ns.isEmpty()) {
return false;
}
ns = e.firstChildElement("time").attribute("xmlns");
if (ns == "urn:xmpp:time") {
QDomElement iq = createIQ(doc(), "result", e.attribute("from"), e.attribute("id"));
QDomElement time = doc()->createElement("time");
time.setAttribute("xmlns", ns);
iq.appendChild(time);
QDateTime local = QDateTime::currentDateTime();
int off = TimeZone::offsetFromUtc();
QTime t = QTime(0, 0).addSecs(qAbs(off)*60);
QString tzo = (off < 0 ? "-" : "+") + t.toString("HH:mm");
time.appendChild(textTag(doc(), "tzo", tzo));
QString localTimeStr = local.toUTC().toString(Qt::ISODate);
if (!localTimeStr.endsWith("Z"))
localTimeStr.append("Z");
time.appendChild(textTag(doc(), "utc", localTimeStr));
send(iq);
return true;
}
return false;
}
//----------------------------------------------------------------------------
// JT_Gateway
//----------------------------------------------------------------------------
JT_Gateway::JT_Gateway(Task *parent)
:Task(parent)
{
type = -1;
}
void JT_Gateway::get(const Jid &jid)
{
type = 0;
v_jid = jid;
iq = createIQ(doc(), "get", v_jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:gateway");
iq.appendChild(query);
}
void JT_Gateway::set(const Jid &jid, const QString &prompt)
{
type = 1;
v_jid = jid;
v_prompt = prompt;
iq = createIQ(doc(), "set", v_jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "jabber:iq:gateway");
iq.appendChild(query);
query.appendChild(textTag(doc(), "prompt", v_prompt));
}
void JT_Gateway::onGo()
{
send(iq);
}
Jid JT_Gateway::jid() const
{
return v_jid;
}
QString JT_Gateway::desc() const
{
return v_desc;
}
QString JT_Gateway::prompt() const
{
return v_prompt;
}
Jid JT_Gateway::translatedJid() const
{
return v_translatedJid;
}
bool JT_Gateway::take(const QDomElement &x)
{
if(!iqVerify(x, v_jid, id()))
return false;
if(x.attribute("type") == "result") {
if(type == 0) {
QDomElement query = queryTag(x);
QDomElement tag;
tag = query.firstChildElement("desc");
if (!tag.isNull()) {
v_desc = tagContent(tag);
}
tag = query.firstChildElement("prompt");
if (!tag.isNull()) {
v_prompt = tagContent(tag);
}
}
else {
QDomElement query = queryTag(x);
QDomElement tag;
tag = query.firstChildElement("jid");
if (!tag.isNull()) {
v_translatedJid = tagContent(tag);
}
// we used to read 'prompt' in the past
// and some gateways still send it
tag = query.firstChildElement("prompt");
if (!tag.isNull()) {
v_prompt = tagContent(tag);
}
}
setSuccess();
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_Browse
//----------------------------------------------------------------------------
class JT_Browse::Private
{
public:
QDomElement iq;
Jid jid;
AgentList agentList;
AgentItem root;
};
JT_Browse::JT_Browse (Task *parent)
:Task (parent)
{
d = new Private;
}
JT_Browse::~JT_Browse ()
{
delete d;
}
void JT_Browse::get (const Jid &j)
{
d->agentList.clear();
d->jid = j;
d->iq = createIQ(doc(), "get", d->jid.full(), id());
QDomElement query = doc()->createElement("item");
query.setAttribute("xmlns", "jabber:iq:browse");
d->iq.appendChild(query);
}
const AgentList & JT_Browse::agents() const
{
return d->agentList;
}
const AgentItem & JT_Browse::root() const
{
return d->root;
}
void JT_Browse::onGo ()
{
send(d->iq);
}
AgentItem JT_Browse::browseHelper (const QDomElement &i)
{
AgentItem a;
if ( i.tagName() == "ns" )
return a;
a.setName ( i.attribute("name") );
a.setJid ( i.attribute("jid") );
// there are two types of category/type specification:
//
// 1. <item category="category_name" type="type_name" />
// 2. <category_name type="type_name" />
if ( i.tagName() == "item" || i.tagName() == "query" )
a.setCategory ( i.attribute("category") );
else
a.setCategory ( i.tagName() );
a.setType ( i.attribute("type") );
QStringList ns;
for(QDomNode n = i.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
if ( i.tagName() == "ns" )
ns << i.text();
}
// For now, conference.jabber.org returns proper namespace only
// when browsing individual rooms. So it's a quick client-side fix.
if ( !a.features().canGroupchat() && a.category() == "conference" )
ns << "jabber:iq:conference";
a.setFeatures (ns);
return a;
}
bool JT_Browse::take(const QDomElement &x)
{
if(!iqVerify(x, d->jid, id()))
return false;
if(x.attribute("type") == "result") {
for(QDomNode n = x.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement i = n.toElement();
if(i.isNull())
continue;
d->root = browseHelper (i);
for(QDomNode nn = i.firstChild(); !nn.isNull(); nn = nn.nextSibling()) {
QDomElement e = nn.toElement();
if ( e.isNull() )
continue;
if ( e.tagName() == "ns" )
continue;
d->agentList += browseHelper (e);
}
}
setSuccess(true);
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_DiscoItems
//----------------------------------------------------------------------------
class JT_DiscoItems::Private
{
public:
Private() { }
QDomElement iq;
Jid jid;
DiscoList items;
};
JT_DiscoItems::JT_DiscoItems(Task *parent)
: Task(parent)
{
d = new Private;
}
JT_DiscoItems::~JT_DiscoItems()
{
delete d;
}
void JT_DiscoItems::get(const DiscoItem &item)
{
get(item.jid(), item.node());
}
void JT_DiscoItems::get (const Jid &j, const QString &node)
{
d->items.clear();
d->jid = j;
d->iq = createIQ(doc(), "get", d->jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "http://jabber.org/protocol/disco#items");
if ( !node.isEmpty() )
query.setAttribute("node", node);
d->iq.appendChild(query);
}
const DiscoList &JT_DiscoItems::items() const
{
return d->items;
}
void JT_DiscoItems::onGo ()
{
send(d->iq);
}
bool JT_DiscoItems::take(const QDomElement &x)
{
if(!iqVerify(x, d->jid, id()))
return false;
if(x.attribute("type") == "result") {
QDomElement q = queryTag(x);
for(QDomNode n = q.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement e = n.toElement();
if( e.isNull() )
continue;
if ( e.tagName() == "item" ) {
DiscoItem item;
item.setJid ( e.attribute("jid") );
item.setName( e.attribute("name") );
item.setNode( e.attribute("node") );
item.setAction( DiscoItem::string2action(e.attribute("action")) );
d->items.append( item );
}
}
setSuccess(true);
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_DiscoPublish
//----------------------------------------------------------------------------
class JT_DiscoPublish::Private
{
public:
Private() { }
QDomElement iq;
Jid jid;
DiscoList list;
};
JT_DiscoPublish::JT_DiscoPublish(Task *parent)
: Task(parent)
{
d = new Private;
}
JT_DiscoPublish::~JT_DiscoPublish()
{
delete d;
}
void JT_DiscoPublish::set(const Jid &j, const DiscoList &list)
{
d->list = list;
d->jid = j;
d->iq = createIQ(doc(), "set", d->jid.full(), id());
QDomElement query = doc()->createElement("query");
query.setAttribute("xmlns", "http://jabber.org/protocol/disco#items");
// FIXME: unsure about this
//if ( !node.isEmpty() )
// query.setAttribute("node", node);
DiscoList::ConstIterator it = list.begin();
for ( ; it != list.end(); ++it) {
QDomElement w = doc()->createElement("item");
w.setAttribute("jid", (*it).jid().full());
if ( !(*it).name().isEmpty() )
w.setAttribute("name", (*it).name());
if ( !(*it).node().isEmpty() )
w.setAttribute("node", (*it).node());
w.setAttribute("action", DiscoItem::action2string((*it).action()));
query.appendChild( w );
}
d->iq.appendChild(query);
}
void JT_DiscoPublish::onGo ()
{
send(d->iq);
}
bool JT_DiscoPublish::take(const QDomElement &x)
{
if(!iqVerify(x, d->jid, id()))
return false;
if(x.attribute("type") == "result") {
setSuccess(true);
}
else {
setError(x);
}
return true;
}
// ---------------------------------------------------------
// JT_BoBServer
// ---------------------------------------------------------
JT_BoBServer::JT_BoBServer(Task *parent)
: Task(parent)
{
}
bool JT_BoBServer::take(const QDomElement &e)
{
if (e.tagName() != "iq" || e.attribute("type") != "get")
return false;
QDomElement data = e.firstChildElement("data");
if (data.attribute("xmlns") == "urn:xmpp:bob") {
QDomElement iq;
BoBData bd = client()->bobManager()->bobData(data.attribute("cid"));
if (bd.isNull()) {
iq = createIQ(client()->doc(), "error",
e.attribute("from"), e.attribute("id"));
Stanza::Error error(Stanza::Error::Cancel,
Stanza::Error::ItemNotFound);
iq.appendChild(error.toXml(*doc(), client()->stream().baseNS()));
}
else {
iq = createIQ(doc(), "result", e.attribute("from"), e.attribute("id"));
iq.appendChild(bd.toXml(doc()));
}
send(iq);
return true;
}
return false;
}
//----------------------------------------------------------------------------
// JT_BitsOfBinary
//----------------------------------------------------------------------------
class JT_BitsOfBinary::Private
{
public:
Private() { }
QDomElement iq;
Jid jid;
QString cid;
BoBData data;
};
JT_BitsOfBinary::JT_BitsOfBinary(Task *parent)
: Task(parent)
{
d = new Private;
}
JT_BitsOfBinary::~JT_BitsOfBinary()
{
delete d;
}
void JT_BitsOfBinary::get(const Jid &j, const QString &cid)
{
d->jid = j;
d->cid = cid;
d->data = client()->bobManager()->bobData(cid);
if (d->data.isNull()) {
d->iq = createIQ(doc(), "get", d->jid.full(), id());
QDomElement data = doc()->createElement("data");
data.setAttribute("xmlns", "urn:xmpp:bob");
data.setAttribute("cid", cid);
d->iq.appendChild(data);
}
}
void JT_BitsOfBinary::onGo()
{
if (d->data.isNull()) {
send(d->iq);
}
else {
setSuccess();
}
}
bool JT_BitsOfBinary::take(const QDomElement &x)
{
if (!iqVerify(x, d->jid, id())) {
return false;
}
if (x.attribute("type") == "result") {
QDomElement data = x.firstChildElement("data");
if (!data.isNull() && data.attribute("cid") == d->cid) { // check xmlns?
d->data.fromXml(data);
client()->bobManager()->append(d->data);
}
setSuccess();
}
else {
setError(x);
}
return true;
}
BoBData &JT_BitsOfBinary::data()
{
return d->data;
}
//----------------------------------------------------------------------------
// JT_PongServer
//----------------------------------------------------------------------------
/**
* \class JT_PongServer
* \brief Answers XMPP Pings
*/
JT_PongServer::JT_PongServer(Task *parent)
:Task(parent)
{
}
bool JT_PongServer::take(const QDomElement &e)
{
if (e.tagName() != "iq" || e.attribute("type") != "get")
return false;
QDomElement ping = e.firstChildElement("ping");
if (!e.isNull() && ping.attribute("xmlns") == "urn:xmpp:ping") {
QDomElement iq = createIQ(doc(), "result", e.attribute("from"), e.attribute("id"));
send(iq);
return true;
}
return false;
}
//---------------------------------------------------------------------------
// JT_CaptchaChallenger
//---------------------------------------------------------------------------
class JT_CaptchaChallenger::Private
{
public:
Jid j;
CaptchaChallenge challenge;
};
JT_CaptchaChallenger::JT_CaptchaChallenger(Task *parent) :
Task(parent),
d(new Private)
{
}
JT_CaptchaChallenger::~JT_CaptchaChallenger()
{
delete d;
}
void JT_CaptchaChallenger::set(const Jid &j, const CaptchaChallenge &c)
{
d->j = j;
d->challenge = c;
}
void JT_CaptchaChallenger::onGo()
{
setTimeout(CaptchaValidTimeout);
Message m;
m.setId(id());
m.setBody(d->challenge.explanation());
m.setUrlList(d->challenge.urls());
XData form = d->challenge.form();
XData::FieldList fl = form.fields();
XData::FieldList::Iterator it;
for (it = fl.begin(); it < fl.end(); ++it) {
if (it->var() == "challenge" && it->type() == XData::Field::Field_Hidden) {
it->setValue(QStringList() << id());
}
}
if (it == fl.end()) {
XData::Field f;
f.setType(XData::Field::Field_Hidden);
f.setVar("challenge");
f.setValue(QStringList() << id());
fl.append(f);
}
form.setFields(fl);
m.setForm(form);
m.setTo(d->j);
client()->sendMessage(m);
}
bool JT_CaptchaChallenger::take(const QDomElement &x)
{
if(x.tagName() == "message" && x.attribute("id") == id() &&
Jid(x.attribute("from")) == d->j && !x.firstChildElement("error").isNull())
{
setError(x);
return true;
}
XDomNodeList nl;
XData xd;
QString rid = x.attribute("id");
if (rid.isEmpty() || x.tagName() != "iq" ||
Jid(x.attribute("from")) != d->j || x.attribute("type") != "set" ||
(nl = childElementsByTagNameNS(x, "urn:xmpp:captcha", "captcha")).isEmpty() ||
(nl = childElementsByTagNameNS(nl.item(0).toElement(), "jabber:x:data", "x")).isEmpty() ||
(xd.fromXml(nl.item(0).toElement()), xd.getField("challenge").value().value(0) != id()))
{
return false;
}
CaptchaChallenge::Result r = d->challenge.validateResponse(xd);
QDomElement iq;
if (r == CaptchaChallenge::Passed) {
iq = createIQ(doc(), "result", d->j.full(), rid);
} else {
Stanza::Error::ErrorCond ec;
if (r == CaptchaChallenge::Unavailable) {
ec = Stanza::Error::ServiceUnavailable;
} else {
ec = Stanza::Error::NotAcceptable;
}
iq = createIQ(doc(), "error", d->j.full(), rid);
Stanza::Error error(Stanza::Error::Cancel, ec);
iq.appendChild(error.toXml(*doc(), client()->stream().baseNS()));
}
send(iq);
setSuccess();
return true;
}
//---------------------------------------------------------------------------
// JT_CaptchaSender
//---------------------------------------------------------------------------
JT_CaptchaSender::JT_CaptchaSender(Task *parent) :
Task(parent)
{}
void JT_CaptchaSender::set(const Jid &j, const XData &xd)
{
to = j;
iq = createIQ(doc(), "set", to.full(), id());
iq.appendChild(doc()->createElementNS("urn:xmpp:captcha", "captcha"))
.appendChild(xd.toXml(doc(), true));
}
void JT_CaptchaSender::onGo()
{
send(iq);
}
bool JT_CaptchaSender::take(const QDomElement &x)
{
if (!iqVerify(x, to, id())) {
return false;
}
if (x.attribute("type") == "result") {
setSuccess();
}
else {
setError(x);
}
return true;
}
//----------------------------------------------------------------------------
// JT_MessageCarbons
//----------------------------------------------------------------------------
JT_MessageCarbons::JT_MessageCarbons(Task *parent)
: Task(parent)
{
}
void JT_MessageCarbons::enable()
{
_iq = createIQ(doc(), "set", "", id());
QDomElement enable = doc()->createElement("enable");
enable.setAttribute("xmlns", "urn:xmpp:carbons:2");
_iq.appendChild(enable);
}
void JT_MessageCarbons::disable()
{
_iq = createIQ(doc(), "set", "", id());
QDomElement disable = doc()->createElement("disable");
disable.setAttribute("xmlns", "urn:xmpp:carbons:2");
_iq.appendChild(disable);
}
void JT_MessageCarbons::onGo()
{
send(_iq);
setSuccess();
}
bool JT_MessageCarbons::take(const QDomElement &e)
{
if (e.tagName() != "iq" || e.attribute("type") != "result")
return false;
bool res = iqVerify(e, Jid(), id());
return res;
}
| ./CrossVul/dataset_final_sorted/CWE-346/cpp/bad_3128_0 |
crossvul-cpp_data_bad_3127_0 | /*
* message.c
*
* Copyright (C) 2012 - 2016 James Booth <boothj5@gmail.com>
*
* This file is part of Profanity.
*
* Profanity is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Profanity 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 Profanity. If not, see <https://www.gnu.org/licenses/>.
*
* In addition, as a special exception, the copyright holders give permission to
* link the code of portions of this program with the OpenSSL library under
* certain conditions as described in each individual source file, and
* distribute linked combinations including the two.
*
* You must obey the GNU General Public License in all respects for all of the
* code used other than OpenSSL. If you modify file(s) with this exception, you
* may extend this exception to your version of the file(s), but you are not
* obligated to do so. If you do not wish to do so, delete this exception
* statement from your version. If you delete this exception statement from all
* source files in the program, then also delete it here.
*
*/
#include "config.h"
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_LIBMESODE
#include <mesode.h>
#endif
#ifdef HAVE_LIBSTROPHE
#include <strophe.h>
#endif
#include "profanity.h"
#include "log.h"
#include "config/preferences.h"
#include "event/server_events.h"
#include "pgp/gpg.h"
#include "plugins/plugins.h"
#include "ui/ui.h"
#include "xmpp/chat_session.h"
#include "xmpp/muc.h"
#include "xmpp/session.h"
#include "xmpp/message.h"
#include "xmpp/roster.h"
#include "xmpp/roster_list.h"
#include "xmpp/stanza.h"
#include "xmpp/connection.h"
#include "xmpp/xmpp.h"
static int _message_handler(xmpp_conn_t *const conn, xmpp_stanza_t *const stanza, void *const userdata);
static void _handle_error(xmpp_stanza_t *const stanza);
static void _handle_groupchat(xmpp_stanza_t *const stanza);
static void _handel_muc_user(xmpp_stanza_t *const stanza);
static void _handle_conference(xmpp_stanza_t *const stanza);
static void _handle_captcha(xmpp_stanza_t *const stanza);
static void _handle_receipt_received(xmpp_stanza_t *const stanza);
static void _handle_chat(xmpp_stanza_t *const stanza);
static void _send_message_stanza(xmpp_stanza_t *const stanza);
static int
_message_handler(xmpp_conn_t *const conn, xmpp_stanza_t *const stanza, void *const userdata)
{
log_debug("Message stanza handler fired");
char *text;
size_t text_size;
xmpp_stanza_to_text(stanza, &text, &text_size);
gboolean cont = plugins_on_message_stanza_receive(text);
xmpp_free(connection_get_ctx(), text);
if (!cont) {
return 1;
}
const char *type = xmpp_stanza_get_type(stanza);
if (g_strcmp0(type, STANZA_TYPE_ERROR) == 0) {
_handle_error(stanza);
}
if (g_strcmp0(type, STANZA_TYPE_GROUPCHAT) == 0) {
_handle_groupchat(stanza);
}
xmpp_stanza_t *mucuser = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_MUC_USER);
if (mucuser) {
_handel_muc_user(stanza);
}
xmpp_stanza_t *conference = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CONFERENCE);
if (conference) {
_handle_conference(stanza);
}
xmpp_stanza_t *captcha = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CAPTCHA);
if (captcha) {
_handle_captcha(stanza);
}
xmpp_stanza_t *receipts = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_RECEIPTS);
if (receipts) {
_handle_receipt_received(stanza);
}
_handle_chat(stanza);
return 1;
}
void
message_handlers_init(void)
{
xmpp_conn_t * const conn = connection_get_conn();
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_handler_add(conn, _message_handler, NULL, STANZA_NAME_MESSAGE, NULL, ctx);
}
char*
message_send_chat(const char *const barejid, const char *const msg, const char *const oob_url,
gboolean request_receipt)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
char *state = chat_session_get_state(barejid);
char *jid = chat_session_get_jid(barejid);
char *id = create_unique_id("msg");
xmpp_stanza_t *message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, jid, id);
xmpp_message_set_body(message, msg);
free(jid);
if (state) {
stanza_attach_state(ctx, message, state);
}
if (oob_url) {
stanza_attach_x_oob_url(ctx, message, oob_url);
}
if (request_receipt) {
stanza_attach_receipt_request(ctx, message);
}
_send_message_stanza(message);
xmpp_stanza_release(message);
return id;
}
char*
message_send_chat_pgp(const char *const barejid, const char *const msg, gboolean request_receipt)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
char *state = chat_session_get_state(barejid);
char *jid = chat_session_get_jid(barejid);
char *id = create_unique_id("msg");
xmpp_stanza_t *message = NULL;
#ifdef HAVE_LIBGPGME
char *account_name = session_get_account_name();
ProfAccount *account = accounts_get_account(account_name);
if (account->pgp_keyid) {
Jid *jidp = jid_create(jid);
char *encrypted = p_gpg_encrypt(jidp->barejid, msg, account->pgp_keyid);
if (encrypted) {
message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, jid, id);
xmpp_message_set_body(message, "This message is encrypted.");
xmpp_stanza_t *x = xmpp_stanza_new(ctx);
xmpp_stanza_set_name(x, STANZA_NAME_X);
xmpp_stanza_set_ns(x, STANZA_NS_ENCRYPTED);
xmpp_stanza_t *enc_st = xmpp_stanza_new(ctx);
xmpp_stanza_set_text(enc_st, encrypted);
xmpp_stanza_add_child(x, enc_st);
xmpp_stanza_release(enc_st);
xmpp_stanza_add_child(message, x);
xmpp_stanza_release(x);
free(encrypted);
} else {
message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, jid, id);
xmpp_message_set_body(message, msg);
}
jid_destroy(jidp);
} else {
message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, jid, id);
xmpp_message_set_body(message, msg);
}
account_free(account);
#else
message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, jid, id);
xmpp_message_set_body(message, msg);
#endif
free(jid);
if (state) {
stanza_attach_state(ctx, message, state);
}
if (request_receipt) {
stanza_attach_receipt_request(ctx, message);
}
_send_message_stanza(message);
xmpp_stanza_release(message);
return id;
}
char*
message_send_chat_otr(const char *const barejid, const char *const msg, gboolean request_receipt)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
char *state = chat_session_get_state(barejid);
char *jid = chat_session_get_jid(barejid);
char *id = create_unique_id("msg");
xmpp_stanza_t *message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, barejid, id);
xmpp_message_set_body(message, msg);
free(jid);
if (state) {
stanza_attach_state(ctx, message, state);
}
stanza_attach_carbons_private(ctx, message);
stanza_attach_hints_no_copy(ctx, message);
stanza_attach_hints_no_store(ctx, message);
if (request_receipt) {
stanza_attach_receipt_request(ctx, message);
}
_send_message_stanza(message);
xmpp_stanza_release(message);
return id;
}
void
message_send_private(const char *const fulljid, const char *const msg, const char *const oob_url)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
char *id = create_unique_id("prv");
xmpp_stanza_t *message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, fulljid, id);
xmpp_message_set_body(message, msg);
free(id);
if (oob_url) {
stanza_attach_x_oob_url(ctx, message, oob_url);
}
_send_message_stanza(message);
xmpp_stanza_release(message);
}
void
message_send_groupchat(const char *const roomjid, const char *const msg, const char *const oob_url)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
char *id = create_unique_id("muc");
xmpp_stanza_t *message = xmpp_message_new(ctx, STANZA_TYPE_GROUPCHAT, roomjid, id);
xmpp_message_set_body(message, msg);
free(id);
if (oob_url) {
stanza_attach_x_oob_url(ctx, message, oob_url);
}
_send_message_stanza(message);
xmpp_stanza_release(message);
}
void
message_send_groupchat_subject(const char *const roomjid, const char *const subject)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_stanza_t *message = stanza_create_room_subject_message(ctx, roomjid, subject);
_send_message_stanza(message);
xmpp_stanza_release(message);
}
void
message_send_invite(const char *const roomjid, const char *const contact,
const char *const reason)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_stanza_t *stanza;
muc_member_type_t member_type = muc_member_type(roomjid);
if (member_type == MUC_MEMBER_TYPE_PUBLIC) {
log_debug("Sending direct invite to %s, for %s", contact, roomjid);
char *password = muc_password(roomjid);
stanza = stanza_create_invite(ctx, roomjid, contact, reason, password);
} else {
log_debug("Sending mediated invite to %s, for %s", contact, roomjid);
stanza = stanza_create_mediated_invite(ctx, roomjid, contact, reason);
}
_send_message_stanza(stanza);
xmpp_stanza_release(stanza);
}
void
message_send_composing(const char *const jid)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_stanza_t *stanza = stanza_create_chat_state(ctx, jid, STANZA_NAME_COMPOSING);
_send_message_stanza(stanza);
xmpp_stanza_release(stanza);
}
void
message_send_paused(const char *const jid)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_stanza_t *stanza = stanza_create_chat_state(ctx, jid, STANZA_NAME_PAUSED);
_send_message_stanza(stanza);
xmpp_stanza_release(stanza);
}
void
message_send_inactive(const char *const jid)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_stanza_t *stanza = stanza_create_chat_state(ctx, jid, STANZA_NAME_INACTIVE);
_send_message_stanza(stanza);
xmpp_stanza_release(stanza);
}
void
message_send_gone(const char *const jid)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_stanza_t *stanza = stanza_create_chat_state(ctx, jid, STANZA_NAME_GONE);
_send_message_stanza(stanza);
xmpp_stanza_release(stanza);
}
static void
_handle_error(xmpp_stanza_t *const stanza)
{
const char *id = xmpp_stanza_get_id(stanza);
const char *jid = xmpp_stanza_get_from(stanza);
xmpp_stanza_t *error_stanza = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_ERROR);
const char *type = NULL;
if (error_stanza) {
type = xmpp_stanza_get_type(error_stanza);
}
// stanza_get_error never returns NULL
char *err_msg = stanza_get_error_message(stanza);
GString *log_msg = g_string_new("message stanza error received");
if (id) {
g_string_append(log_msg, " id=");
g_string_append(log_msg, id);
}
if (jid) {
g_string_append(log_msg, " from=");
g_string_append(log_msg, jid);
}
if (type) {
g_string_append(log_msg, " type=");
g_string_append(log_msg, type);
}
g_string_append(log_msg, " error=");
g_string_append(log_msg, err_msg);
log_info(log_msg->str);
g_string_free(log_msg, TRUE);
if (!jid) {
ui_handle_error(err_msg);
} else if (type && (strcmp(type, "cancel") == 0)) {
log_info("Recipient %s not found: %s", jid, err_msg);
Jid *jidp = jid_create(jid);
chat_session_remove(jidp->barejid);
jid_destroy(jidp);
} else {
ui_handle_recipient_error(jid, err_msg);
}
free(err_msg);
}
static void
_handel_muc_user(xmpp_stanza_t *const stanza)
{
xmpp_ctx_t *ctx = connection_get_ctx();
xmpp_stanza_t *xns_muc_user = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_MUC_USER);
const char *room = xmpp_stanza_get_from(stanza);
if (!room) {
log_warning("Message received with no from attribute, ignoring");
return;
}
// XEP-0045
xmpp_stanza_t *invite = xmpp_stanza_get_child_by_name(xns_muc_user, STANZA_NAME_INVITE);
if (!invite) {
return;
}
const char *invitor_jid = xmpp_stanza_get_from(invite);
if (!invitor_jid) {
log_warning("Chat room invite received with no from attribute");
return;
}
Jid *jidp = jid_create(invitor_jid);
if (!jidp) {
return;
}
char *invitor = jidp->barejid;
char *reason = NULL;
xmpp_stanza_t *reason_st = xmpp_stanza_get_child_by_name(invite, STANZA_NAME_REASON);
if (reason_st) {
reason = xmpp_stanza_get_text(reason_st);
}
char *password = NULL;
xmpp_stanza_t *password_st = xmpp_stanza_get_child_by_name(xns_muc_user, STANZA_NAME_PASSWORD);
if (password_st) {
password = xmpp_stanza_get_text(password_st);
}
sv_ev_room_invite(INVITE_MEDIATED, invitor, room, reason, password);
jid_destroy(jidp);
if (reason) {
xmpp_free(ctx, reason);
}
if (password) {
xmpp_free(ctx, password);
}
}
static void
_handle_conference(xmpp_stanza_t *const stanza)
{
xmpp_stanza_t *xns_conference = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CONFERENCE);
const char *from = xmpp_stanza_get_from(stanza);
if (!from) {
log_warning("Message received with no from attribute, ignoring");
return;
}
Jid *jidp = jid_create(from);
if (!jidp) {
return;
}
// XEP-0249
const char *room = xmpp_stanza_get_attribute(xns_conference, STANZA_ATTR_JID);
if (!room) {
jid_destroy(jidp);
return;
}
const char *reason = xmpp_stanza_get_attribute(xns_conference, STANZA_ATTR_REASON);
const char *password = xmpp_stanza_get_attribute(xns_conference, STANZA_ATTR_PASSWORD);
sv_ev_room_invite(INVITE_DIRECT, jidp->barejid, room, reason, password);
jid_destroy(jidp);
}
static void
_handle_captcha(xmpp_stanza_t *const stanza)
{
xmpp_ctx_t *ctx = connection_get_ctx();
const char *from = xmpp_stanza_get_from(stanza);
if (!from) {
log_warning("Message received with no from attribute, ignoring");
return;
}
// XEP-0158
char *message = xmpp_message_get_body(stanza);
if (!message) {
return;
}
sv_ev_room_broadcast(from, message);
xmpp_free(ctx, message);
}
static void
_handle_groupchat(xmpp_stanza_t *const stanza)
{
xmpp_ctx_t *ctx = connection_get_ctx();
char *message = NULL;
const char *room_jid = xmpp_stanza_get_from(stanza);
Jid *jid = jid_create(room_jid);
// handle room subject
xmpp_stanza_t *subject = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_SUBJECT);
if (subject) {
message = xmpp_stanza_get_text(subject);
sv_ev_room_subject(jid->barejid, jid->resourcepart, message);
xmpp_free(ctx, message);
jid_destroy(jid);
return;
}
// handle room broadcasts
if (!jid->resourcepart) {
message = xmpp_message_get_body(stanza);
if (!message) {
jid_destroy(jid);
return;
}
sv_ev_room_broadcast(room_jid, message);
xmpp_free(ctx, message);
jid_destroy(jid);
return;
}
if (!jid_is_valid_room_form(jid)) {
log_error("Invalid room JID: %s", jid->str);
jid_destroy(jid);
return;
}
// room not active in profanity
if (!muc_active(jid->barejid)) {
log_error("Message received for inactive chat room: %s", jid->str);
jid_destroy(jid);
return;
}
message = xmpp_message_get_body(stanza);
if (!message) {
jid_destroy(jid);
return;
}
// determine if the notifications happened whilst offline
GDateTime *timestamp = stanza_get_delay(stanza);
if (timestamp) {
sv_ev_room_history(jid->barejid, jid->resourcepart, timestamp, message);
g_date_time_unref(timestamp);
} else {
sv_ev_room_message(jid->barejid, jid->resourcepart, message);
}
xmpp_free(ctx, message);
jid_destroy(jid);
}
void
_message_send_receipt(const char *const fulljid, const char *const message_id)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
char *id = create_unique_id("receipt");
xmpp_stanza_t *message = xmpp_message_new(ctx, NULL, fulljid, id);
free(id);
xmpp_stanza_t *receipt = xmpp_stanza_new(ctx);
xmpp_stanza_set_name(receipt, "received");
xmpp_stanza_set_ns(receipt, STANZA_NS_RECEIPTS);
xmpp_stanza_set_id(receipt, message_id);
xmpp_stanza_add_child(message, receipt);
xmpp_stanza_release(receipt);
_send_message_stanza(message);
xmpp_stanza_release(message);
}
static void
_handle_receipt_received(xmpp_stanza_t *const stanza)
{
xmpp_stanza_t *receipt = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_RECEIPTS);
const char *name = xmpp_stanza_get_name(receipt);
if (g_strcmp0(name, "received") != 0) {
return;
}
const char *id = xmpp_stanza_get_id(receipt);
if (!id) {
return;
}
const char *fulljid = xmpp_stanza_get_from(stanza);
if (!fulljid) {
return;
}
Jid *jidp = jid_create(fulljid);
sv_ev_message_receipt(jidp->barejid, id);
jid_destroy(jidp);
}
void
_receipt_request_handler(xmpp_stanza_t *const stanza)
{
if (!prefs_get_boolean(PREF_RECEIPTS_SEND)) {
return;
}
const char *id = xmpp_stanza_get_id(stanza);
if (!id) {
return;
}
xmpp_stanza_t *receipts = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_RECEIPTS);
if (!receipts) {
return;
}
const char *receipts_name = xmpp_stanza_get_name(receipts);
if (g_strcmp0(receipts_name, "request") != 0) {
return;
}
const gchar *from = xmpp_stanza_get_from(stanza);
Jid *jid = jid_create(from);
_message_send_receipt(jid->fulljid, id);
jid_destroy(jid);
}
void
_private_chat_handler(xmpp_stanza_t *const stanza, const char *const fulljid)
{
char *message = xmpp_message_get_body(stanza);
if (!message) {
return;
}
GDateTime *timestamp = stanza_get_delay(stanza);
if (timestamp) {
sv_ev_delayed_private_message(fulljid, message, timestamp);
g_date_time_unref(timestamp);
} else {
sv_ev_incoming_private_message(fulljid, message);
}
xmpp_ctx_t *ctx = connection_get_ctx();
xmpp_free(ctx, message);
}
static gboolean
_handle_carbons(xmpp_stanza_t *const stanza)
{
xmpp_stanza_t *carbons = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CARBONS);
if (!carbons) {
return FALSE;
}
const char *name = xmpp_stanza_get_name(carbons);
if (!name) {
log_error("Unable to retrieve stanza name for Carbon");
return TRUE;
}
if (g_strcmp0(name, "private") == 0) {
log_info("Carbon received with private element.");
return FALSE;
}
if ((g_strcmp0(name, "received") != 0) && (g_strcmp0(name, "sent") != 0)) {
log_warning("Carbon received with unrecognised stanza name: %s", name);
return TRUE;
}
xmpp_stanza_t *forwarded = xmpp_stanza_get_child_by_ns(carbons, STANZA_NS_FORWARD);
if (!forwarded) {
log_warning("Carbon received with no forwarded element");
return TRUE;
}
xmpp_stanza_t *message = xmpp_stanza_get_child_by_name(forwarded, STANZA_NAME_MESSAGE);
if (!message) {
log_warning("Carbon received with no message element");
return TRUE;
}
char *message_txt = xmpp_message_get_body(message);
if (!message_txt) {
log_warning("Carbon received with no message.");
return TRUE;
}
const gchar *to = xmpp_stanza_get_to(message);
const gchar *from = xmpp_stanza_get_from(message);
// happens when receive a carbon of a self sent message
if (!to) to = from;
Jid *jid_from = jid_create(from);
Jid *jid_to = jid_create(to);
Jid *my_jid = jid_create(connection_get_fulljid());
// check for pgp encrypted message
char *enc_message = NULL;
xmpp_stanza_t *x = xmpp_stanza_get_child_by_ns(message, STANZA_NS_ENCRYPTED);
if (x) {
enc_message = xmpp_stanza_get_text(x);
}
// if we are the recipient, treat as standard incoming message
if (g_strcmp0(my_jid->barejid, jid_to->barejid) == 0) {
sv_ev_incoming_carbon(jid_from->barejid, jid_from->resourcepart, message_txt, enc_message);
// else treat as a sent message
} else {
sv_ev_outgoing_carbon(jid_to->barejid, message_txt, enc_message);
}
xmpp_ctx_t *ctx = connection_get_ctx();
xmpp_free(ctx, message_txt);
xmpp_free(ctx, enc_message);
jid_destroy(jid_from);
jid_destroy(jid_to);
jid_destroy(my_jid);
return TRUE;
}
static void
_handle_chat(xmpp_stanza_t *const stanza)
{
// ignore if type not chat or absent
const char *type = xmpp_stanza_get_type(stanza);
if (!(g_strcmp0(type, "chat") == 0 || type == NULL)) {
return;
}
// check if carbon message
gboolean res = _handle_carbons(stanza);
if (res) {
return;
}
// ignore handled namespaces
xmpp_stanza_t *conf = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CONFERENCE);
xmpp_stanza_t *captcha = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CAPTCHA);
if (conf || captcha) {
return;
}
// some clients send the mucuser namespace with private messages
// if the namespace exists, and the stanza contains a body element, assume its a private message
// otherwise exit the handler
xmpp_stanza_t *mucuser = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_MUC_USER);
xmpp_stanza_t *body = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_BODY);
if (mucuser && body == NULL) {
return;
}
const gchar *from = xmpp_stanza_get_from(stanza);
Jid *jid = jid_create(from);
// private message from chat room use full jid (room/nick)
if (muc_active(jid->barejid)) {
_private_chat_handler(stanza, jid->fulljid);
jid_destroy(jid);
return;
}
// standard chat message, use jid without resource
xmpp_ctx_t *ctx = connection_get_ctx();
GDateTime *timestamp = stanza_get_delay(stanza);
if (body) {
char *message = xmpp_stanza_get_text(body);
if (message) {
char *enc_message = NULL;
xmpp_stanza_t *x = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_ENCRYPTED);
if (x) {
enc_message = xmpp_stanza_get_text(x);
}
sv_ev_incoming_message(jid->barejid, jid->resourcepart, message, enc_message, timestamp);
xmpp_free(ctx, enc_message);
_receipt_request_handler(stanza);
xmpp_free(ctx, message);
}
}
// handle chat sessions and states
if (!timestamp && jid->resourcepart) {
gboolean gone = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_GONE) != NULL;
gboolean typing = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_COMPOSING) != NULL;
gboolean paused = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_PAUSED) != NULL;
gboolean inactive = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_INACTIVE) != NULL;
if (gone) {
sv_ev_gone(jid->barejid, jid->resourcepart);
} else if (typing) {
sv_ev_typing(jid->barejid, jid->resourcepart);
} else if (paused) {
sv_ev_paused(jid->barejid, jid->resourcepart);
} else if (inactive) {
sv_ev_inactive(jid->barejid, jid->resourcepart);
} else if (stanza_contains_chat_state(stanza)) {
sv_ev_activity(jid->barejid, jid->resourcepart, TRUE);
} else {
sv_ev_activity(jid->barejid, jid->resourcepart, FALSE);
}
}
if (timestamp) g_date_time_unref(timestamp);
jid_destroy(jid);
}
static void
_send_message_stanza(xmpp_stanza_t *const stanza)
{
char *text;
size_t text_size;
xmpp_stanza_to_text(stanza, &text, &text_size);
xmpp_conn_t *conn = connection_get_conn();
char *plugin_text = plugins_on_message_stanza_send(text);
if (plugin_text) {
xmpp_send_raw_string(conn, "%s", plugin_text);
free(plugin_text);
} else {
xmpp_send_raw_string(conn, "%s", text);
}
xmpp_free(connection_get_ctx(), text);
}
| ./CrossVul/dataset_final_sorted/CWE-346/c/bad_3127_0 |
crossvul-cpp_data_good_3127_0 | /*
* message.c
*
* Copyright (C) 2012 - 2016 James Booth <boothj5@gmail.com>
*
* This file is part of Profanity.
*
* Profanity is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Profanity 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 Profanity. If not, see <https://www.gnu.org/licenses/>.
*
* In addition, as a special exception, the copyright holders give permission to
* link the code of portions of this program with the OpenSSL library under
* certain conditions as described in each individual source file, and
* distribute linked combinations including the two.
*
* You must obey the GNU General Public License in all respects for all of the
* code used other than OpenSSL. If you modify file(s) with this exception, you
* may extend this exception to your version of the file(s), but you are not
* obligated to do so. If you do not wish to do so, delete this exception
* statement from your version. If you delete this exception statement from all
* source files in the program, then also delete it here.
*
*/
#include "config.h"
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_LIBMESODE
#include <mesode.h>
#endif
#ifdef HAVE_LIBSTROPHE
#include <strophe.h>
#endif
#include "profanity.h"
#include "log.h"
#include "config/preferences.h"
#include "event/server_events.h"
#include "pgp/gpg.h"
#include "plugins/plugins.h"
#include "ui/ui.h"
#include "xmpp/chat_session.h"
#include "xmpp/muc.h"
#include "xmpp/session.h"
#include "xmpp/message.h"
#include "xmpp/roster.h"
#include "xmpp/roster_list.h"
#include "xmpp/stanza.h"
#include "xmpp/connection.h"
#include "xmpp/xmpp.h"
static int _message_handler(xmpp_conn_t *const conn, xmpp_stanza_t *const stanza, void *const userdata);
static void _handle_error(xmpp_stanza_t *const stanza);
static void _handle_groupchat(xmpp_stanza_t *const stanza);
static void _handel_muc_user(xmpp_stanza_t *const stanza);
static void _handle_conference(xmpp_stanza_t *const stanza);
static void _handle_captcha(xmpp_stanza_t *const stanza);
static void _handle_receipt_received(xmpp_stanza_t *const stanza);
static void _handle_chat(xmpp_stanza_t *const stanza);
static void _send_message_stanza(xmpp_stanza_t *const stanza);
static int
_message_handler(xmpp_conn_t *const conn, xmpp_stanza_t *const stanza, void *const userdata)
{
log_debug("Message stanza handler fired");
char *text;
size_t text_size;
xmpp_stanza_to_text(stanza, &text, &text_size);
gboolean cont = plugins_on_message_stanza_receive(text);
xmpp_free(connection_get_ctx(), text);
if (!cont) {
return 1;
}
const char *type = xmpp_stanza_get_type(stanza);
if (g_strcmp0(type, STANZA_TYPE_ERROR) == 0) {
_handle_error(stanza);
}
if (g_strcmp0(type, STANZA_TYPE_GROUPCHAT) == 0) {
_handle_groupchat(stanza);
}
xmpp_stanza_t *mucuser = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_MUC_USER);
if (mucuser) {
_handel_muc_user(stanza);
}
xmpp_stanza_t *conference = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CONFERENCE);
if (conference) {
_handle_conference(stanza);
}
xmpp_stanza_t *captcha = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CAPTCHA);
if (captcha) {
_handle_captcha(stanza);
}
xmpp_stanza_t *receipts = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_RECEIPTS);
if (receipts) {
_handle_receipt_received(stanza);
}
_handle_chat(stanza);
return 1;
}
void
message_handlers_init(void)
{
xmpp_conn_t * const conn = connection_get_conn();
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_handler_add(conn, _message_handler, NULL, STANZA_NAME_MESSAGE, NULL, ctx);
}
char*
message_send_chat(const char *const barejid, const char *const msg, const char *const oob_url,
gboolean request_receipt)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
char *state = chat_session_get_state(barejid);
char *jid = chat_session_get_jid(barejid);
char *id = create_unique_id("msg");
xmpp_stanza_t *message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, jid, id);
xmpp_message_set_body(message, msg);
free(jid);
if (state) {
stanza_attach_state(ctx, message, state);
}
if (oob_url) {
stanza_attach_x_oob_url(ctx, message, oob_url);
}
if (request_receipt) {
stanza_attach_receipt_request(ctx, message);
}
_send_message_stanza(message);
xmpp_stanza_release(message);
return id;
}
char*
message_send_chat_pgp(const char *const barejid, const char *const msg, gboolean request_receipt)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
char *state = chat_session_get_state(barejid);
char *jid = chat_session_get_jid(barejid);
char *id = create_unique_id("msg");
xmpp_stanza_t *message = NULL;
#ifdef HAVE_LIBGPGME
char *account_name = session_get_account_name();
ProfAccount *account = accounts_get_account(account_name);
if (account->pgp_keyid) {
Jid *jidp = jid_create(jid);
char *encrypted = p_gpg_encrypt(jidp->barejid, msg, account->pgp_keyid);
if (encrypted) {
message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, jid, id);
xmpp_message_set_body(message, "This message is encrypted.");
xmpp_stanza_t *x = xmpp_stanza_new(ctx);
xmpp_stanza_set_name(x, STANZA_NAME_X);
xmpp_stanza_set_ns(x, STANZA_NS_ENCRYPTED);
xmpp_stanza_t *enc_st = xmpp_stanza_new(ctx);
xmpp_stanza_set_text(enc_st, encrypted);
xmpp_stanza_add_child(x, enc_st);
xmpp_stanza_release(enc_st);
xmpp_stanza_add_child(message, x);
xmpp_stanza_release(x);
free(encrypted);
} else {
message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, jid, id);
xmpp_message_set_body(message, msg);
}
jid_destroy(jidp);
} else {
message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, jid, id);
xmpp_message_set_body(message, msg);
}
account_free(account);
#else
message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, jid, id);
xmpp_message_set_body(message, msg);
#endif
free(jid);
if (state) {
stanza_attach_state(ctx, message, state);
}
if (request_receipt) {
stanza_attach_receipt_request(ctx, message);
}
_send_message_stanza(message);
xmpp_stanza_release(message);
return id;
}
char*
message_send_chat_otr(const char *const barejid, const char *const msg, gboolean request_receipt)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
char *state = chat_session_get_state(barejid);
char *jid = chat_session_get_jid(barejid);
char *id = create_unique_id("msg");
xmpp_stanza_t *message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, barejid, id);
xmpp_message_set_body(message, msg);
free(jid);
if (state) {
stanza_attach_state(ctx, message, state);
}
stanza_attach_carbons_private(ctx, message);
stanza_attach_hints_no_copy(ctx, message);
stanza_attach_hints_no_store(ctx, message);
if (request_receipt) {
stanza_attach_receipt_request(ctx, message);
}
_send_message_stanza(message);
xmpp_stanza_release(message);
return id;
}
void
message_send_private(const char *const fulljid, const char *const msg, const char *const oob_url)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
char *id = create_unique_id("prv");
xmpp_stanza_t *message = xmpp_message_new(ctx, STANZA_TYPE_CHAT, fulljid, id);
xmpp_message_set_body(message, msg);
free(id);
if (oob_url) {
stanza_attach_x_oob_url(ctx, message, oob_url);
}
_send_message_stanza(message);
xmpp_stanza_release(message);
}
void
message_send_groupchat(const char *const roomjid, const char *const msg, const char *const oob_url)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
char *id = create_unique_id("muc");
xmpp_stanza_t *message = xmpp_message_new(ctx, STANZA_TYPE_GROUPCHAT, roomjid, id);
xmpp_message_set_body(message, msg);
free(id);
if (oob_url) {
stanza_attach_x_oob_url(ctx, message, oob_url);
}
_send_message_stanza(message);
xmpp_stanza_release(message);
}
void
message_send_groupchat_subject(const char *const roomjid, const char *const subject)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_stanza_t *message = stanza_create_room_subject_message(ctx, roomjid, subject);
_send_message_stanza(message);
xmpp_stanza_release(message);
}
void
message_send_invite(const char *const roomjid, const char *const contact,
const char *const reason)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_stanza_t *stanza;
muc_member_type_t member_type = muc_member_type(roomjid);
if (member_type == MUC_MEMBER_TYPE_PUBLIC) {
log_debug("Sending direct invite to %s, for %s", contact, roomjid);
char *password = muc_password(roomjid);
stanza = stanza_create_invite(ctx, roomjid, contact, reason, password);
} else {
log_debug("Sending mediated invite to %s, for %s", contact, roomjid);
stanza = stanza_create_mediated_invite(ctx, roomjid, contact, reason);
}
_send_message_stanza(stanza);
xmpp_stanza_release(stanza);
}
void
message_send_composing(const char *const jid)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_stanza_t *stanza = stanza_create_chat_state(ctx, jid, STANZA_NAME_COMPOSING);
_send_message_stanza(stanza);
xmpp_stanza_release(stanza);
}
void
message_send_paused(const char *const jid)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_stanza_t *stanza = stanza_create_chat_state(ctx, jid, STANZA_NAME_PAUSED);
_send_message_stanza(stanza);
xmpp_stanza_release(stanza);
}
void
message_send_inactive(const char *const jid)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_stanza_t *stanza = stanza_create_chat_state(ctx, jid, STANZA_NAME_INACTIVE);
_send_message_stanza(stanza);
xmpp_stanza_release(stanza);
}
void
message_send_gone(const char *const jid)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_stanza_t *stanza = stanza_create_chat_state(ctx, jid, STANZA_NAME_GONE);
_send_message_stanza(stanza);
xmpp_stanza_release(stanza);
}
static void
_handle_error(xmpp_stanza_t *const stanza)
{
const char *id = xmpp_stanza_get_id(stanza);
const char *jid = xmpp_stanza_get_from(stanza);
xmpp_stanza_t *error_stanza = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_ERROR);
const char *type = NULL;
if (error_stanza) {
type = xmpp_stanza_get_type(error_stanza);
}
// stanza_get_error never returns NULL
char *err_msg = stanza_get_error_message(stanza);
GString *log_msg = g_string_new("message stanza error received");
if (id) {
g_string_append(log_msg, " id=");
g_string_append(log_msg, id);
}
if (jid) {
g_string_append(log_msg, " from=");
g_string_append(log_msg, jid);
}
if (type) {
g_string_append(log_msg, " type=");
g_string_append(log_msg, type);
}
g_string_append(log_msg, " error=");
g_string_append(log_msg, err_msg);
log_info(log_msg->str);
g_string_free(log_msg, TRUE);
if (!jid) {
ui_handle_error(err_msg);
} else if (type && (strcmp(type, "cancel") == 0)) {
log_info("Recipient %s not found: %s", jid, err_msg);
Jid *jidp = jid_create(jid);
chat_session_remove(jidp->barejid);
jid_destroy(jidp);
} else {
ui_handle_recipient_error(jid, err_msg);
}
free(err_msg);
}
static void
_handel_muc_user(xmpp_stanza_t *const stanza)
{
xmpp_ctx_t *ctx = connection_get_ctx();
xmpp_stanza_t *xns_muc_user = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_MUC_USER);
const char *room = xmpp_stanza_get_from(stanza);
if (!room) {
log_warning("Message received with no from attribute, ignoring");
return;
}
// XEP-0045
xmpp_stanza_t *invite = xmpp_stanza_get_child_by_name(xns_muc_user, STANZA_NAME_INVITE);
if (!invite) {
return;
}
const char *invitor_jid = xmpp_stanza_get_from(invite);
if (!invitor_jid) {
log_warning("Chat room invite received with no from attribute");
return;
}
Jid *jidp = jid_create(invitor_jid);
if (!jidp) {
return;
}
char *invitor = jidp->barejid;
char *reason = NULL;
xmpp_stanza_t *reason_st = xmpp_stanza_get_child_by_name(invite, STANZA_NAME_REASON);
if (reason_st) {
reason = xmpp_stanza_get_text(reason_st);
}
char *password = NULL;
xmpp_stanza_t *password_st = xmpp_stanza_get_child_by_name(xns_muc_user, STANZA_NAME_PASSWORD);
if (password_st) {
password = xmpp_stanza_get_text(password_st);
}
sv_ev_room_invite(INVITE_MEDIATED, invitor, room, reason, password);
jid_destroy(jidp);
if (reason) {
xmpp_free(ctx, reason);
}
if (password) {
xmpp_free(ctx, password);
}
}
static void
_handle_conference(xmpp_stanza_t *const stanza)
{
xmpp_stanza_t *xns_conference = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CONFERENCE);
const char *from = xmpp_stanza_get_from(stanza);
if (!from) {
log_warning("Message received with no from attribute, ignoring");
return;
}
Jid *jidp = jid_create(from);
if (!jidp) {
return;
}
// XEP-0249
const char *room = xmpp_stanza_get_attribute(xns_conference, STANZA_ATTR_JID);
if (!room) {
jid_destroy(jidp);
return;
}
const char *reason = xmpp_stanza_get_attribute(xns_conference, STANZA_ATTR_REASON);
const char *password = xmpp_stanza_get_attribute(xns_conference, STANZA_ATTR_PASSWORD);
sv_ev_room_invite(INVITE_DIRECT, jidp->barejid, room, reason, password);
jid_destroy(jidp);
}
static void
_handle_captcha(xmpp_stanza_t *const stanza)
{
xmpp_ctx_t *ctx = connection_get_ctx();
const char *from = xmpp_stanza_get_from(stanza);
if (!from) {
log_warning("Message received with no from attribute, ignoring");
return;
}
// XEP-0158
char *message = xmpp_message_get_body(stanza);
if (!message) {
return;
}
sv_ev_room_broadcast(from, message);
xmpp_free(ctx, message);
}
static void
_handle_groupchat(xmpp_stanza_t *const stanza)
{
xmpp_ctx_t *ctx = connection_get_ctx();
char *message = NULL;
const char *room_jid = xmpp_stanza_get_from(stanza);
Jid *jid = jid_create(room_jid);
// handle room subject
xmpp_stanza_t *subject = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_SUBJECT);
if (subject) {
message = xmpp_stanza_get_text(subject);
sv_ev_room_subject(jid->barejid, jid->resourcepart, message);
xmpp_free(ctx, message);
jid_destroy(jid);
return;
}
// handle room broadcasts
if (!jid->resourcepart) {
message = xmpp_message_get_body(stanza);
if (!message) {
jid_destroy(jid);
return;
}
sv_ev_room_broadcast(room_jid, message);
xmpp_free(ctx, message);
jid_destroy(jid);
return;
}
if (!jid_is_valid_room_form(jid)) {
log_error("Invalid room JID: %s", jid->str);
jid_destroy(jid);
return;
}
// room not active in profanity
if (!muc_active(jid->barejid)) {
log_error("Message received for inactive chat room: %s", jid->str);
jid_destroy(jid);
return;
}
message = xmpp_message_get_body(stanza);
if (!message) {
jid_destroy(jid);
return;
}
// determine if the notifications happened whilst offline
GDateTime *timestamp = stanza_get_delay(stanza);
if (timestamp) {
sv_ev_room_history(jid->barejid, jid->resourcepart, timestamp, message);
g_date_time_unref(timestamp);
} else {
sv_ev_room_message(jid->barejid, jid->resourcepart, message);
}
xmpp_free(ctx, message);
jid_destroy(jid);
}
void
_message_send_receipt(const char *const fulljid, const char *const message_id)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
char *id = create_unique_id("receipt");
xmpp_stanza_t *message = xmpp_message_new(ctx, NULL, fulljid, id);
free(id);
xmpp_stanza_t *receipt = xmpp_stanza_new(ctx);
xmpp_stanza_set_name(receipt, "received");
xmpp_stanza_set_ns(receipt, STANZA_NS_RECEIPTS);
xmpp_stanza_set_id(receipt, message_id);
xmpp_stanza_add_child(message, receipt);
xmpp_stanza_release(receipt);
_send_message_stanza(message);
xmpp_stanza_release(message);
}
static void
_handle_receipt_received(xmpp_stanza_t *const stanza)
{
xmpp_stanza_t *receipt = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_RECEIPTS);
const char *name = xmpp_stanza_get_name(receipt);
if (g_strcmp0(name, "received") != 0) {
return;
}
const char *id = xmpp_stanza_get_id(receipt);
if (!id) {
return;
}
const char *fulljid = xmpp_stanza_get_from(stanza);
if (!fulljid) {
return;
}
Jid *jidp = jid_create(fulljid);
sv_ev_message_receipt(jidp->barejid, id);
jid_destroy(jidp);
}
void
_receipt_request_handler(xmpp_stanza_t *const stanza)
{
if (!prefs_get_boolean(PREF_RECEIPTS_SEND)) {
return;
}
const char *id = xmpp_stanza_get_id(stanza);
if (!id) {
return;
}
xmpp_stanza_t *receipts = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_RECEIPTS);
if (!receipts) {
return;
}
const char *receipts_name = xmpp_stanza_get_name(receipts);
if (g_strcmp0(receipts_name, "request") != 0) {
return;
}
const gchar *from = xmpp_stanza_get_from(stanza);
Jid *jid = jid_create(from);
_message_send_receipt(jid->fulljid, id);
jid_destroy(jid);
}
void
_private_chat_handler(xmpp_stanza_t *const stanza, const char *const fulljid)
{
char *message = xmpp_message_get_body(stanza);
if (!message) {
return;
}
GDateTime *timestamp = stanza_get_delay(stanza);
if (timestamp) {
sv_ev_delayed_private_message(fulljid, message, timestamp);
g_date_time_unref(timestamp);
} else {
sv_ev_incoming_private_message(fulljid, message);
}
xmpp_ctx_t *ctx = connection_get_ctx();
xmpp_free(ctx, message);
}
static gboolean
_handle_carbons(xmpp_stanza_t *const stanza)
{
xmpp_stanza_t *carbons = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CARBONS);
if (!carbons) {
return FALSE;
}
const char *name = xmpp_stanza_get_name(carbons);
if (!name) {
log_error("Unable to retrieve stanza name for Carbon");
return TRUE;
}
if (g_strcmp0(name, "private") == 0) {
log_info("Carbon received with private element.");
return FALSE;
}
if ((g_strcmp0(name, "received") != 0) && (g_strcmp0(name, "sent") != 0)) {
log_warning("Carbon received with unrecognised stanza name: %s", name);
return TRUE;
}
xmpp_stanza_t *forwarded = xmpp_stanza_get_child_by_ns(carbons, STANZA_NS_FORWARD);
if (!forwarded) {
log_warning("Carbon received with no forwarded element");
return TRUE;
}
xmpp_stanza_t *message = xmpp_stanza_get_child_by_name(forwarded, STANZA_NAME_MESSAGE);
if (!message) {
log_warning("Carbon received with no message element");
return TRUE;
}
char *message_txt = xmpp_message_get_body(message);
if (!message_txt) {
log_warning("Carbon received with no message.");
return TRUE;
}
Jid *my_jid = jid_create(connection_get_fulljid());
const char *const stanza_from = xmpp_stanza_get_from(stanza);
Jid *msg_jid = jid_create(stanza_from);
if (g_strcmp0(my_jid->barejid, msg_jid->barejid) != 0) {
log_warning("Invalid carbon received, from: %s", stanza_from);
return TRUE;
}
const gchar *to = xmpp_stanza_get_to(message);
const gchar *from = xmpp_stanza_get_from(message);
// happens when receive a carbon of a self sent message
if (!to) to = from;
Jid *jid_from = jid_create(from);
Jid *jid_to = jid_create(to);
// check for pgp encrypted message
char *enc_message = NULL;
xmpp_stanza_t *x = xmpp_stanza_get_child_by_ns(message, STANZA_NS_ENCRYPTED);
if (x) {
enc_message = xmpp_stanza_get_text(x);
}
// if we are the recipient, treat as standard incoming message
if (g_strcmp0(my_jid->barejid, jid_to->barejid) == 0) {
sv_ev_incoming_carbon(jid_from->barejid, jid_from->resourcepart, message_txt, enc_message);
// else treat as a sent message
} else {
sv_ev_outgoing_carbon(jid_to->barejid, message_txt, enc_message);
}
xmpp_ctx_t *ctx = connection_get_ctx();
xmpp_free(ctx, message_txt);
xmpp_free(ctx, enc_message);
jid_destroy(jid_from);
jid_destroy(jid_to);
jid_destroy(my_jid);
return TRUE;
}
static void
_handle_chat(xmpp_stanza_t *const stanza)
{
// ignore if type not chat or absent
const char *type = xmpp_stanza_get_type(stanza);
if (!(g_strcmp0(type, "chat") == 0 || type == NULL)) {
return;
}
// check if carbon message
gboolean res = _handle_carbons(stanza);
if (res) {
return;
}
// ignore handled namespaces
xmpp_stanza_t *conf = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CONFERENCE);
xmpp_stanza_t *captcha = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CAPTCHA);
if (conf || captcha) {
return;
}
// some clients send the mucuser namespace with private messages
// if the namespace exists, and the stanza contains a body element, assume its a private message
// otherwise exit the handler
xmpp_stanza_t *mucuser = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_MUC_USER);
xmpp_stanza_t *body = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_BODY);
if (mucuser && body == NULL) {
return;
}
const gchar *from = xmpp_stanza_get_from(stanza);
Jid *jid = jid_create(from);
// private message from chat room use full jid (room/nick)
if (muc_active(jid->barejid)) {
_private_chat_handler(stanza, jid->fulljid);
jid_destroy(jid);
return;
}
// standard chat message, use jid without resource
xmpp_ctx_t *ctx = connection_get_ctx();
GDateTime *timestamp = stanza_get_delay(stanza);
if (body) {
char *message = xmpp_stanza_get_text(body);
if (message) {
char *enc_message = NULL;
xmpp_stanza_t *x = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_ENCRYPTED);
if (x) {
enc_message = xmpp_stanza_get_text(x);
}
sv_ev_incoming_message(jid->barejid, jid->resourcepart, message, enc_message, timestamp);
xmpp_free(ctx, enc_message);
_receipt_request_handler(stanza);
xmpp_free(ctx, message);
}
}
// handle chat sessions and states
if (!timestamp && jid->resourcepart) {
gboolean gone = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_GONE) != NULL;
gboolean typing = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_COMPOSING) != NULL;
gboolean paused = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_PAUSED) != NULL;
gboolean inactive = xmpp_stanza_get_child_by_name(stanza, STANZA_NAME_INACTIVE) != NULL;
if (gone) {
sv_ev_gone(jid->barejid, jid->resourcepart);
} else if (typing) {
sv_ev_typing(jid->barejid, jid->resourcepart);
} else if (paused) {
sv_ev_paused(jid->barejid, jid->resourcepart);
} else if (inactive) {
sv_ev_inactive(jid->barejid, jid->resourcepart);
} else if (stanza_contains_chat_state(stanza)) {
sv_ev_activity(jid->barejid, jid->resourcepart, TRUE);
} else {
sv_ev_activity(jid->barejid, jid->resourcepart, FALSE);
}
}
if (timestamp) g_date_time_unref(timestamp);
jid_destroy(jid);
}
static void
_send_message_stanza(xmpp_stanza_t *const stanza)
{
char *text;
size_t text_size;
xmpp_stanza_to_text(stanza, &text, &text_size);
xmpp_conn_t *conn = connection_get_conn();
char *plugin_text = plugins_on_message_stanza_send(text);
if (plugin_text) {
xmpp_send_raw_string(conn, "%s", plugin_text);
free(plugin_text);
} else {
xmpp_send_raw_string(conn, "%s", text);
}
xmpp_free(connection_get_ctx(), text);
}
| ./CrossVul/dataset_final_sorted/CWE-346/c/good_3127_0 |
crossvul-cpp_data_bad_3234_1 | /*
===========================================================================
Copyright (C) 1999 - 2005, Id Software, Inc.
Copyright (C) 2000 - 2013, Raven Software, Inc.
Copyright (C) 2001 - 2013, Activision, Inc.
Copyright (C) 2005 - 2015, ioquake3 contributors
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
/*****************************************************************************
* name: files.cpp
*
* desc: file code
*
*****************************************************************************/
#include "q_shared.h"
#include "qcommon.h"
#ifndef FINAL_BUILD
#include "../client/client.h"
#endif
#include <minizip/unzip.h>
// for rmdir
#if defined (_MSC_VER)
#include <direct.h>
#else
#include <unistd.h>
#endif
#if defined(_WIN32)
#include <windows.h>
#endif
/*
=============================================================================
QUAKE3 FILESYSTEM
All of Quake's data access is through a hierarchical file system, but the contents of
the file system can be transparently merged from several sources.
A "qpath" is a reference to game file data. MAX_ZPATH is 256 characters, which must include
a terminating zero. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any
references outside the quake directory system.
The "base path" is the path to the directory holding all the game directories and usually
the executable. It defaults to ".", but can be overridden with a "+set fs_basepath c:\quake3"
command line to allow code debugging in a different directory. Basepath cannot
be modified at all after startup. Any files that are created (demos, screenshots,
etc) will be created relative to the base path, so base path should usually be writable.
The "home path" is the path used for all write access. On win32 systems we have "base path"
== "home path", but on *nix systems the base installation is usually readonly, and
"home path" points to ~/.q3a or similar
The user can also install custom mods and content in "home path", so it should be searched
along with "home path" and "cd path" for game content.
The "base game" is the directory under the paths where data comes from by default, and
can be either "baseq3" or "demoq3".
The "current game" may be the same as the base game, or it may be the name of another
directory under the paths that should be searched for files before looking in the base game.
This is the basis for addons.
Clients automatically set the game directory after receiving a gamestate from a server,
so only servers need to worry about +set fs_game.
No other directories outside of the base game and current game will ever be referenced by
filesystem functions.
To save disk space and speed loading, directory trees can be collapsed into zip files.
The files use a ".pk3" extension to prevent users from unzipping them accidentally, but
otherwise the are simply normal uncompressed zip files. A game directory can have multiple
zip files of the form "pak0.pk3", "pak1.pk3", etc. Zip files are searched in decending order
from the highest number to the lowest, and will always take precedence over the filesystem.
This allows a pk3 distributed as a patch to override all existing data.
Because we will have updated executables freely available online, there is no point to
trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
should be exactly the same executables as release versions, but with different data that
automatically restricts where game media can come from to prevent add-ons from working.
File search order: when FS_FOpenFileRead gets called it will go through the fs_searchpaths
structure and stop on the first successful hit. fs_searchpaths is built with successive
calls to FS_AddGameDirectory
Additionaly, we search in several subdirectories:
current game is the current mode
base game is a variable to allow mods based on other mods
(such as baseq3 + missionpack content combination in a mod for instance)
BASEGAME is the hardcoded base game ("baseq3")
e.g. the qpath "sound/newstuff/test.wav" would be searched for in the following places:
home path + current game's zip files
home path + current game's directory
base path + current game's zip files
base path + current game's directory
cd path + current game's zip files
cd path + current game's directory
home path + base game's zip file
home path + base game's directory
base path + base game's zip file
base path + base game's directory
cd path + base game's zip file
cd path + base game's directory
home path + BASEGAME's zip file
home path + BASEGAME's directory
base path + BASEGAME's zip file
base path + BASEGAME's directory
cd path + BASEGAME's zip file
cd path + BASEGAME's directory
server download, to be written to home path + current game's directory
The filesystem can be safely shutdown and reinitialized with different
basedir / cddir / game combinations, but all other subsystems that rely on it
(sound, video) must also be forced to restart.
Because the same files are loaded by both the clip model (CM_) and renderer (TR_)
subsystems, a simple single-file caching scheme is used. The CM_ subsystems will
load the file with a request to cache. Only one file will be kept cached at a time,
so any models that are going to be referenced by both subsystems should alternate
between the CM_ load function and the ref load function.
TODO: A qpath that starts with a leading slash will always refer to the base game, even if another
game is currently active. This allows character models, skins, and sounds to be downloaded
to a common directory no matter which game is active.
How to prevent downloading zip files?
Pass pk3 file names in systeminfo, and download before FS_Restart()?
Aborting a download disconnects the client from the server.
How to mark files as downloadable? Commercial add-ons won't be downloadable.
Non-commercial downloads will want to download the entire zip file.
the game would have to be reset to actually read the zip in
Auto-update information
Path separators
Casing
separate server gamedir and client gamedir, so if the user starts
a local game after having connected to a network game, it won't stick
with the network game.
allow menu options for game selection?
Read / write config to floppy option.
Different version coexistance?
When building a pak file, make sure a q3config.cfg isn't present in it,
or configs will never get loaded from disk!
todo:
downloading (outside fs?)
game directory passing and restarting
=============================================================================
*/
/*static const uint32_t pak_checksums[] = {
0u,
};
static const uint32_t bonuspak_checksum = 0u;*/
#define MAX_ZPATH 256
#define MAX_SEARCH_PATHS 4096
#define MAX_FILEHASH_SIZE 1024
typedef struct fileInPack_s {
char *name; // name of the file
unsigned long pos; // file info position in zip
unsigned long len; // uncompress file size
struct fileInPack_s* next; // next file in the hash
} fileInPack_t;
typedef struct pack_s {
char pakPathname[MAX_OSPATH]; // c:\jediacademy\gamedata\base
char pakFilename[MAX_OSPATH]; // c:\jediacademy\gamedata\base\assets0.pk3
char pakBasename[MAX_OSPATH]; // assets0
char pakGamename[MAX_OSPATH]; // base
unzFile handle; // handle to zip file
int checksum; // regular checksum
int numfiles; // number of files in pk3
int hashSize; // hash table size (power of 2)
fileInPack_t* *hashTable; // hash table
fileInPack_t* buildBuffer; // buffer with the filenames etc.
} pack_t;
typedef struct directory_s {
char path[MAX_OSPATH]; // c:\jediacademy\gamedata
char fullpath[MAX_OSPATH]; // c:\jediacademy\gamedata\base
char gamedir[MAX_OSPATH]; // base
} directory_t;
typedef struct searchpath_s {
struct searchpath_s *next;
pack_t *pack; // only one of pack / dir will be non NULL
directory_t *dir;
} searchpath_t;
static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators
static cvar_t *fs_debug;
static cvar_t *fs_homepath;
#ifdef MACOS_X
// Also search the .app bundle for .pk3 files
static cvar_t *fs_apppath;
#endif
static cvar_t *fs_basepath;
static cvar_t *fs_basegame;
static cvar_t *fs_cdpath;
static cvar_t *fs_copyfiles;
static cvar_t *fs_gamedirvar;
static cvar_t *fs_dirbeforepak; //rww - when building search path, keep directories at top and insert pk3's under them
static searchpath_t *fs_searchpaths;
static int fs_readCount; // total bytes read
static int fs_loadCount; // total files read
static int fs_packFiles = 0; // total number of files in packs
typedef union qfile_gus {
FILE* o;
unzFile z;
} qfile_gut;
typedef struct qfile_us {
qfile_gut file;
qboolean unique;
} qfile_ut;
typedef struct fileHandleData_s {
qfile_ut handleFiles;
qboolean handleSync;
int fileSize;
int zipFilePos;
int zipFileLen;
qboolean zipFile;
char name[MAX_ZPATH];
} fileHandleData_t;
static fileHandleData_t fsh[MAX_FILE_HANDLES];
// last valid game folder used
char lastValidBase[MAX_OSPATH];
char lastValidGame[MAX_OSPATH];
/* C99 defines __func__ */
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2 || _MSC_VER >= 1300
# define __func__ __FUNCTION__
# else
# define __func__ "(unknown)"
# endif
#endif
/*
==============
FS_Initialized
==============
*/
qboolean FS_Initialized( void ) {
return (qboolean)(fs_searchpaths != NULL);
}
static void FS_AssertInitialised( void ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
}
}
/*
================
return a hash value for the filename
================
*/
static long FS_HashFileName( const char *fname, int hashSize ) {
int i;
long hash;
char letter;
hash = 0;
i = 0;
while (fname[i] != '\0') {
letter = tolower(fname[i]);
if (letter =='.') break; // don't include extension
if (letter =='\\') letter = '/'; // damn path names
if (letter == PATH_SEP) letter = '/'; // damn path names
hash+=(long)(letter)*(i+119);
i++;
}
hash = (hash ^ (hash >> 10) ^ (hash >> 20));
hash &= (hashSize-1);
return hash;
}
static fileHandle_t FS_HandleForFile(void) {
int i;
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o == NULL ) {
return i;
}
}
Com_Printf( "FS_HandleForFile: all handles taken:\n" );
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
Com_Printf( "%d. %s\n", i, fsh[i].name);
}
Com_Error( ERR_DROP, "FS_HandleForFile: none free" );
return 0;
}
static FILE *FS_FileForHandle( fileHandle_t f ) {
if ( f < 1 || f >= MAX_FILE_HANDLES ) {
Com_Error( ERR_DROP, "FS_FileForHandle: out of range" );
}
if (fsh[f].zipFile == qtrue) {
Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" );
}
if ( ! fsh[f].handleFiles.file.o ) {
Com_Error( ERR_DROP, "FS_FileForHandle: NULL" );
}
return fsh[f].handleFiles.file.o;
}
void FS_ForceFlush( fileHandle_t f ) {
FILE *file;
file = FS_FileForHandle(f);
setvbuf( file, NULL, _IONBF, 0 );
}
/*
================
FS_fplength
================
*/
long FS_fplength(FILE *h)
{
long pos;
long end;
pos = ftell(h);
if ( pos == EOF )
return EOF;
fseek(h, 0, SEEK_END);
end = ftell(h);
fseek(h, pos, SEEK_SET);
return end;
}
/*
================
FS_filelength
If this is called on a non-unique FILE (from a pak file),
it will return the size of the pak file, not the expected
size of the file.
================
*/
int FS_filelength( fileHandle_t f ) {
FILE *h;
h = FS_FileForHandle(f);
if(h == NULL)
return EOF;
else
return FS_fplength(h);
}
/*
====================
FS_ReplaceSeparators
Fix things up differently for win/unix/mac
====================
*/
void FS_ReplaceSeparators( char *path ) {
char *s;
qboolean lastCharWasSep = qfalse;
for ( s = path ; *s ; s++ ) {
if ( *s == '/' || *s == '\\' ) {
if ( !lastCharWasSep ) {
*s = PATH_SEP;
lastCharWasSep = qtrue;
} else {
memmove (s, s + 1, strlen (s));
}
} else {
lastCharWasSep = qfalse;
}
}
}
/*
===================
FS_BuildOSPath
Qpath may have either forward or backwards slashes
===================
*/
char *FS_BuildOSPath( const char *qpath ) {
char temp[MAX_OSPATH];
static char ospath[4][MAX_OSPATH];
static int toggle;
int nextToggle = (toggle + 1)&3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement)
toggle = nextToggle;
// Fix for filenames that are given to FS with a leading "/" (/botfiles/Foo)
if (qpath[0] == '\\' || qpath[0] == '/')
qpath++;
Com_sprintf( temp, sizeof(temp), "/base/%s", qpath ); // FIXME SP used fs_gamedir here as well (not sure if this func is even used)
FS_ReplaceSeparators( temp );
Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", fs_basepath->string, temp );
return ospath[toggle];
}
char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) {
char temp[MAX_OSPATH];
static char ospath[4][MAX_OSPATH];
static int toggle;
int nextToggle = (toggle + 1)&3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement)
toggle = nextToggle;
if( !game || !game[0] ) {
game = fs_gamedir;
}
Com_sprintf( temp, sizeof(temp), "/%s/%s", game, qpath );
FS_ReplaceSeparators( temp );
Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp );
return ospath[toggle];
}
/*
============
FS_CreatePath
Creates any directories needed to store the given filename
============
*/
qboolean FS_CreatePath (char *OSPath) {
char *ofs;
char path[MAX_OSPATH];
// make absolutely sure that it can't back up the path
// FIXME: is c: allowed???
if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) {
Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath );
return qtrue;
}
Q_strncpyz( path, OSPath, sizeof( path ) );
FS_ReplaceSeparators( path );
// Skip creation of the root directory as it will always be there
ofs = strchr( path, PATH_SEP );
if ( ofs ) {
ofs++;
}
for (; ofs != NULL && *ofs ; ofs++) {
if (*ofs == PATH_SEP) {
// create the directory
*ofs = 0;
if (!Sys_Mkdir (path)) {
Com_Error( ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"",
path );
}
*ofs = PATH_SEP;
}
}
return qfalse;
}
/*
=================
FS_CheckFilenameIsMutable
ERR_FATAL if trying to maniuplate a file with the platform library, or pk3 extension
=================
*/
static void FS_CheckFilenameIsMutable( const char *filename, const char *function )
{
// Check if the filename ends with the library, or pk3 extension
if( COM_CompareExtension( filename, DLL_EXT )
|| COM_CompareExtension( filename, ".pk3" ) )
{
Com_Error( ERR_FATAL, "%s: Not allowed to manipulate '%s' due "
"to %s extension", function, filename, COM_GetExtension( filename ) );
}
}
/*
=================
FS_CopyFile
Copy a fully specified file from one place to another
=================
*/
// added extra param so behind-the-scenes copying in savegames doesn't clutter up the screen -slc
void FS_CopyFile( char *fromOSPath, char *toOSPath, qboolean qbSilent = qfalse );
void FS_CopyFile( char *fromOSPath, char *toOSPath, qboolean qbSilent ) {
FILE *f;
int len;
byte *buf;
FS_CheckFilenameIsMutable( fromOSPath, __func__ );
if ( !qbSilent )
Com_Printf( "copy %s to %s\n", fromOSPath, toOSPath );
f = fopen( fromOSPath, "rb" );
if ( !f ) {
return;
}
fseek (f, 0, SEEK_END);
len = ftell (f);
fseek (f, 0, SEEK_SET);
if ( len == EOF )
{
fclose( f );
if ( qbSilent )
return;
Com_Error( ERR_FATAL, "Bad file length in FS_CopyFile()" );
}
// we are using direct malloc instead of Z_Malloc here, so it
// probably won't work on a mac... Its only for developers anyway...
buf = (unsigned char *)malloc( len );
if (fread( buf, 1, len, f ) != (size_t)len)
{
fclose( f );
free ( buf );
if ( qbSilent )
return;
Com_Error( ERR_FATAL, "Short read in FS_Copyfiles()\n" );
}
fclose( f );
if( FS_CreatePath( toOSPath ) ) {
free ( buf );
return;
}
f = fopen( toOSPath, "wb" );
if ( !f ) {
free ( buf );
return;
}
if (fwrite( buf, 1, len, f ) != (size_t)len)
{
fclose( f );
free ( buf );
if ( qbSilent )
return;
Com_Error( ERR_FATAL, "Short write in FS_Copyfiles()\n" );
}
fclose( f );
free( buf );
}
/*
===========
FS_Remove
===========
*/
void FS_Remove( const char *osPath ) {
FS_CheckFilenameIsMutable( osPath, __func__ );
remove( osPath );
}
/*
===========
FS_HomeRemove
===========
*/
void FS_HomeRemove( const char *homePath ) {
FS_CheckFilenameIsMutable( homePath, __func__ );
remove( FS_BuildOSPath( fs_homepath->string,
fs_gamedir, homePath ) );
}
// The following functions with "UserGen" in them were added for savegame handling,
// since outside functions aren't supposed to know about full paths/dirs
// "filename" is local to the current gamedir (eg "saves/blah.sav")
//
void FS_DeleteUserGenFile( const char *filename ) {
FS_HomeRemove( filename );
}
// filenames are local (eg "saves/blah.sav")
//
// return: qtrue = OK
//
qboolean FS_MoveUserGenFile( const char *filename_src, const char *filename_dst ) {
char *from_ospath, *to_ospath;
FS_AssertInitialised();
// don't let sound stutter
S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename_src );
to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename_dst );
if ( fs_debug->integer ) {
Com_Printf( "FS_MoveUserGenFile: %s --> %s\n", from_ospath, to_ospath );
}
FS_CheckFilenameIsMutable( to_ospath, __func__ );
remove( to_ospath );
return (qboolean)!rename( from_ospath, to_ospath );
}
/*
===========
FS_Rmdir
Removes a directory, optionally deleting all files under it
===========
*/
void FS_Rmdir( const char *osPath, qboolean recursive ) {
FS_CheckFilenameIsMutable( osPath, __func__ );
if ( recursive ) {
int numfiles;
int i;
char **filesToRemove = Sys_ListFiles( osPath, "", NULL, &numfiles, qfalse );
for ( i = 0; i < numfiles; i++ ) {
char fileOsPath[MAX_OSPATH];
Com_sprintf( fileOsPath, sizeof( fileOsPath ), "%s/%s", osPath, filesToRemove[i] );
FS_Remove( fileOsPath );
}
FS_FreeFileList( filesToRemove );
char **directoriesToRemove = Sys_ListFiles( osPath, "/", NULL, &numfiles, qfalse );
for ( i = 0; i < numfiles; i++ ) {
if ( !Q_stricmp( directoriesToRemove[i], "." ) || !Q_stricmp( directoriesToRemove[i], ".." ) ) {
continue;
}
char directoryOsPath[MAX_OSPATH];
Com_sprintf( directoryOsPath, sizeof( directoryOsPath ), "%s/%s", osPath, directoriesToRemove[i] );
FS_Rmdir( directoryOsPath, qtrue );
}
FS_FreeFileList( directoriesToRemove );
}
rmdir( osPath );
}
/*
===========
FS_HomeRmdir
Removes a directory, optionally deleting all files under it
===========
*/
void FS_HomeRmdir( const char *homePath, qboolean recursive ) {
FS_CheckFilenameIsMutable( homePath, __func__ );
FS_Rmdir( FS_BuildOSPath( fs_homepath->string,
fs_gamedir, homePath ), recursive );
}
/*
================
FS_FileInPathExists
Tests if path and file exists
================
*/
qboolean FS_FileInPathExists(const char *testpath)
{
FILE *filep;
filep = fopen(testpath, "rb");
if(filep)
{
fclose(filep);
return qtrue;
}
return qfalse;
}
/*
================
FS_FileExists
Tests if the file exists in the current gamedir, this DOES NOT
search the paths. This is to determine if opening a file to write
(which always goes into the current gamedir) will cause any overwrites.
NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards
================
*/
qboolean FS_FileExists( const char *file )
{
return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file));
}
/*
================
FS_SV_FileExists
Tests if the file exists
================
*/
qboolean FS_SV_FileExists( const char *file )
{
char *testpath;
testpath = FS_BuildOSPath( fs_homepath->string, file, "");
testpath[strlen(testpath)-1] = '\0';
return FS_FileInPathExists(testpath);
}
/*
===========
FS_SV_FOpenFileWrite
===========
*/
fileHandle_t FS_SV_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
FS_AssertInitialised();
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileWrite: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = fopen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_SV_FOpenFileRead
search for a file somewhere below the home path, base path or cd path
we search in that order, matching FS_SV_FOpenFileRead order
===========
*/
int FS_SV_FOpenFileRead( const char *filename, fileHandle_t *fp ) {
char *ospath;
fileHandle_t f = 0;
FS_AssertInitialised();
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
S_ClearSoundBuffer();
// search homepath
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
// remove trailing slash
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o)
{
// NOTE TTimo on non *nix systems, fs_homepath == fs_basepath, might want to avoid
if (Q_stricmp(fs_homepath->string,fs_basepath->string))
{
// search basepath
ospath = FS_BuildOSPath( fs_basepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
if ( !fsh[f].handleFiles.file.o )
{
f = 0;
}
}
if (!fsh[f].handleFiles.file.o)
{
// search cd path
ospath = FS_BuildOSPath( fs_cdpath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if (fs_debug->integer)
{
Com_Printf( "FS_SV_FOpenFileRead (fs_cdpath) : %s\n", ospath );
}
fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
fsh[f].handleSync = qfalse;
if ( !fsh[f].handleFiles.file.o )
{
f = 0;
}
}
*fp = f;
if (f) {
return FS_filelength(f);
}
return 0;
}
/*
===========
FS_SV_Rename
===========
*/
void FS_SV_Rename( const char *from, const char *to, qboolean safe ) {
char *from_ospath, *to_ospath;
FS_AssertInitialised();
// don't let sound stutter
S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, from, "" );
to_ospath = FS_BuildOSPath( fs_homepath->string, to, "" );
from_ospath[strlen(from_ospath)-1] = '\0';
to_ospath[strlen(to_ospath)-1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath );
}
if ( safe ) {
FS_CheckFilenameIsMutable( to_ospath, __func__ );
}
if (rename( from_ospath, to_ospath )) {
// Failed, try copying it and deleting the original
FS_CopyFile ( from_ospath, to_ospath );
FS_Remove ( from_ospath );
}
}
/*
===========
FS_Rename
===========
*/
void FS_Rename( const char *from, const char *to ) {
char *from_ospath, *to_ospath;
FS_AssertInitialised();
// don't let sound stutter
S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from );
to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to );
if ( fs_debug->integer ) {
Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath );
}
FS_CheckFilenameIsMutable( to_ospath, __func__ );
if (rename( from_ospath, to_ospath )) {
// Failed, try copying it and deleting the original
FS_CopyFile ( from_ospath, to_ospath );
FS_Remove ( from_ospath );
}
}
/*
===========
FS_FCloseFile
Close a file.
There are three cases handled:
* normal file: closed with fclose.
* file in pak3 archive: subfile is closed with unzCloseCurrentFile, but the
minizip handle to the pak3 remains open.
* file in pak3 archive, opened with "unique" flag: This file did not use
the system minizip handle to the pak3 file, but its own dedicated one.
The dedicated handle is closed with unzClose.
===========
*/
void FS_FCloseFile( fileHandle_t f ) {
FS_AssertInitialised();
if (fsh[f].zipFile == qtrue) {
unzCloseCurrentFile( fsh[f].handleFiles.file.z );
if ( fsh[f].handleFiles.unique ) {
unzClose( fsh[f].handleFiles.file.z );
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
return;
}
// we didn't find it as a pak, so close it as a unique file
if (fsh[f].handleFiles.file.o) {
fclose (fsh[f].handleFiles.file.o);
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
}
/*
===========
FS_FOpenFileWrite
===========
*/
fileHandle_t FS_FOpenFileWrite( const char *filename, qboolean safe ) {
char *ospath;
fileHandle_t f;
FS_AssertInitialised();
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileWrite: %s\n", ospath );
}
if ( safe ) {
FS_CheckFilenameIsMutable( ospath, __func__ );
}
if( FS_CreatePath( ospath ) ) {
return 0;
}
// enabling the following line causes a recursive function call loop
// when running with +set logfile 1 +set developer 1
//Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = fopen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_FOpenFileAppend
===========
*/
fileHandle_t FS_FOpenFileAppend( const char *filename ) {
char *ospath;
fileHandle_t f;
FS_AssertInitialised();
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileAppend: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
fsh[f].handleFiles.file.o = fopen( ospath, "ab" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_FilenameCompare
Ignore case and separator char distinctions
===========
*/
qboolean FS_FilenameCompare( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if (c1 >= 'a' && c1 <= 'z') {
c1 -= ('a' - 'A');
}
if (c2 >= 'a' && c2 <= 'z') {
c2 -= ('a' - 'A');
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if (c1 != c2) {
return qtrue; // strings not equal
}
} while (c1);
return qfalse; // strings are equal
}
/*
===========
FS_IsExt
Return qtrue if ext matches file extension filename
===========
*/
qboolean FS_IsExt(const char *filename, const char *ext, int namelen)
{
int extlen;
extlen = strlen(ext);
if(extlen > namelen)
return qfalse;
filename += namelen - extlen;
return (qboolean)!Q_stricmp(filename, ext);
}
/*
===========
FS_IsDemoExt
Return qtrue if filename has a demo extension
===========
*/
#define DEMO_EXTENSION "dm_"
qboolean FS_IsDemoExt(const char *filename, int namelen)
{
const char *ext_test;
ext_test = strrchr(filename, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMO_EXTENSION, ARRAY_LEN(DEMO_EXTENSION) - 1))
{
int protocol = atoi(ext_test + ARRAY_LEN(DEMO_EXTENSION));
if(protocol == PROTOCOL_VERSION)
return qtrue;
}
return qfalse;
}
#ifdef _WIN32
bool Sys_GetFileTime(LPCSTR psFileName, FILETIME &ft)
{
bool bSuccess = false;
HANDLE hFile = INVALID_HANDLE_VALUE;
hFile = CreateFile( psFileName, // LPCTSTR lpFileName, // pointer to name of the file
GENERIC_READ, // DWORD dwDesiredAccess, // access (read-write) mode
FILE_SHARE_READ, // DWORD dwShareMode, // share mode
NULL, // LPSECURITY_ATTRIBUTES lpSecurityAttributes, // pointer to security attributes
OPEN_EXISTING, // DWORD dwCreationDisposition, // how to create
FILE_FLAG_NO_BUFFERING,// DWORD dwFlagsAndAttributes, // file attributes
NULL // HANDLE hTemplateFile // handle to file with attributes to
);
if (hFile != INVALID_HANDLE_VALUE)
{
if (GetFileTime(hFile, // handle to file
NULL, // LPFILETIME lpCreationTime
NULL, // LPFILETIME lpLastAccessTime
&ft // LPFILETIME lpLastWriteTime
)
)
{
bSuccess = true;
}
CloseHandle(hFile);
}
return bSuccess;
}
bool Sys_FileOutOfDate( LPCSTR psFinalFileName /* dest */, LPCSTR psDataFileName /* src */ )
{
FILETIME ftFinalFile, ftDataFile;
if (Sys_GetFileTime(psFinalFileName, ftFinalFile) && Sys_GetFileTime(psDataFileName, ftDataFile))
{
// timer res only accurate to within 2 seconds on FAT, so can't do exact compare...
//
//LONG l = CompareFileTime( &ftFinalFile, &ftDataFile );
if ( (abs((double)(ftFinalFile.dwLowDateTime - ftDataFile.dwLowDateTime)) <= 20000000 ) &&
ftFinalFile.dwHighDateTime == ftDataFile.dwHighDateTime
)
{
return false; // file not out of date, ie use it.
}
return true; // flag return code to copy over a replacement version of this file
}
// extra error check, report as suspicious if you find a file locally but not out on the net.,.
//
if (com_developer->integer)
{
if (!Sys_GetFileTime(psDataFileName, ftDataFile))
{
Com_Printf( "Sys_FileOutOfDate: reading %s but it's not on the net!\n", psFinalFileName);
}
}
return false;
}
#endif // _WIN32
bool FS_FileCacheable(const char* const filename)
{
extern cvar_t *com_buildScript;
if (com_buildScript && com_buildScript->integer)
{
return true;
}
return( strchr(filename, '/') != 0 );
}
/*
===========
FS_FOpenFileRead
Finds the file in the search path.
Returns filesize and an open FILE pointer.
Used for streaming data out of either a
separate file or a ZIP file.
===========
*/
extern qboolean com_fullyInitialized;
long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean uniqueFILE ) {
searchpath_t *search;
char *netpath;
pack_t *pak;
fileInPack_t *pakFile;
directory_t *dir;
long hash;
//unz_s *zfi;
//void *temp;
hash = 0;
FS_AssertInitialised();
if ( file == NULL ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'file' parameter passed\n" );
}
if ( !filename ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" );
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
*file = 0;
return -1;
}
// make sure the q3key file is only readable by the quake3.exe at initialization
// any other time the key should only be accessed in memory using the provided functions
if( com_fullyInitialized && strstr( filename, "q3key" ) ) {
*file = 0;
return -1;
}
//
// search through the path, one element at a time
//
*file = FS_HandleForFile();
fsh[*file].handleFiles.unique = uniqueFILE;
// this new bool is in for an optimisation, if you (eg) opened a BSP file under fs_copyfiles==2,
// then it triggered a copy operation to update your local HD version, then this will re-open the
// file handle on your local version, not the net build. This uses a bit more CPU to re-do the loop
// logic, but should read faster than accessing the net version a second time.
//
qboolean bFasterToReOpenUsingNewLocalFile = qfalse;
do
{
bFasterToReOpenUsingNewLocalFile = qfalse;
for ( search = fs_searchpaths ; search ; search = search->next ) {
//
if ( search->pack ) {
hash = FS_HashFileName(filename, search->pack->hashSize);
}
// is the element a pak file?
if ( search->pack && search->pack->hashTable[hash] ) {
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
// found it!
if ( uniqueFILE ) {
// open a new file on the pakfile
fsh[*file].handleFiles.file.z = unzOpen (pak->pakFilename);
if (fsh[*file].handleFiles.file.z == NULL) {
Com_Error (ERR_FATAL, "Couldn't open %s", pak->pakFilename);
}
} else {
fsh[*file].handleFiles.file.z = pak->handle;
}
Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) );
fsh[*file].zipFile = qtrue;
// set the file position in the zip file (also sets the current file info)
unzSetOffset(fsh[*file].handleFiles.file.z, pakFile->pos);
// open the file in the zip
unzOpenCurrentFile(fsh[*file].handleFiles.file.z);
#if 0
zfi = (unz_s *)fsh[*file].handleFiles.file.z;
// in case the file was new
temp = zfi->filestream;
// set the file position in the zip file (also sets the current file info)
unzSetOffset(pak->handle, pakFile->pos);
// copy the file info into the unzip structure
Com_Memcpy( zfi, pak->handle, sizeof(unz_s) );
// we copy this back into the structure
zfi->filestream = temp;
// open the file in the zip
unzOpenCurrentFile( fsh[*file].handleFiles.file.z );
#endif
fsh[*file].zipFilePos = pakFile->pos;
fsh[*file].zipFileLen = pakFile->len;
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileRead: %s (found in '%s')\n",
filename, pak->pakFilename );
}
return pakFile->len;
}
pakFile = pakFile->next;
} while(pakFile != NULL);
} else if ( search->dir ) {
// check a file in the directory tree
dir = search->dir;
netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename );
fsh[*file].handleFiles.file.o = fopen (netpath, "rb");
if ( !fsh[*file].handleFiles.file.o ) {
continue;
}
#ifdef _WIN32
// if running with fs_copyfiles 2, and search path == local, then we need to fail to open
// if the time/date stamp != the network version (so it'll loop round again and use the network path,
// which comes later in the search order)
//
if ( fs_copyfiles->integer == 2 && fs_cdpath->string[0] && !Q_stricmp( dir->path, fs_basepath->string )
&& FS_FileCacheable(filename) )
{
if ( Sys_FileOutOfDate( netpath, FS_BuildOSPath( fs_cdpath->string, dir->gamedir, filename ) ))
{
fclose(fsh[*file].handleFiles.file.o);
fsh[*file].handleFiles.file.o = 0;
continue; //carry on to find the cdpath version.
}
}
#endif
Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) );
fsh[*file].zipFile = qfalse;
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename,
dir->path, PATH_SEP, dir->gamedir );
}
#ifdef _WIN32
// if we are getting it from the cdpath, optionally copy it
// to the basepath
if ( fs_copyfiles->integer && !Q_stricmp( dir->path, fs_cdpath->string ) ) {
char *copypath;
copypath = FS_BuildOSPath( fs_basepath->string, dir->gamedir, filename );
switch ( fs_copyfiles->integer )
{
default:
case 1:
{
FS_CopyFile( netpath, copypath );
}
break;
case 2:
{
if (FS_FileCacheable(filename) )
{
// maybe change this to Com_DPrintf? On the other hand...
//
Com_Printf( "fs_copyfiles(2), Copying: %s to %s\n", netpath, copypath );
FS_CreatePath( copypath );
bool bOk = true;
if (!CopyFile( netpath, copypath, FALSE ))
{
DWORD dwAttrs = GetFileAttributes(copypath);
SetFileAttributes(copypath, dwAttrs & ~FILE_ATTRIBUTE_READONLY);
bOk = !!CopyFile( netpath, copypath, FALSE );
}
if (bOk)
{
// clear this handle and setup for re-opening of the new local copy...
//
bFasterToReOpenUsingNewLocalFile = qtrue;
fclose(fsh[*file].handleFiles.file.o);
fsh[*file].handleFiles.file.o = NULL;
}
}
}
break;
}
}
#endif
if (bFasterToReOpenUsingNewLocalFile)
{
break; // and re-read the local copy, not the net version
}
return FS_fplength(fsh[*file].handleFiles.file.o);
}
}
}
while ( bFasterToReOpenUsingNewLocalFile );
Com_DPrintf ("Can't find %s\n", filename);
*file = 0;
return -1;
}
/*
=================
FS_Read
Properly handles partial reads
=================
*/
int FS_Read( void *buffer, int len, fileHandle_t f ) {
int block, remaining;
int read;
byte *buf;
int tries;
FS_AssertInitialised();
if ( !f ) {
return 0;
}
buf = (byte *)buffer;
fs_readCount += len;
if (fsh[f].zipFile == qfalse) {
remaining = len;
tries = 0;
while (remaining) {
block = remaining;
read = fread (buf, 1, block, fsh[f].handleFiles.file.o);
if (read == 0) {
// we might have been trying to read from a CD, which
// sometimes returns a 0 read on windows
if (!tries) {
tries = 1;
} else {
return len-remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read");
}
}
if (read == -1) {
Com_Error (ERR_FATAL, "FS_Read: -1 bytes read");
}
remaining -= read;
buf += read;
}
return len;
} else {
return unzReadCurrentFile(fsh[f].handleFiles.file.z, buffer, len);
}
}
/*
=================
FS_Write
Properly handles partial writes
=================
*/
int FS_Write( const void *buffer, int len, fileHandle_t h ) {
int block, remaining;
int written;
byte *buf;
int tries;
FILE *f;
FS_AssertInitialised();
if ( !h ) {
return 0;
}
f = FS_FileForHandle(h);
buf = (byte *)buffer;
remaining = len;
tries = 0;
while (remaining) {
block = remaining;
written = fwrite (buf, 1, block, f);
if (written == 0) {
if (!tries) {
tries = 1;
} else {
Com_Printf( "FS_Write: 0 bytes written\n" );
return 0;
}
}
if (written == -1) {
Com_Printf( "FS_Write: -1 bytes written\n" );
return 0;
}
remaining -= written;
buf += written;
}
if ( fsh[h].handleSync ) {
fflush( f );
}
return len;
}
#define MAXPRINTMSG 4096
void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start (argptr,fmt);
Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
va_end (argptr);
FS_Write(msg, strlen(msg), h);
}
#define PK3_SEEK_BUFFER_SIZE 65536
/*
=================
FS_Seek
=================
*/
int FS_Seek( fileHandle_t f, long offset, int origin ) {
int _origin;
FS_AssertInitialised();
if (fsh[f].zipFile == qtrue) {
//FIXME: this is really, really crappy
//(but better than what was here before)
byte buffer[PK3_SEEK_BUFFER_SIZE];
int remainder;
int currentPosition = FS_FTell( f );
// change negative offsets into FS_SEEK_SET
if ( offset < 0 ) {
switch( origin ) {
case FS_SEEK_END:
remainder = fsh[f].zipFileLen + offset;
break;
case FS_SEEK_CUR:
remainder = currentPosition + offset;
break;
case FS_SEEK_SET:
default:
remainder = 0;
break;
}
if ( remainder < 0 ) {
remainder = 0;
}
origin = FS_SEEK_SET;
} else {
if ( origin == FS_SEEK_END ) {
remainder = fsh[f].zipFileLen - currentPosition + offset;
} else {
remainder = offset;
}
}
switch( origin ) {
case FS_SEEK_SET:
if ( remainder == currentPosition ) {
return offset;
}
unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
unzOpenCurrentFile(fsh[f].handleFiles.file.z);
//fallthrough
case FS_SEEK_END:
case FS_SEEK_CUR:
while( remainder > PK3_SEEK_BUFFER_SIZE ) {
FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f );
remainder -= PK3_SEEK_BUFFER_SIZE;
}
FS_Read( buffer, remainder, f );
return offset;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
return -1;
}
} else {
FILE *file;
file = FS_FileForHandle(f);
switch( origin ) {
case FS_SEEK_CUR:
_origin = SEEK_CUR;
break;
case FS_SEEK_END:
_origin = SEEK_END;
break;
case FS_SEEK_SET:
_origin = SEEK_SET;
break;
default:
_origin = SEEK_CUR;
Com_Error( ERR_FATAL, "Bad origin in FS_Seek\n" );
break;
}
return fseek( file, offset, _origin );
}
}
/*
======================================================================================
CONVENIENCE FUNCTIONS FOR ENTIRE FILES
======================================================================================
*/
int FS_FileIsInPAK(const char *filename ) {
searchpath_t *search;
pack_t *pak;
fileInPack_t *pakFile;
long hash = 0;
FS_AssertInitialised();
if ( !filename ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" );
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
return -1;
}
//
// search through the path, one element at a time
//
for ( search = fs_searchpaths ; search ; search = search->next ) {
//
if (search->pack) {
hash = FS_HashFileName(filename, search->pack->hashSize);
}
// is the element a pak file?
if ( search->pack && search->pack->hashTable[hash] ) {
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
return 1;
}
pakFile = pakFile->next;
} while(pakFile != NULL);
}
}
return -1;
}
/*
============
FS_ReadFile
Filename are relative to the quake search path
a null buffer will just return the file length without loading
============
*/
long FS_ReadFile( const char *qpath, void **buffer ) {
fileHandle_t h;
byte* buf;
long len;
FS_AssertInitialised();
if ( !qpath || !qpath[0] ) {
Com_Error( ERR_FATAL, "FS_ReadFile with empty name\n" );
}
// stop sounds from repeating
S_ClearSoundBuffer();
buf = NULL; // quiet compiler warning
// look for it in the filesystem or pack files
len = FS_FOpenFileRead( qpath, &h, qfalse );
if ( h == 0 ) {
if ( buffer ) {
*buffer = NULL;
}
return -1;
}
if ( !buffer ) {
FS_FCloseFile( h);
return len;
}
fs_loadCount++;
buf = (byte*)Z_Malloc( len+1, TAG_FILESYS, qfalse);
buf[len]='\0'; // because we're not calling Z_Malloc with optional trailing 'bZeroIt' bool
*buffer = buf;
Z_Label(buf, qpath);
// PRECACE CHECKER!
#ifndef FINAL_BUILD
if (com_sv_running && com_sv_running->integer && cls.state >= CA_ACTIVE) { //com_cl_running
if (strncmp(qpath,"menu/",5) ) {
Com_DPrintf( S_COLOR_MAGENTA"FS_ReadFile: %s NOT PRECACHED!\n", qpath );
}
}
#endif
FS_Read (buf, len, h);
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
FS_FCloseFile( h );
return len;
}
/*
=============
FS_FreeFile
=============
*/
void FS_FreeFile( void *buffer ) {
FS_AssertInitialised();
if ( !buffer ) {
Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" );
}
Z_Free( buffer );
}
/*
============
FS_WriteFile
Filename are reletive to the quake search path
============
*/
void FS_WriteFile( const char *qpath, const void *buffer, int size ) {
fileHandle_t f;
FS_AssertInitialised();
if ( !qpath || !buffer ) {
Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" );
}
f = FS_FOpenFileWrite( qpath );
if ( !f ) {
Com_Printf( "Failed to open %s\n", qpath );
return;
}
FS_Write( buffer, size, f );
FS_FCloseFile( f );
}
/*
==========================================================================
ZIP FILE LOADING
==========================================================================
*/
/*
=================
FS_LoadZipFile
Creates a new pak_t in the search chain for the contents
of a zip file.
=================
*/
static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename )
{
fileInPack_t *buildBuffer;
pack_t *pack;
unzFile uf;
int err;
unz_global_info gi;
char filename_inzip[MAX_ZPATH];
unz_file_info file_info;
int len;
size_t i;
long hash;
int fs_numHeaderLongs;
int *fs_headerLongs;
char *namePtr;
fs_numHeaderLongs = 0;
uf = unzOpen(zipfile);
err = unzGetGlobalInfo (uf,&gi);
if (err != UNZ_OK)
return NULL;
len = 0;
unzGoToFirstFile(uf);
for (i = 0; i < gi.number_entry; i++)
{
err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
if (err != UNZ_OK) {
break;
}
len += strlen(filename_inzip) + 1;
unzGoToNextFile(uf);
}
buildBuffer = (struct fileInPack_s *)Z_Malloc( (gi.number_entry * sizeof( fileInPack_t )) + len, TAG_FILESYS, qtrue );
namePtr = ((char *) buildBuffer) + gi.number_entry * sizeof( fileInPack_t );
fs_headerLongs = (int *)Z_Malloc( gi.number_entry * sizeof(int), TAG_FILESYS, qtrue );
// get the hash table size from the number of files in the zip
// because lots of custom pk3 files have less than 32 or 64 files
for (i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1) {
if (i > gi.number_entry) {
break;
}
}
pack = (pack_t *)Z_Malloc( sizeof( pack_t ) + i * sizeof(fileInPack_t *), TAG_FILESYS, qtrue );
pack->hashSize = i;
pack->hashTable = (fileInPack_t **) (((char *) pack) + sizeof( pack_t ));
for(int j = 0; j < pack->hashSize; j++) {
pack->hashTable[j] = NULL;
}
Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) );
Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) );
// strip .pk3 if needed
if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) {
pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0;
}
pack->handle = uf;
pack->numfiles = gi.number_entry;
unzGoToFirstFile(uf);
for (i = 0; i < gi.number_entry; i++)
{
err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
if (err != UNZ_OK) {
break;
}
if (file_info.uncompressed_size > 0) {
fs_headerLongs[fs_numHeaderLongs++] = LittleLong(file_info.crc);
}
Q_strlwr( filename_inzip );
hash = FS_HashFileName(filename_inzip, pack->hashSize);
buildBuffer[i].name = namePtr;
strcpy( buildBuffer[i].name, filename_inzip );
namePtr += strlen(filename_inzip) + 1;
// store the file position in the zip
buildBuffer[i].pos = unzGetOffset(uf);
buildBuffer[i].len = file_info.uncompressed_size;
buildBuffer[i].next = pack->hashTable[hash];
pack->hashTable[hash] = &buildBuffer[i];
unzGoToNextFile(uf);
}
pack->checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs );
pack->checksum = LittleLong( pack->checksum );
Z_Free(fs_headerLongs);
pack->buildBuffer = buildBuffer;
return pack;
}
/*
=================
FS_FreePak
Frees a pak structure and releases all associated resources
=================
*/
void FS_FreePak(pack_t *thepak)
{
unzClose(thepak->handle);
Z_Free(thepak->buildBuffer);
Z_Free(thepak);
}
/*
=================================================================================
DIRECTORY SCANNING FUNCTIONS
=================================================================================
*/
#define MAX_FOUND_FILES 0x1000
static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) {
int len, at, newdep;
newdep = 0;
zpath[0] = 0;
len = 0;
at = 0;
while(zname[at] != 0)
{
if (zname[at]=='/' || zname[at]=='\\') {
len = at;
newdep++;
}
at++;
}
strcpy(zpath, zname);
zpath[len] = 0;
*depth = newdep;
return len;
}
/*
==================
FS_AddFileToList
==================
*/
static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) {
int i;
if ( nfiles == MAX_FOUND_FILES - 1 ) {
return nfiles;
}
for ( i = 0 ; i < nfiles ; i++ ) {
if ( !Q_stricmp( name, list[i] ) ) {
return nfiles; // allready in list
}
}
list[nfiles] = CopyString( name );
nfiles++;
return nfiles;
}
/*
===============
FS_ListFilteredFiles
Returns a uniqued list of files that match the given criteria
from all search paths
===============
*/
char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles ) {
int nfiles;
char **listCopy;
char *list[MAX_FOUND_FILES];
searchpath_t *search;
int i;
int pathLength;
int extensionLength;
int length, pathDepth, temp;
pack_t *pak;
fileInPack_t *buildBuffer;
char zpath[MAX_ZPATH];
FS_AssertInitialised();
if ( !path ) {
*numfiles = 0;
return NULL;
}
if ( !extension ) {
extension = "";
}
pathLength = strlen( path );
if ( path[pathLength-1] == '\\' || path[pathLength-1] == '/' ) {
pathLength--;
}
extensionLength = strlen( extension );
nfiles = 0;
FS_ReturnPath(path, zpath, &pathDepth);
//
// search through the path, one element at a time, adding to list
//
for (search = fs_searchpaths ; search ; search = search->next) {
// is the element a pak file?
if (search->pack) {
// look through all the pak file elements
pak = search->pack;
buildBuffer = pak->buildBuffer;
for (i = 0; i < pak->numfiles; i++) {
char *name;
int zpathLen, depth;
// check for directory match
name = buildBuffer[i].name;
//
if (filter) {
// case insensitive
if (!Com_FilterPath( filter, name, qfalse ))
continue;
// unique the match
nfiles = FS_AddFileToList( name, list, nfiles );
}
else {
zpathLen = FS_ReturnPath(name, zpath, &depth);
if ( (depth-pathDepth)>2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) {
continue;
}
// check for extension match
length = strlen( name );
if ( length < extensionLength ) {
continue;
}
if ( Q_stricmp( name + length - extensionLength, extension ) ) {
continue;
}
// unique the match
temp = pathLength;
if (pathLength) {
temp++; // include the '/'
}
nfiles = FS_AddFileToList( name + temp, list, nfiles );
}
}
} else if (search->dir) { // scan for files in the filesystem
char *netpath;
int numSysFiles;
char **sysFiles;
char *name;
netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path );
sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse );
for ( i = 0 ; i < numSysFiles ; i++ ) {
// unique the match
name = sysFiles[i];
nfiles = FS_AddFileToList( name, list, nfiles );
}
Sys_FreeFileList( sysFiles );
}
}
// return a copy of the list
*numfiles = nfiles;
if ( !nfiles ) {
return NULL;
}
listCopy = (char **)Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ), TAG_FILESYS, qfalse );
for ( i = 0 ; i < nfiles ; i++ ) {
listCopy[i] = list[i];
}
listCopy[i] = NULL;
return listCopy;
}
/*
=================
FS_ListFiles
=================
*/
char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) {
return FS_ListFilteredFiles( path, extension, NULL, numfiles );
}
/*
=================
FS_FreeFileList
=================
*/
void FS_FreeFileList( char **fileList ) {
//rwwRMG - changed to fileList to not conflict with list type
int i;
FS_AssertInitialised();
if ( !fileList ) {
return;
}
for ( i = 0 ; fileList[i] ; i++ ) {
Z_Free( fileList[i] );
}
Z_Free( fileList );
}
/*
================
FS_GetFileList
================
*/
int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
int nFiles, i, nTotal, nLen;
char **pFiles = NULL;
*listbuf = 0;
nFiles = 0;
nTotal = 0;
if (Q_stricmp(path, "$modlist") == 0) {
return FS_GetModList(listbuf, bufsize);
}
pFiles = FS_ListFiles(path, extension, &nFiles);
for (i =0; i < nFiles; i++) {
nLen = strlen(pFiles[i]) + 1;
if (nTotal + nLen + 1 < bufsize) {
strcpy(listbuf, pFiles[i]);
listbuf += nLen;
nTotal += nLen;
}
else {
nFiles = i;
break;
}
}
FS_FreeFileList(pFiles);
return nFiles;
}
/*
=======================
Sys_ConcatenateFileLists
mkv: Naive implementation. Concatenates three lists into a
new list, and frees the old lists from the heap.
bk001129 - from cvs1.17 (mkv)
FIXME TTimo those two should move to common.c next to Sys_ListFiles
=======================
*/
static unsigned int Sys_CountFileList(char **fileList)
{
int i = 0;
if (fileList)
{
while (*fileList)
{
fileList++;
i++;
}
}
return i;
}
static char** Sys_ConcatenateFileLists( char **list0, char **list1, char **list2 )
{
int totalLength = 0;
char** cat = NULL, **dst, **src;
totalLength += Sys_CountFileList(list0);
totalLength += Sys_CountFileList(list1);
totalLength += Sys_CountFileList(list2);
/* Create new list. */
dst = cat = (char **)Z_Malloc( ( totalLength + 1 ) * sizeof( char* ), TAG_FILESYS, qtrue );
/* Copy over lists. */
if (list0) {
for (src = list0; *src; src++, dst++)
*dst = *src;
}
if (list1) {
for (src = list1; *src; src++, dst++)
*dst = *src;
}
if (list2) {
for (src = list2; *src; src++, dst++)
*dst = *src;
}
// Terminate the list
*dst = NULL;
// Free our old lists.
// NOTE: not freeing their content, it's been merged in dst and still being used
if (list0) Z_Free( list0 );
if (list1) Z_Free( list1 );
if (list2) Z_Free( list2 );
return cat;
}
//#endif
// For base game mod listing
const char *SE_GetString( const char *psPackageAndStringReference );
/*
================
FS_GetModList
Returns a list of mod directory names
A mod directory is a peer to base with a pk3 in it
The directories are searched in base path, cd path and home path
================
*/
int FS_GetModList( char *listbuf, int bufsize ) {
int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen;
char **pFiles = NULL;
char **pPaks = NULL;
char *name, *path;
char descPath[MAX_OSPATH];
fileHandle_t descHandle;
int dummy;
char **pFiles0 = NULL;
char **pFiles1 = NULL;
char **pFiles2 = NULL;
qboolean bDrop = qfalse;
*listbuf = 0;
nMods = nPotential = nTotal = 0;
pFiles0 = Sys_ListFiles( fs_homepath->string, NULL, NULL, &dummy, qtrue );
pFiles1 = Sys_ListFiles( fs_basepath->string, NULL, NULL, &dummy, qtrue );
pFiles2 = Sys_ListFiles( fs_cdpath->string, NULL, NULL, &dummy, qtrue );
// we searched for mods in the three paths
// it is likely that we have duplicate names now, which we will cleanup below
pFiles = Sys_ConcatenateFileLists( pFiles0, pFiles1, pFiles2 );
nPotential = Sys_CountFileList(pFiles);
for ( i = 0 ; i < nPotential ; i++ ) {
name = pFiles[i];
// NOTE: cleaner would involve more changes
// ignore duplicate mod directories
if (i!=0) {
bDrop = qfalse;
for(j=0; j<i; j++)
{
if (Q_stricmp(pFiles[j],name)==0) {
// this one can be dropped
bDrop = qtrue;
break;
}
}
}
if (bDrop) {
continue;
}
// we drop "." and ".."
if (Q_stricmpn(name, ".", 1)) {
// now we need to find some .pk3 files to validate the mod
// NOTE TTimo: (actually I'm not sure why .. what if it's a mod under developement with no .pk3?)
// we didn't keep the information when we merged the directory names, as to what OS Path it was found under
// so it could be in base path, cd path or home path
// we will try each three of them here (yes, it's a bit messy)
path = FS_BuildOSPath( fs_basepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse);
Sys_FreeFileList( pPaks ); // we only use Sys_ListFiles to check wether .pk3 files are present
/* Try on cd path */
if( nPaks <= 0 ) {
path = FS_BuildOSPath( fs_cdpath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
/* try on home path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_homepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
if (nPaks > 0) {
bool isBase = !Q_stricmp( name, BASEGAME );
nLen = isBase ? 1 : strlen(name) + 1;
// nLen is the length of the mod path
// we need to see if there is a description available
descPath[0] = '\0';
strcpy(descPath, name);
strcat(descPath, "/description.txt");
nDescLen = FS_SV_FOpenFileRead( descPath, &descHandle );
if ( nDescLen > 0 && descHandle) {
FILE *file;
file = FS_FileForHandle(descHandle);
Com_Memset( descPath, 0, sizeof( descPath ) );
nDescLen = fread(descPath, 1, 48, file);
if (nDescLen >= 0) {
descPath[nDescLen] = '\0';
}
FS_FCloseFile(descHandle);
} else if ( isBase ) {
strcpy(descPath, SE_GetString("MENUS_JEDI_ACADEMY"));
} else {
strcpy(descPath, name);
}
nDescLen = strlen(descPath) + 1;
if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) {
if ( isBase )
strcpy(listbuf, "");
else
strcpy(listbuf, name);
listbuf += nLen;
strcpy(listbuf, descPath);
listbuf += nDescLen;
nTotal += nLen + nDescLen;
nMods++;
}
else {
break;
}
}
}
}
Sys_FreeFileList( pFiles );
return nMods;
}
//============================================================================
/*
================
FS_Dir_f
================
*/
void FS_Dir_f( void ) {
char *path;
char *extension;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) {
Com_Printf( "usage: dir <directory> [extension]\n" );
return;
}
if ( Cmd_Argc() == 2 ) {
path = Cmd_Argv( 1 );
extension = "";
} else {
path = Cmd_Argv( 1 );
extension = Cmd_Argv( 2 );
}
Com_Printf( "Directory of %s %s\n", path, extension );
Com_Printf( "---------------\n" );
dirnames = FS_ListFiles( path, extension, &ndirs );
for ( i = 0; i < ndirs; i++ ) {
Com_Printf( "%s\n", dirnames[i] );
}
FS_FreeFileList( dirnames );
}
/*
===========
FS_ConvertPath
===========
*/
void FS_ConvertPath( char *s ) {
while (*s) {
if ( *s == '\\' || *s == ':' ) {
*s = '/';
}
s++;
}
}
/*
===========
FS_PathCmp
Ignore case and separator char distinctions
===========
*/
int FS_PathCmp( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if (c1 >= 'a' && c1 <= 'z') {
c1 -= ('a' - 'A');
}
if (c2 >= 'a' && c2 <= 'z') {
c2 -= ('a' - 'A');
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if (c1 < c2) {
return -1; // strings not equal
}
if (c1 > c2) {
return 1;
}
} while (c1);
return 0; // strings are equal
}
/*
================
FS_SortFileList
================
*/
void FS_SortFileList(char **filelist, int numfiles) {
int i, j, k, numsortedfiles;
char **sortedlist;
sortedlist = (char **)Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ), TAG_FILESYS, qtrue );
sortedlist[0] = NULL;
numsortedfiles = 0;
for (i = 0; i < numfiles; i++) {
for (j = 0; j < numsortedfiles; j++) {
if (FS_PathCmp(filelist[i], sortedlist[j]) < 0) {
break;
}
}
for (k = numsortedfiles; k > j; k--) {
sortedlist[k] = sortedlist[k-1];
}
sortedlist[j] = filelist[i];
numsortedfiles++;
}
Com_Memcpy(filelist, sortedlist, numfiles * sizeof( *filelist ) );
Z_Free(sortedlist);
}
/*
================
FS_NewDir_f
================
*/
void FS_NewDir_f( void ) {
char *filter;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 ) {
Com_Printf( "usage: fdir <filter>\n" );
Com_Printf( "example: fdir *t1*.bsp\n");
return;
}
filter = Cmd_Argv( 1 );
Com_Printf( "---------------\n" );
dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs );
FS_SortFileList(dirnames, ndirs);
for ( i = 0; i < ndirs; i++ ) {
FS_ConvertPath(dirnames[i]);
Com_Printf( "%s\n", dirnames[i] );
}
Com_Printf( "%d files listed\n", ndirs );
FS_FreeFileList( dirnames );
}
/*
============
FS_Path_f
============
*/
void FS_Path_f( void ) {
searchpath_t *s;
int i;
Com_Printf ("Current search path:\n");
for (s = fs_searchpaths; s; s = s->next) {
if (s->pack) {
Com_Printf ("%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles);
} else {
Com_Printf ("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir );
}
}
Com_Printf( "\n" );
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o ) {
Com_Printf( "handle %i: %s\n", i, fsh[i].name );
}
}
}
/*
============
FS_TouchFile_f
The only purpose of this function is to allow game script files to copy
arbitrary files furing an "fs_copyfiles 1" run.
============
*/
void FS_TouchFile_f( void ) {
fileHandle_t f;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: touchFile <file>\n" );
return;
}
FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse );
if ( f ) {
FS_FCloseFile( f );
}
}
/*
============
FS_Which_f
============
*/
void FS_Which_f( void ) {
searchpath_t *search;
char *filename;
filename = Cmd_Argv(1);
if ( !filename[0] ) {
Com_Printf( "Usage: which <file>\n" );
return;
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
return;
}
// just wants to see if file is there
for ( search=fs_searchpaths; search; search=search->next ) {
if ( search->pack ) {
long hash = FS_HashFileName( filename, search->pack->hashSize );
// is the element a pak file?
if ( search->pack->hashTable[hash]) {
// look through all the pak file elements
pack_t* pak = search->pack;
fileInPack_t* pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
// found it!
Com_Printf( "File \"%s\" found in \"%s\"\n", filename, pak->pakFilename );
return;
}
pakFile = pakFile->next;
} while ( pakFile != NULL );
}
} else if (search->dir) {
directory_t* dir = search->dir;
char* netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename );
FILE* filep = fopen(netpath, "rb");
if ( filep ) {
fclose( filep );
char buf[MAX_OSPATH];
Com_sprintf( buf, sizeof( buf ), "%s%c%s", dir->path, PATH_SEP, dir->gamedir );
FS_ReplaceSeparators( buf );
Com_Printf( "File \"%s\" found at \"%s\"\n", filename, buf );
return;
}
}
}
Com_Printf( "File not found: \"%s\"\n", filename );
}
//===========================================================================
static int QDECL paksort( const void *a, const void *b ) {
char *aa, *bb;
aa = *(char **)a;
bb = *(char **)b;
return FS_PathCmp( aa, bb );
}
/*
================
FS_AddGameDirectory
Sets fs_gamedir, adds the directory to the head of the path,
then loads the zip headers
================
*/
#define MAX_PAKFILES 1024
static void FS_AddGameDirectory( const char *path, const char *dir ) {
searchpath_t *sp;
int i;
searchpath_t *search;
searchpath_t *thedir;
pack_t *pak;
char curpath[MAX_OSPATH + 1], *pakfile;
int numfiles;
char **pakfiles;
char *sorted[MAX_PAKFILES];
// this fixes the case where fs_basepath is the same as fs_cdpath
// which happens on full installs
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
// TODO Sys_PathCmp SDL-Port will contain this for SP as well
// Should be Sys_PathCmp(sp->dir->path, path)
if ( sp->dir && !Q_stricmp(sp->dir->path, path) && !Q_stricmp(sp->dir->gamedir, dir)) {
return; // we've already got this one
}
}
Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) );
// find all pak files in this directory
Q_strncpyz(curpath, FS_BuildOSPath(path, dir, ""), sizeof(curpath));
curpath[strlen(curpath) - 1] = '\0'; // strip the trailing slash
//
// add the directory to the search path
//
search = (struct searchpath_s *)Z_Malloc (sizeof(searchpath_t), TAG_FILESYS, qtrue);
search->dir = (directory_t *)Z_Malloc( sizeof( *search->dir ), TAG_FILESYS, qtrue );
Q_strncpyz( search->dir->path, path, sizeof( search->dir->path ) );
Q_strncpyz( search->dir->fullpath, curpath, sizeof( search->dir->fullpath ) );
Q_strncpyz( search->dir->gamedir, dir, sizeof( search->dir->gamedir ) );
search->next = fs_searchpaths;
fs_searchpaths = search;
thedir = search;
pakfiles = Sys_ListFiles( curpath, ".pk3", NULL, &numfiles, qfalse );
// sort them so that later alphabetic matches override
// earlier ones. This makes pak1.pk3 override pak0.pk3
if ( numfiles > MAX_PAKFILES ) {
numfiles = MAX_PAKFILES;
}
for ( i = 0 ; i < numfiles ; i++ ) {
sorted[i] = pakfiles[i];
}
qsort( sorted, numfiles, sizeof(char*), paksort );
for ( i = 0 ; i < numfiles ; i++ ) {
pakfile = FS_BuildOSPath( path, dir, sorted[i] );
if ( ( pak = FS_LoadZipFile( pakfile, sorted[i] ) ) == 0 )
continue;
Q_strncpyz(pak->pakPathname, curpath, sizeof(pak->pakPathname));
// store the game name for downloading
Q_strncpyz(pak->pakGamename, dir, sizeof(pak->pakGamename));
fs_packFiles += pak->numfiles;
search = (searchpath_s *)Z_Malloc (sizeof(searchpath_t), TAG_FILESYS, qtrue);
search->pack = pak;
if (fs_dirbeforepak && fs_dirbeforepak->integer && thedir)
{
searchpath_t *oldnext = thedir->next;
thedir->next = search;
while (oldnext)
{
search->next = oldnext;
search = search->next;
oldnext = oldnext->next;
}
}
else
{
search->next = fs_searchpaths;
fs_searchpaths = search;
}
}
// done
Sys_FreeFileList( pakfiles );
}
/*
================
FS_CheckDirTraversal
Check whether the string contains stuff like "../" to prevent directory traversal bugs
and return qtrue if it does.
================
*/
qboolean FS_CheckDirTraversal(const char *checkdir)
{
if(strstr(checkdir, "../") || strstr(checkdir, "..\\"))
return qtrue;
return qfalse;
}
/*
================
FS_Shutdown
Frees all resources and closes all files
================
*/
void FS_Shutdown( void ) {
searchpath_t *p, *next;
int i;
for(i = 0; i < MAX_FILE_HANDLES; i++) {
if (fsh[i].fileSize) {
FS_FCloseFile(i);
}
}
// free everything
for ( p = fs_searchpaths ; p ; p = next ) {
next = p->next;
if ( p->pack ) {
FS_FreePak( p->pack );
}
if ( p->dir ) {
Z_Free( p->dir );
}
Z_Free( p );
}
// any FS_ calls will now be an error until reinitialized
fs_searchpaths = NULL;
Cmd_RemoveCommand( "path" );
Cmd_RemoveCommand( "dir" );
Cmd_RemoveCommand( "fdir" );
Cmd_RemoveCommand( "touchFile" );
Cmd_RemoveCommand( "which" );
}
/*
================
FS_Startup
================
*/
void FS_Startup( const char *gameName ) {
const char *homePath;
Com_Printf( "----- FS_Startup -----\n" );
fs_packFiles = 0;
fs_debug = Cvar_Get( "fs_debug", "0", 0 );
fs_copyfiles = Cvar_Get( "fs_copyfiles", "0", CVAR_INIT );
fs_cdpath = Cvar_Get ("fs_cdpath", "", CVAR_INIT|CVAR_PROTECTED );
fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT|CVAR_PROTECTED );
fs_basegame = Cvar_Get ("fs_basegame", "", CVAR_INIT );
homePath = Sys_DefaultHomePath();
if (!homePath || !homePath[0]) {
homePath = fs_basepath->string;
}
fs_homepath = Cvar_Get ("fs_homepath", homePath, CVAR_INIT|CVAR_PROTECTED );
fs_gamedirvar = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
fs_dirbeforepak = Cvar_Get("fs_dirbeforepak", "0", CVAR_INIT|CVAR_PROTECTED);
// add search path elements in reverse priority order
if (fs_cdpath->string[0]) {
FS_AddGameDirectory( fs_cdpath->string, gameName );
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory( fs_basepath->string, gameName );
}
#ifdef MACOS_X
fs_apppath = Cvar_Get ("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT|CVAR_PROTECTED );
// Make MacOSX also include the base path included with the .app bundle
if (fs_apppath->string[0]) {
FS_AddGameDirectory( fs_apppath->string, gameName );
}
#endif
// fs_homepath is somewhat particular to *nix systems, only add if relevant
// NOTE: same filtering below for mods and basegame
// TODO Sys_PathCmp see previous comment for why
// !Sys_PathCmp(fs_homepath->string, fs_basepath->string)
if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string, fs_basepath->string)) {
FS_CreatePath ( fs_homepath->string );
FS_AddGameDirectory ( fs_homepath->string, gameName );
}
// check for additional base game so mods can be based upon other mods
if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) ) {
if (fs_cdpath->string[0]) {
FS_AddGameDirectory(fs_cdpath->string, fs_basegame->string);
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory(fs_basepath->string, fs_basegame->string);
}
if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string, fs_basepath->string)) {
FS_AddGameDirectory(fs_homepath->string, fs_basegame->string);
}
}
// check for additional game folder for mods
if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) ) {
if (fs_cdpath->string[0]) {
FS_AddGameDirectory(fs_cdpath->string, fs_gamedirvar->string);
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory(fs_basepath->string, fs_gamedirvar->string);
}
if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string, fs_basepath->string)) {
FS_AddGameDirectory(fs_homepath->string, fs_gamedirvar->string);
}
}
// add our commands
Cmd_AddCommand ("path", FS_Path_f);
Cmd_AddCommand ("dir", FS_Dir_f );
Cmd_AddCommand ("fdir", FS_NewDir_f );
Cmd_AddCommand ("touchFile", FS_TouchFile_f );
Cmd_AddCommand ("which", FS_Which_f );
// print the current search paths
FS_Path_f();
fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified
Com_Printf( "----------------------\n" );
Com_Printf( "%d files in pk3 files\n", fs_packFiles );
}
/*
================
FS_InitFilesystem
Called only at inital startup, not when the filesystem
is resetting due to a game change
================
*/
void FS_InitFilesystem( void ) {
// allow command line parms to override our defaults
// we have to specially handle this, because normal command
// line variable sets don't happen until after the filesystem
// has already been initialized
Com_StartupVariable( "fs_cdpath" );
Com_StartupVariable( "fs_basepath" );
Com_StartupVariable( "fs_homepath" );
Com_StartupVariable( "fs_game" );
Com_StartupVariable( "fs_copyfiles" );
Com_StartupVariable( "fs_dirbeforepak" );
#ifdef MACOS_X
Com_StartupVariable( "fs_apppath" );
#endif
const char *gamedir = Cvar_VariableString("fs_game");
bool requestbase = false;
if ( !FS_FilenameCompare( gamedir, BASEGAME ) )
requestbase = true;
if ( requestbase )
Cvar_Set2( "fs_game", "", qtrue );
// try to start up normally
FS_Startup( BASEGAME );
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
// bk001208 - SafeMode see below, FIXME?
}
Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
// bk001208 - SafeMode see below, FIXME?
}
/*
================
FS_Restart
================
*/
void FS_Restart( void ) {
// free anything we currently have loaded
FS_Shutdown();
// try to start up normally
FS_Startup( BASEGAME );
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
// this might happen when connecting to a pure server not using BASEGAME/pak0.pk3
// (for instance a TA demo server)
if (lastValidBase[0]) {
Cvar_Set("fs_basepath", lastValidBase);
Cvar_Set("fs_game", lastValidGame);
lastValidBase[0] = '\0';
lastValidGame[0] = '\0';
FS_Restart();
Com_Error( ERR_DROP, "Invalid game folder" );
return;
}
Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
}
if ( Q_stricmp(fs_gamedirvar->string, lastValidGame) ) {
// skip the jaconfig.cfg if "safe" is on the command line
if ( !Com_SafeMode() ) {
Cbuf_AddText ("exec " Q3CONFIG_NAME "\n");
}
}
Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
}
/*
=================
FS_ConditionalRestart
Restart if necessary
=================
*/
qboolean FS_ConditionalRestart( void ) {
if(fs_gamedirvar->modified) {
FS_Restart();
return qtrue;
}
return qfalse;
}
/*
========================================================================================
Handle based file calls for virtual machines
========================================================================================
*/
int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
int r;
qboolean sync;
sync = qfalse;
switch( mode ) {
case FS_READ:
r = FS_FOpenFileRead( qpath, f, qtrue );
break;
case FS_WRITE:
*f = FS_FOpenFileWrite( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
case FS_APPEND_SYNC:
sync = qtrue;
case FS_APPEND:
*f = FS_FOpenFileAppend( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
default:
Com_Error( ERR_FATAL, "FSH_FOpenFile: bad mode" );
return -1;
}
if (!f) {
return r;
}
if ( *f ) {
fsh[*f].fileSize = r;
}
fsh[*f].handleSync = sync;
return r;
}
int FS_FTell( fileHandle_t f ) {
int pos;
if (fsh[f].zipFile == qtrue) {
pos = unztell(fsh[f].handleFiles.file.z);
} else {
pos = ftell(fsh[f].handleFiles.file.o);
}
return pos;
}
void FS_Flush( fileHandle_t f ) {
fflush(fsh[f].handleFiles.file.o);
}
void FS_FilenameCompletion( const char *dir, const char *ext, qboolean stripExt, callbackFunc_t callback, qboolean allowNonPureFilesOnDisk ) {
int nfiles;
char **filenames, filename[MAX_STRING_CHARS];
filenames = FS_ListFilteredFiles( dir, ext, NULL, &nfiles );
FS_SortFileList( filenames, nfiles );
// pass all the files to callback (FindMatches)
for ( int i=0; i<nfiles; i++ ) {
FS_ConvertPath( filenames[i] );
Q_strncpyz( filename, filenames[i], MAX_STRING_CHARS );
if ( stripExt )
COM_StripExtension( filename, filename, sizeof( filename ) );
callback( filename );
}
FS_FreeFileList( filenames );
}
const char *FS_GetCurrentGameDir(bool emptybase)
{
if(fs_gamedirvar->string[0])
return fs_gamedirvar->string;
return emptybase ? "" : BASEGAME;
}
qboolean FS_WriteToTemporaryFile( const void *data, size_t dataLength, char **tempFilePath )
{
// SP doesn't need to do this.
return qfalse;
}
| ./CrossVul/dataset_final_sorted/CWE-269/cpp/bad_3234_1 |
crossvul-cpp_data_good_3234_3 | /*
===========================================================================
Copyright (C) 1999 - 2005, Id Software, Inc.
Copyright (C) 2000 - 2013, Raven Software, Inc.
Copyright (C) 2001 - 2013, Activision, Inc.
Copyright (C) 2005 - 2015, ioquake3 contributors
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
/*****************************************************************************
* name: files.cpp
*
* desc: file code
*
*****************************************************************************/
#include "qcommon/qcommon.h"
#ifndef DEDICATED
#ifndef FINAL_BUILD
#include "client/client.h"
#endif
#endif
#include <minizip/unzip.h>
#if defined(_WIN32)
#include <windows.h>
#endif
// for rmdir
#if defined (_MSC_VER)
#include <direct.h>
#else
#include <unistd.h>
#endif
/*
=============================================================================
QUAKE3 FILESYSTEM
All of Quake's data access is through a hierarchical file system, but the contents of
the file system can be transparently merged from several sources.
A "qpath" is a reference to game file data. MAX_ZPATH is 256 characters, which must include
a terminating zero. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any
references outside the quake directory system.
The "base path" is the path to the directory holding all the game directories and usually
the executable. It defaults to ".", but can be overridden with a "+set fs_basepath c:\quake3"
command line to allow code debugging in a different directory. Basepath cannot
be modified at all after startup. Any files that are created (demos, screenshots,
etc) will be created relative to the base path, so base path should usually be writable.
The "home path" is the path used for all write access. On win32 systems we have "base path"
== "home path", but on *nix systems the base installation is usually readonly, and
"home path" points to ~/.q3a or similar
The user can also install custom mods and content in "home path", so it should be searched
along with "home path" and "cd path" for game content.
The "base game" is the directory under the paths where data comes from by default, and
can be either "baseq3" or "demoq3".
The "current game" may be the same as the base game, or it may be the name of another
directory under the paths that should be searched for files before looking in the base game.
This is the basis for addons.
Clients automatically set the game directory after receiving a gamestate from a server,
so only servers need to worry about +set fs_game.
No other directories outside of the base game and current game will ever be referenced by
filesystem functions.
To save disk space and speed loading, directory trees can be collapsed into zip files.
The files use a ".pk3" extension to prevent users from unzipping them accidentally, but
otherwise the are simply normal uncompressed zip files. A game directory can have multiple
zip files of the form "pak0.pk3", "pak1.pk3", etc. Zip files are searched in decending order
from the highest number to the lowest, and will always take precedence over the filesystem.
This allows a pk3 distributed as a patch to override all existing data.
Because we will have updated executables freely available online, there is no point to
trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
should be exactly the same executables as release versions, but with different data that
automatically restricts where game media can come from to prevent add-ons from working.
File search order: when FS_FOpenFileRead gets called it will go through the fs_searchpaths
structure and stop on the first successful hit. fs_searchpaths is built with successive
calls to FS_AddGameDirectory
Additionaly, we search in several subdirectories:
current game is the current mode
base game is a variable to allow mods based on other mods
(such as baseq3 + missionpack content combination in a mod for instance)
BASEGAME is the hardcoded base game ("baseq3")
e.g. the qpath "sound/newstuff/test.wav" would be searched for in the following places:
home path + current game's zip files
home path + current game's directory
base path + current game's zip files
base path + current game's directory
cd path + current game's zip files
cd path + current game's directory
home path + base game's zip file
home path + base game's directory
base path + base game's zip file
base path + base game's directory
cd path + base game's zip file
cd path + base game's directory
home path + BASEGAME's zip file
home path + BASEGAME's directory
base path + BASEGAME's zip file
base path + BASEGAME's directory
cd path + BASEGAME's zip file
cd path + BASEGAME's directory
server download, to be written to home path + current game's directory
The filesystem can be safely shutdown and reinitialized with different
basedir / cddir / game combinations, but all other subsystems that rely on it
(sound, video) must also be forced to restart.
Because the same files are loaded by both the clip model (CM_) and renderer (TR_)
subsystems, a simple single-file caching scheme is used. The CM_ subsystems will
load the file with a request to cache. Only one file will be kept cached at a time,
so any models that are going to be referenced by both subsystems should alternate
between the CM_ load function and the ref load function.
TODO: A qpath that starts with a leading slash will always refer to the base game, even if another
game is currently active. This allows character models, skins, and sounds to be downloaded
to a common directory no matter which game is active.
How to prevent downloading zip files?
Pass pk3 file names in systeminfo, and download before FS_Restart()?
Aborting a download disconnects the client from the server.
How to mark files as downloadable? Commercial add-ons won't be downloadable.
Non-commercial downloads will want to download the entire zip file.
the game would have to be reset to actually read the zip in
Auto-update information
Path separators
Casing
separate server gamedir and client gamedir, so if the user starts
a local game after having connected to a network game, it won't stick
with the network game.
allow menu options for game selection?
Read / write config to floppy option.
Different version coexistance?
When building a pak file, make sure a q3config.cfg isn't present in it,
or configs will never get loaded from disk!
todo:
downloading (outside fs?)
game directory passing and restarting
=============================================================================
*/
#define MAX_ZPATH 256
#define MAX_SEARCH_PATHS 4096
#define MAX_FILEHASH_SIZE 1024
typedef struct fileInPack_s {
char *name; // name of the file
unsigned long pos; // file info position in zip
unsigned long len; // uncompress file size
struct fileInPack_s* next; // next file in the hash
} fileInPack_t;
typedef struct pack_s {
char pakPathname[MAX_OSPATH]; // c:\jediacademy\gamedata\base
char pakFilename[MAX_OSPATH]; // c:\jediacademy\gamedata\base\assets0.pk3
char pakBasename[MAX_OSPATH]; // assets0
char pakGamename[MAX_OSPATH]; // base
unzFile handle; // handle to zip file
int checksum; // regular checksum
int pure_checksum; // checksum for pure
int numfiles; // number of files in pk3
int referenced; // referenced file flags
int hashSize; // hash table size (power of 2)
fileInPack_t* *hashTable; // hash table
fileInPack_t* buildBuffer; // buffer with the filenames etc.
} pack_t;
typedef struct directory_s {
char path[MAX_OSPATH]; // c:\jediacademy\gamedata
char fullpath[MAX_OSPATH]; // c:\jediacademy\gamedata\base
char gamedir[MAX_OSPATH]; // base
} directory_t;
typedef struct searchpath_s {
struct searchpath_s *next;
pack_t *pack; // only one of pack / dir will be non NULL
directory_t *dir;
} searchpath_t;
static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators
static cvar_t *fs_debug;
static cvar_t *fs_homepath;
#ifdef MACOS_X
// Also search the .app bundle for .pk3 files
static cvar_t *fs_apppath;
#endif
static cvar_t *fs_basepath;
static cvar_t *fs_basegame;
static cvar_t *fs_cdpath;
static cvar_t *fs_copyfiles;
static cvar_t *fs_gamedirvar;
static cvar_t *fs_dirbeforepak; //rww - when building search path, keep directories at top and insert pk3's under them
static searchpath_t *fs_searchpaths;
static int fs_readCount; // total bytes read
static int fs_loadCount; // total files read
static int fs_packFiles = 0; // total number of files in packs
static int fs_fakeChkSum;
static int fs_checksumFeed;
typedef union qfile_gus {
FILE* o;
unzFile z;
} qfile_gut;
typedef struct qfile_us {
qfile_gut file;
qboolean unique;
} qfile_ut;
typedef struct fileHandleData_s {
qfile_ut handleFiles;
qboolean handleSync;
int fileSize;
int zipFilePos;
int zipFileLen;
qboolean zipFile;
char name[MAX_ZPATH];
} fileHandleData_t;
static fileHandleData_t fsh[MAX_FILE_HANDLES];
// TTimo - https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
// wether we did a reorder on the current search path when joining the server
static qboolean fs_reordered = qfalse;
// never load anything from pk3 files that are not present at the server when pure
static int fs_numServerPaks = 0;
static int fs_serverPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverPakNames[MAX_SEARCH_PATHS]; // pk3 names
// only used for autodownload, to make sure the client has at least
// all the pk3 files that are referenced at the server side
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS]; // pk3 names
#if defined(_WIN32)
// temporary files - store them in a circular buffer. We're pretty
// much guaranteed to not need more than 8 temp files at a time.
static int fs_temporaryFileWriteIdx = 0;
static char fs_temporaryFileNames[8][MAX_OSPATH];
#endif
// last valid game folder used
char lastValidBase[MAX_OSPATH];
char lastValidGame[MAX_OSPATH];
#ifdef FS_MISSING
FILE* missingFiles = NULL;
#endif
/* C99 defines __func__ */
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2 || _MSC_VER >= 1300
# define __func__ __FUNCTION__
# else
# define __func__ "(unknown)"
# endif
#endif
/*
==============
FS_Initialized
==============
*/
qboolean FS_Initialized( void ) {
return (qboolean)(fs_searchpaths != NULL);
}
static void FS_AssertInitialised( void ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
}
}
/*
=================
FS_PakIsPure
=================
*/
qboolean FS_PakIsPure( pack_t *pack ) {
int i;
if ( fs_numServerPaks ) {
// NOTE TTimo we are matching checksums without checking the pak names
// this means you can have the same pk3 as the server under a different name, you will still get through sv_pure validation
// (what happens when two pk3's have the same checkums? is it a likely situation?)
// also, if there's a wrong checksumed pk3 and autodownload is enabled, the checksum will be appended to the downloaded pk3 name
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
// FIXME: also use hashed file names
if ( pack->checksum == fs_serverPaks[i] ) {
return qtrue; // on the aproved list
}
}
return qfalse; // not on the pure server pak list
}
return qtrue;
}
/*
================
return a hash value for the filename
================
*/
static long FS_HashFileName( const char *fname, int hashSize ) {
int i;
long hash;
char letter;
hash = 0;
i = 0;
while (fname[i] != '\0') {
letter = tolower(fname[i]);
if (letter =='.') break; // don't include extension
if (letter =='\\') letter = '/'; // damn path names
if (letter == PATH_SEP) letter = '/'; // damn path names
hash+=(long)(letter)*(i+119);
i++;
}
hash = (hash ^ (hash >> 10) ^ (hash >> 20));
hash &= (hashSize-1);
return hash;
}
static fileHandle_t FS_HandleForFile(void) {
int i;
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o == NULL ) {
return i;
}
}
Com_Error( ERR_DROP, "FS_HandleForFile: none free" );
return 0;
}
static FILE *FS_FileForHandle( fileHandle_t f ) {
if ( f < 1 || f >= MAX_FILE_HANDLES ) {
Com_Error( ERR_DROP, "FS_FileForHandle: out of range" );
}
if (fsh[f].zipFile == qtrue) {
Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" );
}
if ( ! fsh[f].handleFiles.file.o ) {
Com_Error( ERR_DROP, "FS_FileForHandle: NULL" );
}
return fsh[f].handleFiles.file.o;
}
void FS_ForceFlush( fileHandle_t f ) {
FILE *file;
file = FS_FileForHandle(f);
setvbuf( file, NULL, _IONBF, 0 );
}
/*
================
FS_fplength
================
*/
long FS_fplength(FILE *h)
{
long pos;
long end;
pos = ftell(h);
if ( pos == EOF )
return EOF;
fseek(h, 0, SEEK_END);
end = ftell(h);
fseek(h, pos, SEEK_SET);
return end;
}
/*
================
FS_filelength
If this is called on a non-unique FILE (from a pak file),
it will return the size of the pak file, not the expected
size of the file.
================
*/
int FS_filelength( fileHandle_t f ) {
FILE *h;
h = FS_FileForHandle(f);
if(h == NULL)
return EOF;
else
return FS_fplength(h);
}
/*
====================
FS_ReplaceSeparators
Fix things up differently for win/unix/mac
====================
*/
void FS_ReplaceSeparators( char *path ) {
char *s;
qboolean lastCharWasSep = qfalse;
for ( s = path ; *s ; s++ ) {
if ( *s == '/' || *s == '\\' ) {
if ( !lastCharWasSep ) {
*s = PATH_SEP;
lastCharWasSep = qtrue;
} else {
memmove (s, s + 1, strlen (s));
}
} else {
lastCharWasSep = qfalse;
}
}
}
/*
===================
FS_BuildOSPath
Qpath may have either forward or backwards slashes
===================
*/
char *FS_BuildOSPath( const char *qpath ) {
char temp[MAX_OSPATH];
static char ospath[4][MAX_OSPATH];
static int toggle;
int nextToggle = (toggle + 1)&3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement)
toggle = nextToggle;
// Fix for filenames that are given to FS with a leading "/" (/botfiles/Foo)
if (qpath[0] == '\\' || qpath[0] == '/')
qpath++;
Com_sprintf( temp, sizeof(temp), "/base/%s", qpath );
FS_ReplaceSeparators( temp );
Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", fs_basepath->string, temp );
return ospath[toggle];
}
char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) {
char temp[MAX_OSPATH];
static char ospath[4][MAX_OSPATH];
static int toggle;
int nextToggle = (toggle + 1)&3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement)
toggle = nextToggle;
if( !game || !game[0] ) {
game = fs_gamedir;
}
Com_sprintf( temp, sizeof(temp), "/%s/%s", game, qpath );
FS_ReplaceSeparators( temp );
Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp );
return ospath[toggle];
}
/*
============
FS_CreatePath
Creates any directories needed to store the given filename
============
*/
qboolean FS_CreatePath (char *OSPath) {
char *ofs;
char path[MAX_OSPATH];
// make absolutely sure that it can't back up the path
// FIXME: is c: allowed???
if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) {
Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath );
return qtrue;
}
Q_strncpyz( path, OSPath, sizeof( path ) );
FS_ReplaceSeparators( path );
// Skip creation of the root directory as it will always be there
ofs = strchr( path, PATH_SEP );
if ( ofs ) {
ofs++;
}
for (; ofs != NULL && *ofs ; ofs++) {
if (*ofs == PATH_SEP) {
// create the directory
*ofs = 0;
if (!Sys_Mkdir (path)) {
Com_Error( ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"",
path );
}
*ofs = PATH_SEP;
}
}
return qfalse;
}
/*
=================
FS_CheckFilenameIsMutable
ERR_FATAL if trying to maniuplate a file with the platform library, or pk3 extension
=================
*/
static void FS_CheckFilenameIsMutable( const char *filename, const char *function )
{
// Check if the filename ends with the library, or pk3 extension
if( COM_CompareExtension( filename, DLL_EXT )
|| COM_CompareExtension( filename, ".pk3" ) )
{
Com_Error( ERR_FATAL, "%s: Not allowed to manipulate '%s' due "
"to %s extension", function, filename, COM_GetExtension( filename ) );
}
}
/*
=================
FS_CopyFile
Copy a fully specified file from one place to another
=================
*/
void FS_CopyFile( char *fromOSPath, char *toOSPath ) {
FILE *f;
int len;
byte *buf;
FS_CheckFilenameIsMutable( fromOSPath, __func__ );
Com_Printf( "copy %s to %s\n", fromOSPath, toOSPath );
if (strstr(fromOSPath, "journal.dat") || strstr(fromOSPath, "journaldata.dat")) {
Com_Printf( "Ignoring journal files\n");
return;
}
f = fopen( fromOSPath, "rb" );
if ( !f ) {
return;
}
fseek (f, 0, SEEK_END);
len = ftell (f);
fseek (f, 0, SEEK_SET);
if ( len == EOF )
{
fclose( f );
Com_Error( ERR_FATAL, "Bad file length in FS_CopyFile()" );
}
// we are using direct malloc instead of Z_Malloc here, so it
// probably won't work on a mac... Its only for developers anyway...
buf = (unsigned char *)malloc( len );
if (fread( buf, 1, len, f ) != (unsigned)len)
{
fclose( f );
free ( buf );
Com_Error( ERR_FATAL, "Short read in FS_Copyfiles()\n" );
}
fclose( f );
if( FS_CreatePath( toOSPath ) ) {
free ( buf );
return;
}
f = fopen( toOSPath, "wb" );
if ( !f ) {
free ( buf );
return;
}
if (fwrite( buf, 1, len, f ) != (unsigned)len)
{
fclose( f );
free ( buf );
Com_Error( ERR_FATAL, "Short write in FS_Copyfiles()\n" );
}
fclose( f );
free( buf );
}
/*
===========
FS_Remove
===========
*/
void FS_Remove( const char *osPath ) {
FS_CheckFilenameIsMutable( osPath, __func__ );
remove( osPath );
}
/*
===========
FS_HomeRemove
===========
*/
void FS_HomeRemove( const char *homePath ) {
FS_CheckFilenameIsMutable( homePath, __func__ );
remove( FS_BuildOSPath( fs_homepath->string,
fs_gamedir, homePath ) );
}
/*
===========
FS_Rmdir
Removes a directory, optionally deleting all files under it
===========
*/
void FS_Rmdir( const char *osPath, qboolean recursive ) {
FS_CheckFilenameIsMutable( osPath, __func__ );
if ( recursive ) {
int numfiles;
int i;
char **filesToRemove = Sys_ListFiles( osPath, "", NULL, &numfiles, qfalse );
for ( i = 0; i < numfiles; i++ ) {
char fileOsPath[MAX_OSPATH];
Com_sprintf( fileOsPath, sizeof( fileOsPath ), "%s/%s", osPath, filesToRemove[i] );
FS_Remove( fileOsPath );
}
FS_FreeFileList( filesToRemove );
char **directoriesToRemove = Sys_ListFiles( osPath, "/", NULL, &numfiles, qfalse );
for ( i = 0; i < numfiles; i++ ) {
if ( !Q_stricmp( directoriesToRemove[i], "." ) || !Q_stricmp( directoriesToRemove[i], ".." ) ) {
continue;
}
char directoryOsPath[MAX_OSPATH];
Com_sprintf( directoryOsPath, sizeof( directoryOsPath ), "%s/%s", osPath, directoriesToRemove[i] );
FS_Rmdir( directoryOsPath, qtrue );
}
FS_FreeFileList( directoriesToRemove );
}
rmdir( osPath );
}
/*
===========
FS_HomeRmdir
Removes a directory, optionally deleting all files under it
===========
*/
void FS_HomeRmdir( const char *homePath, qboolean recursive ) {
FS_CheckFilenameIsMutable( homePath, __func__ );
FS_Rmdir( FS_BuildOSPath( fs_homepath->string,
fs_gamedir, homePath ), recursive );
}
/*
================
FS_FileInPathExists
Tests if path and file exists
================
*/
qboolean FS_FileInPathExists(const char *testpath)
{
FILE *filep;
filep = fopen(testpath, "rb");
if(filep)
{
fclose(filep);
return qtrue;
}
return qfalse;
}
/*
================
FS_FileExists
Tests if the file exists in the current gamedir, this DOES NOT
search the paths. This is to determine if opening a file to write
(which always goes into the current gamedir) will cause any overwrites.
NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards
================
*/
qboolean FS_FileExists( const char *file )
{
return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file));
}
/*
================
FS_SV_FileExists
Tests if the file exists
================
*/
qboolean FS_SV_FileExists( const char *file )
{
char *testpath;
testpath = FS_BuildOSPath( fs_homepath->string, file, "");
testpath[strlen(testpath)-1] = '\0';
return FS_FileInPathExists(testpath);
}
/*
===========
FS_SV_FOpenFileWrite
===========
*/
fileHandle_t FS_SV_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
FS_AssertInitialised();
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileWrite: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = fopen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_SV_FOpenFileRead
search for a file somewhere below the home path, base path or cd path
we search in that order, matching FS_SV_FOpenFileRead order
===========
*/
int FS_SV_FOpenFileRead( const char *filename, fileHandle_t *fp ) {
char *ospath;
fileHandle_t f = 0;
FS_AssertInitialised();
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
S_ClearSoundBuffer();
// search homepath
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
// remove trailing slash
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o)
{
// NOTE TTimo on non *nix systems, fs_homepath == fs_basepath, might want to avoid
if (Q_stricmp(fs_homepath->string,fs_basepath->string))
{
// search basepath
ospath = FS_BuildOSPath( fs_basepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
if ( !fsh[f].handleFiles.file.o )
{
f = 0;
}
}
if (!fsh[f].handleFiles.file.o)
{
// search cd path
ospath = FS_BuildOSPath( fs_cdpath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if (fs_debug->integer)
{
Com_Printf( "FS_SV_FOpenFileRead (fs_cdpath) : %s\n", ospath );
}
fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
fsh[f].handleSync = qfalse;
if ( !fsh[f].handleFiles.file.o )
{
f = 0;
}
}
*fp = f;
if (f) {
return FS_filelength(f);
}
return 0;
}
/*
===========
FS_SV_Rename
===========
*/
void FS_SV_Rename( const char *from, const char *to, qboolean safe ) {
char *from_ospath, *to_ospath;
FS_AssertInitialised();
// don't let sound stutter
S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, from, "" );
to_ospath = FS_BuildOSPath( fs_homepath->string, to, "" );
from_ospath[strlen(from_ospath)-1] = '\0';
to_ospath[strlen(to_ospath)-1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath );
}
if ( safe ) {
FS_CheckFilenameIsMutable( to_ospath, __func__ );
}
if (rename( from_ospath, to_ospath )) {
// Failed, try copying it and deleting the original
FS_CopyFile ( from_ospath, to_ospath );
FS_Remove ( from_ospath );
}
}
/*
===========
FS_Rename
===========
*/
void FS_Rename( const char *from, const char *to ) {
char *from_ospath, *to_ospath;
FS_AssertInitialised();
// don't let sound stutter
S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from );
to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to );
if ( fs_debug->integer ) {
Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath );
}
FS_CheckFilenameIsMutable( to_ospath, __func__ );
if (rename( from_ospath, to_ospath )) {
// Failed, try copying it and deleting the original
FS_CopyFile ( from_ospath, to_ospath );
FS_Remove ( from_ospath );
}
}
/*
===========
FS_FCloseFile
Close a file.
There are three cases handled:
* normal file: closed with fclose.
* file in pak3 archive: subfile is closed with unzCloseCurrentFile, but the
minizip handle to the pak3 remains open.
* file in pak3 archive, opened with "unique" flag: This file did not use
the system minizip handle to the pak3 file, but its own dedicated one.
The dedicated handle is closed with unzClose.
===========
*/
void FS_FCloseFile( fileHandle_t f ) {
FS_AssertInitialised();
if (fsh[f].zipFile == qtrue) {
unzCloseCurrentFile( fsh[f].handleFiles.file.z );
if ( fsh[f].handleFiles.unique ) {
unzClose( fsh[f].handleFiles.file.z );
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
return;
}
// we didn't find it as a pak, so close it as a unique file
if (fsh[f].handleFiles.file.o) {
fclose (fsh[f].handleFiles.file.o);
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
}
/*
===========
FS_FOpenFileWrite
===========
*/
fileHandle_t FS_FOpenFileWrite( const char *filename, qboolean safe ) {
char *ospath;
fileHandle_t f;
FS_AssertInitialised();
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileWrite: %s\n", ospath );
}
if ( safe ) {
FS_CheckFilenameIsMutable( ospath, __func__ );
}
if( FS_CreatePath( ospath ) ) {
return 0;
}
// enabling the following line causes a recursive function call loop
// when running with +set logfile 1 +set developer 1
//Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = fopen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_FOpenFileAppend
===========
*/
fileHandle_t FS_FOpenFileAppend( const char *filename ) {
char *ospath;
fileHandle_t f;
FS_AssertInitialised();
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileAppend: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
fsh[f].handleFiles.file.o = fopen( ospath, "ab" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_FilenameCompare
Ignore case and separator char distinctions
===========
*/
qboolean FS_FilenameCompare( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if (c1 >= 'a' && c1 <= 'z') {
c1 -= ('a' - 'A');
}
if (c2 >= 'a' && c2 <= 'z') {
c2 -= ('a' - 'A');
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if (c1 != c2) {
return qtrue; // strings not equal
}
} while (c1);
return qfalse; // strings are equal
}
/*
===========
FS_IsExt
Return qtrue if ext matches file extension filename
===========
*/
qboolean FS_IsExt(const char *filename, const char *ext, int namelen)
{
int extlen;
extlen = strlen(ext);
if(extlen > namelen)
return qfalse;
filename += namelen - extlen;
return (qboolean)!Q_stricmp(filename, ext);
}
/*
===========
FS_IsDemoExt
Return qtrue if filename has a demo extension
===========
*/
#define DEMO_EXTENSION "dm_"
qboolean FS_IsDemoExt(const char *filename, int namelen)
{
const char *ext_test;
ext_test = strrchr(filename, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMO_EXTENSION, ARRAY_LEN(DEMO_EXTENSION) - 1))
{
int protocol = atoi(ext_test + ARRAY_LEN(DEMO_EXTENSION));
if(protocol == PROTOCOL_VERSION)
return qtrue;
}
return qfalse;
}
#ifdef _WIN32
bool Sys_GetFileTime(LPCSTR psFileName, FILETIME &ft)
{
bool bSuccess = false;
HANDLE hFile = INVALID_HANDLE_VALUE;
hFile = CreateFile( psFileName, // LPCTSTR lpFileName, // pointer to name of the file
GENERIC_READ, // DWORD dwDesiredAccess, // access (read-write) mode
FILE_SHARE_READ, // DWORD dwShareMode, // share mode
NULL, // LPSECURITY_ATTRIBUTES lpSecurityAttributes, // pointer to security attributes
OPEN_EXISTING, // DWORD dwCreationDisposition, // how to create
FILE_FLAG_NO_BUFFERING,// DWORD dwFlagsAndAttributes, // file attributes
NULL // HANDLE hTemplateFile // handle to file with attributes to
);
if (hFile != INVALID_HANDLE_VALUE)
{
if (GetFileTime(hFile, // handle to file
NULL, // LPFILETIME lpCreationTime
NULL, // LPFILETIME lpLastAccessTime
&ft // LPFILETIME lpLastWriteTime
)
)
{
bSuccess = true;
}
CloseHandle(hFile);
}
return bSuccess;
}
bool Sys_FileOutOfDate( LPCSTR psFinalFileName /* dest */, LPCSTR psDataFileName /* src */ )
{
FILETIME ftFinalFile, ftDataFile;
if (Sys_GetFileTime(psFinalFileName, ftFinalFile) && Sys_GetFileTime(psDataFileName, ftDataFile))
{
// timer res only accurate to within 2 seconds on FAT, so can't do exact compare...
//
//LONG l = CompareFileTime( &ftFinalFile, &ftDataFile );
if ( (fabs((double)(ftFinalFile.dwLowDateTime - ftDataFile.dwLowDateTime)) <= 20000000 ) &&
ftFinalFile.dwHighDateTime == ftDataFile.dwHighDateTime
)
{
return false; // file not out of date, ie use it.
}
return true; // flag return code to copy over a replacement version of this file
}
// extra error check, report as suspicious if you find a file locally but not out on the net.,.
//
if (com_developer->integer)
{
if (!Sys_GetFileTime(psDataFileName, ftDataFile))
{
Com_Printf( "Sys_FileOutOfDate: reading %s but it's not on the net!\n", psFinalFileName);
}
}
return false;
}
#endif // _WIN32
bool FS_FileCacheable(const char* const filename)
{
extern cvar_t *com_buildScript;
if (com_buildScript && com_buildScript->integer)
{
return true;
}
return( strchr(filename, '/') != 0 );
}
/*
===========
FS_FOpenFileRead
Finds the file in the search path.
Returns filesize and an open FILE pointer.
Used for streaming data out of either a
separate file or a ZIP file.
===========
*/
extern qboolean com_fullyInitialized;
long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean uniqueFILE ) {
searchpath_t *search;
char *netpath;
pack_t *pak;
fileInPack_t *pakFile;
directory_t *dir;
long hash;
//unz_s *zfi;
//void *temp;
int l;
bool isUserConfig = false;
hash = 0;
FS_AssertInitialised();
if ( file == NULL ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'file' parameter passed\n" );
}
if ( !filename ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" );
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
*file = 0;
return -1;
}
// make sure the q3key file is only readable by the quake3.exe at initialization
// any other time the key should only be accessed in memory using the provided functions
if( com_fullyInitialized && strstr( filename, "q3key" ) ) {
*file = 0;
return -1;
}
isUserConfig = !Q_stricmp( filename, "autoexec.cfg" ) || !Q_stricmp( filename, Q3CONFIG_CFG );
//
// search through the path, one element at a time
//
*file = FS_HandleForFile();
fsh[*file].handleFiles.unique = uniqueFILE;
// this new bool is in for an optimisation, if you (eg) opened a BSP file under fs_copyfiles==2,
// then it triggered a copy operation to update your local HD version, then this will re-open the
// file handle on your local version, not the net build. This uses a bit more CPU to re-do the loop
// logic, but should read faster than accessing the net version a second time.
//
qboolean bFasterToReOpenUsingNewLocalFile = qfalse;
do
{
bFasterToReOpenUsingNewLocalFile = qfalse;
for ( search = fs_searchpaths ; search ; search = search->next ) {
//
if ( search->pack ) {
hash = FS_HashFileName(filename, search->pack->hashSize);
}
// is the element a pak file?
if ( search->pack && search->pack->hashTable[hash] ) {
// disregard if it doesn't match one of the allowed pure pak files
if ( !FS_PakIsPure(search->pack) ) {
continue;
}
// autoexec.cfg and openjk.cfg can only be loaded outside of pk3 files.
if ( isUserConfig ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
// found it!
// mark the pak as having been referenced and mark specifics on cgame and ui
// shaders, txt, arena files by themselves do not count as a reference as
// these are loaded from all pk3s
// from every pk3 file..
// The x86.dll suffixes are needed in order for sv_pure to continue to
// work on non-x86/windows systems...
l = strlen( filename );
if ( !(pak->referenced & FS_GENERAL_REF)) {
if( !FS_IsExt(filename, ".shader", l) &&
!FS_IsExt(filename, ".txt", l) &&
!FS_IsExt(filename, ".str", l) &&
!FS_IsExt(filename, ".cfg", l) &&
!FS_IsExt(filename, ".config", l) &&
!FS_IsExt(filename, ".bot", l) &&
!FS_IsExt(filename, ".arena", l) &&
!FS_IsExt(filename, ".menu", l) &&
!FS_IsExt(filename, ".fcf", l) &&
Q_stricmp(filename, "jampgamex86.dll") != 0 &&
//Q_stricmp(filename, "vm/qagame.qvm") != 0 &&
!strstr(filename, "levelshots"))
{
pak->referenced |= FS_GENERAL_REF;
}
}
if (!(pak->referenced & FS_CGAME_REF))
{
if ( Q_stricmp( filename, "cgame.qvm" ) == 0 ||
Q_stricmp( filename, "cgamex86.dll" ) == 0 )
{
pak->referenced |= FS_CGAME_REF;
}
}
if (!(pak->referenced & FS_UI_REF))
{
if ( Q_stricmp( filename, "ui.qvm" ) == 0 ||
Q_stricmp( filename, "uix86.dll" ) == 0 )
{
pak->referenced |= FS_UI_REF;
}
}
if ( uniqueFILE ) {
// open a new file on the pakfile
fsh[*file].handleFiles.file.z = unzOpen (pak->pakFilename);
if (fsh[*file].handleFiles.file.z == NULL) {
Com_Error (ERR_FATAL, "Couldn't open %s", pak->pakFilename);
}
} else {
fsh[*file].handleFiles.file.z = pak->handle;
}
Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) );
fsh[*file].zipFile = qtrue;
// set the file position in the zip file (also sets the current file info)
unzSetOffset(fsh[*file].handleFiles.file.z, pakFile->pos);
// open the file in the zip
unzOpenCurrentFile(fsh[*file].handleFiles.file.z);
#if 0
zfi = (unz_s *)fsh[*file].handleFiles.file.z;
// in case the file was new
temp = zfi->filestream;
// set the file position in the zip file (also sets the current file info)
unzSetOffset(pak->handle, pakFile->pos);
// copy the file info into the unzip structure
Com_Memcpy( zfi, pak->handle, sizeof(unz_s) );
// we copy this back into the structure
zfi->filestream = temp;
// open the file in the zip
unzOpenCurrentFile( fsh[*file].handleFiles.file.z );
#endif
fsh[*file].zipFilePos = pakFile->pos;
fsh[*file].zipFileLen = pakFile->len;
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileRead: %s (found in '%s')\n",
filename, pak->pakFilename );
}
#ifndef DEDICATED
#ifndef FINAL_BUILD
// Check for unprecached files when in game but not in the menus
if((cls.state == CA_ACTIVE) && !(Key_GetCatcher( ) & KEYCATCH_UI))
{
Com_Printf(S_COLOR_YELLOW "WARNING: File %s not precached\n", filename);
}
#endif
#endif // DEDICATED
return pakFile->len;
}
pakFile = pakFile->next;
} while(pakFile != NULL);
} else if ( search->dir ) {
// check a file in the directory tree
// if we are running restricted, the only files we
// will allow to come from the directory are .cfg files
l = strlen( filename );
// FIXME TTimo I'm not sure about the fs_numServerPaks test
// if you are using FS_ReadFile to find out if a file exists,
// this test can make the search fail although the file is in the directory
// I had the problem on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8
// turned out I used FS_FileExists instead
if ( fs_numServerPaks ) {
if ( !FS_IsExt( filename, ".cfg", l ) && // for config files
!FS_IsExt( filename, ".fcf", l ) && // force configuration files
!FS_IsExt( filename, ".menu", l ) && // menu files
!FS_IsExt( filename, ".game", l ) && // menu files
!FS_IsExt( filename, ".dat", l ) && // for journal files
!FS_IsDemoExt( filename, l ) ) { // demos
continue;
}
}
dir = search->dir;
netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename );
fsh[*file].handleFiles.file.o = fopen (netpath, "rb");
if ( !fsh[*file].handleFiles.file.o ) {
continue;
}
if ( !FS_IsExt( filename, ".cfg", l ) && // for config files
!FS_IsExt( filename, ".fcf", l ) && // force configuration files
!FS_IsExt( filename, ".menu", l ) && // menu files
!FS_IsExt( filename, ".game", l ) && // menu files
!FS_IsExt( filename, ".dat", l ) && // for journal files
!FS_IsDemoExt( filename, l ) ) { // demos
fs_fakeChkSum = Q_flrand(0.0f, 1.0f);
}
#ifdef _WIN32
// if running with fs_copyfiles 2, and search path == local, then we need to fail to open
// if the time/date stamp != the network version (so it'll loop round again and use the network path,
// which comes later in the search order)
//
if ( fs_copyfiles->integer == 2 && fs_cdpath->string[0] && !Q_stricmp( dir->path, fs_basepath->string )
&& FS_FileCacheable(filename) )
{
if ( Sys_FileOutOfDate( netpath, FS_BuildOSPath( fs_cdpath->string, dir->gamedir, filename ) ))
{
fclose(fsh[*file].handleFiles.file.o);
fsh[*file].handleFiles.file.o = 0;
continue; //carry on to find the cdpath version.
}
}
#endif
Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) );
fsh[*file].zipFile = qfalse;
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename,
dir->path, PATH_SEP, dir->gamedir );
}
#ifdef _WIN32
// if we are getting it from the cdpath, optionally copy it
// to the basepath
if ( fs_copyfiles->integer && !Q_stricmp( dir->path, fs_cdpath->string ) ) {
char *copypath;
copypath = FS_BuildOSPath( fs_basepath->string, dir->gamedir, filename );
switch ( fs_copyfiles->integer )
{
default:
case 1:
{
FS_CopyFile( netpath, copypath );
}
break;
case 2:
{
if (FS_FileCacheable(filename) )
{
// maybe change this to Com_DPrintf? On the other hand...
//
Com_Printf( "fs_copyfiles(2), Copying: %s to %s\n", netpath, copypath );
FS_CreatePath( copypath );
bool bOk = true;
if (!CopyFile( netpath, copypath, FALSE ))
{
DWORD dwAttrs = GetFileAttributes(copypath);
SetFileAttributes(copypath, dwAttrs & ~FILE_ATTRIBUTE_READONLY);
bOk = !!CopyFile( netpath, copypath, FALSE );
}
if (bOk)
{
// clear this handle and setup for re-opening of the new local copy...
//
bFasterToReOpenUsingNewLocalFile = qtrue;
fclose(fsh[*file].handleFiles.file.o);
fsh[*file].handleFiles.file.o = NULL;
}
}
}
break;
}
}
#endif
if (bFasterToReOpenUsingNewLocalFile)
{
break; // and re-read the local copy, not the net version
}
#ifndef DEDICATED
#ifndef FINAL_BUILD
// Check for unprecached files when in game but not in the menus
if((cls.state == CA_ACTIVE) && !(Key_GetCatcher( ) & KEYCATCH_UI))
{
Com_Printf(S_COLOR_YELLOW "WARNING: File %s not precached\n", filename);
}
#endif
#endif // dedicated
return FS_fplength(fsh[*file].handleFiles.file.o);
}
}
}
while ( bFasterToReOpenUsingNewLocalFile );
Com_DPrintf ("Can't find %s\n", filename);
#ifdef FS_MISSING
if (missingFiles) {
fprintf(missingFiles, "%s\n", filename);
}
#endif
*file = 0;
return -1;
}
// This is a bit of a hack but it is used for other OS'/arch to still be acceptable with pure servers.
// Intentionally looking for x86.dll because this is all that exists in pk3s.
qboolean FS_FindPureDLL(const char *name)
{
char dllName[MAX_OSPATH];
fileHandle_t h;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
if ( !Cvar_VariableValue( "sv_pure" ) )
return qtrue;
Com_sprintf(dllName, sizeof(dllName), "%sx86.dll", name);
if(FS_FOpenFileRead(dllName, &h, qtrue) > 0)
{
FS_FCloseFile( h );
return qtrue;
}
return qfalse;
}
/*
=================
FS_Read
Properly handles partial reads
=================
*/
int FS_Read( void *buffer, int len, fileHandle_t f ) {
int block, remaining;
int read;
byte *buf;
int tries;
FS_AssertInitialised();
if ( !f ) {
return 0;
}
buf = (byte *)buffer;
fs_readCount += len;
if (fsh[f].zipFile == qfalse) {
remaining = len;
tries = 0;
while (remaining) {
block = remaining;
read = fread (buf, 1, block, fsh[f].handleFiles.file.o);
if (read == 0) {
// we might have been trying to read from a CD, which
// sometimes returns a 0 read on windows
if (!tries) {
tries = 1;
} else {
return len-remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read");
}
}
if (read == -1) {
Com_Error (ERR_FATAL, "FS_Read: -1 bytes read");
}
remaining -= read;
buf += read;
}
return len;
} else {
return unzReadCurrentFile(fsh[f].handleFiles.file.z, buffer, len);
}
}
/*
=================
FS_Write
Properly handles partial writes
=================
*/
int FS_Write( const void *buffer, int len, fileHandle_t h ) {
int block, remaining;
int written;
byte *buf;
int tries;
FILE *f;
FS_AssertInitialised();
if ( !h ) {
return 0;
}
f = FS_FileForHandle(h);
buf = (byte *)buffer;
remaining = len;
tries = 0;
while (remaining) {
block = remaining;
written = fwrite (buf, 1, block, f);
if (written == 0) {
if (!tries) {
tries = 1;
} else {
Com_Printf( "FS_Write: 0 bytes written\n" );
return 0;
}
}
if (written == -1) {
Com_Printf( "FS_Write: -1 bytes written\n" );
return 0;
}
remaining -= written;
buf += written;
}
if ( fsh[h].handleSync ) {
fflush( f );
}
return len;
}
void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start (argptr,fmt);
Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
va_end (argptr);
FS_Write(msg, strlen(msg), h);
}
#define PK3_SEEK_BUFFER_SIZE 65536
/*
=================
FS_Seek
=================
*/
int FS_Seek( fileHandle_t f, long offset, int origin ) {
int _origin;
FS_AssertInitialised();
if (fsh[f].zipFile == qtrue) {
//FIXME: this is really, really crappy
//(but better than what was here before)
byte buffer[PK3_SEEK_BUFFER_SIZE];
int remainder;
int currentPosition = FS_FTell( f );
// change negative offsets into FS_SEEK_SET
if ( offset < 0 ) {
switch( origin ) {
case FS_SEEK_END:
remainder = fsh[f].zipFileLen + offset;
break;
case FS_SEEK_CUR:
remainder = currentPosition + offset;
break;
case FS_SEEK_SET:
default:
remainder = 0;
break;
}
if ( remainder < 0 ) {
remainder = 0;
}
origin = FS_SEEK_SET;
} else {
if ( origin == FS_SEEK_END ) {
remainder = fsh[f].zipFileLen - currentPosition + offset;
} else {
remainder = offset;
}
}
switch( origin ) {
case FS_SEEK_SET:
if ( remainder == currentPosition ) {
return offset;
}
unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
unzOpenCurrentFile(fsh[f].handleFiles.file.z);
//fallthrough
case FS_SEEK_END:
case FS_SEEK_CUR:
while( remainder > PK3_SEEK_BUFFER_SIZE ) {
FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f );
remainder -= PK3_SEEK_BUFFER_SIZE;
}
FS_Read( buffer, remainder, f );
return offset;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
return -1;
}
} else {
FILE *file;
file = FS_FileForHandle(f);
switch( origin ) {
case FS_SEEK_CUR:
_origin = SEEK_CUR;
break;
case FS_SEEK_END:
_origin = SEEK_END;
break;
case FS_SEEK_SET:
_origin = SEEK_SET;
break;
default:
_origin = SEEK_CUR;
Com_Error( ERR_FATAL, "Bad origin in FS_Seek\n" );
break;
}
return fseek( file, offset, _origin );
}
}
/*
======================================================================================
CONVENIENCE FUNCTIONS FOR ENTIRE FILES
======================================================================================
*/
int FS_FileIsInPAK(const char *filename, int *pChecksum ) {
searchpath_t *search;
pack_t *pak;
fileInPack_t *pakFile;
long hash = 0;
FS_AssertInitialised();
if ( !filename ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" );
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
return -1;
}
//
// search through the path, one element at a time
//
for ( search = fs_searchpaths ; search ; search = search->next ) {
//
if (search->pack) {
hash = FS_HashFileName(filename, search->pack->hashSize);
}
// is the element a pak file?
if ( search->pack && search->pack->hashTable[hash] ) {
// disregard if it doesn't match one of the allowed pure pak files
if ( !FS_PakIsPure(search->pack) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
if (pChecksum) {
*pChecksum = pak->pure_checksum;
}
return 1;
}
pakFile = pakFile->next;
} while(pakFile != NULL);
}
}
return -1;
}
/*
============
FS_ReadFile
Filename are relative to the quake search path
a null buffer will just return the file length without loading
============
*/
long FS_ReadFile( const char *qpath, void **buffer ) {
fileHandle_t h;
byte* buf;
qboolean isConfig;
long len;
FS_AssertInitialised();
if ( !qpath || !qpath[0] ) {
Com_Error( ERR_FATAL, "FS_ReadFile with empty name\n" );
}
buf = NULL; // quiet compiler warning
// if this is a .cfg file and we are playing back a journal, read
// it from the journal file
if ( strstr( qpath, ".cfg" ) ) {
isConfig = qtrue;
if ( com_journal && com_journal->integer == 2 ) {
int r;
Com_DPrintf( "Loading %s from journal file.\n", qpath );
r = FS_Read( &len, sizeof( len ), com_journalDataFile );
if ( r != sizeof( len ) ) {
if (buffer != NULL) *buffer = NULL;
return -1;
}
// if the file didn't exist when the journal was created
if (!len) {
if (buffer == NULL) {
return 1; // hack for old journal files
}
*buffer = NULL;
return -1;
}
if (buffer == NULL) {
return len;
}
buf = (unsigned char *)Hunk_AllocateTempMemory(len+1);
*buffer = buf;
r = FS_Read( buf, len, com_journalDataFile );
if ( r != len ) {
Com_Error( ERR_FATAL, "Read from journalDataFile failed" );
}
fs_loadCount++;
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
return len;
}
} else {
isConfig = qfalse;
}
// look for it in the filesystem or pack files
len = FS_FOpenFileRead( qpath, &h, qfalse );
if ( h == 0 ) {
if ( buffer ) {
*buffer = NULL;
}
// if we are journalling and it is a config file, write a zero to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing zero for %s to journal file.\n", qpath );
len = 0;
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return -1;
}
if ( !buffer ) {
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing len for %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
FS_FCloseFile( h);
return len;
}
fs_loadCount++;
buf = (byte*)Z_Malloc( len+1, TAG_FILESYS, qfalse);
buf[len]='\0'; // because we're not calling Z_Malloc with optional trailing 'bZeroIt' bool
*buffer = buf;
// Z_Label(buf, qpath);
FS_Read (buf, len, h);
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
FS_FCloseFile( h );
// if we are journalling and it is a config file, write it to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Write( buf, len, com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return len;
}
/*
=============
FS_FreeFile
=============
*/
void FS_FreeFile( void *buffer ) {
FS_AssertInitialised();
if ( !buffer ) {
Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" );
}
Z_Free( buffer );
}
/*
============
FS_WriteFile
Filename are reletive to the quake search path
============
*/
void FS_WriteFile( const char *qpath, const void *buffer, int size ) {
fileHandle_t f;
FS_AssertInitialised();
if ( !qpath || !buffer ) {
Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" );
}
f = FS_FOpenFileWrite( qpath );
if ( !f ) {
Com_Printf( "Failed to open %s\n", qpath );
return;
}
FS_Write( buffer, size, f );
FS_FCloseFile( f );
}
/*
==========================================================================
ZIP FILE LOADING
==========================================================================
*/
/*
=================
FS_LoadZipFile
Creates a new pak_t in the search chain for the contents
of a zip file.
=================
*/
static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename )
{
fileInPack_t *buildBuffer;
pack_t *pack;
unzFile uf;
int err;
unz_global_info gi;
char filename_inzip[MAX_ZPATH];
unz_file_info file_info;
int len;
size_t i;
long hash;
int fs_numHeaderLongs;
int *fs_headerLongs;
char *namePtr;
fs_numHeaderLongs = 0;
uf = unzOpen(zipfile);
err = unzGetGlobalInfo (uf,&gi);
if (err != UNZ_OK)
return NULL;
len = 0;
unzGoToFirstFile(uf);
for (i = 0; i < gi.number_entry; i++)
{
err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
if (err != UNZ_OK) {
break;
}
len += strlen(filename_inzip) + 1;
unzGoToNextFile(uf);
}
buildBuffer = (struct fileInPack_s *)Z_Malloc( (gi.number_entry * sizeof( fileInPack_t )) + len, TAG_FILESYS, qtrue );
namePtr = ((char *) buildBuffer) + gi.number_entry * sizeof( fileInPack_t );
fs_headerLongs = (int *)Z_Malloc( ( gi.number_entry + 1 ) * sizeof(int), TAG_FILESYS, qtrue );
fs_headerLongs[ fs_numHeaderLongs++ ] = LittleLong( fs_checksumFeed );
// get the hash table size from the number of files in the zip
// because lots of custom pk3 files have less than 32 or 64 files
for (i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1) {
if (i > gi.number_entry) {
break;
}
}
pack = (pack_t *)Z_Malloc( sizeof( pack_t ) + i * sizeof(fileInPack_t *), TAG_FILESYS, qtrue );
pack->hashSize = i;
pack->hashTable = (fileInPack_t **) (((char *) pack) + sizeof( pack_t ));
for(int j = 0; j < pack->hashSize; j++) {
pack->hashTable[j] = NULL;
}
Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) );
Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) );
// strip .pk3 if needed
if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) {
pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0;
}
pack->handle = uf;
pack->numfiles = gi.number_entry;
unzGoToFirstFile(uf);
for (i = 0; i < gi.number_entry; i++)
{
err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
if (err != UNZ_OK) {
break;
}
if (file_info.uncompressed_size > 0) {
fs_headerLongs[fs_numHeaderLongs++] = LittleLong(file_info.crc);
}
Q_strlwr( filename_inzip );
hash = FS_HashFileName(filename_inzip, pack->hashSize);
buildBuffer[i].name = namePtr;
strcpy( buildBuffer[i].name, filename_inzip );
namePtr += strlen(filename_inzip) + 1;
// store the file position in the zip
buildBuffer[i].pos = unzGetOffset(uf);
buildBuffer[i].len = file_info.uncompressed_size;
buildBuffer[i].next = pack->hashTable[hash];
pack->hashTable[hash] = &buildBuffer[i];
unzGoToNextFile(uf);
}
pack->checksum = Com_BlockChecksum( &fs_headerLongs[ 1 ], sizeof(*fs_headerLongs) * ( fs_numHeaderLongs - 1 ) );
pack->pure_checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs );
pack->checksum = LittleLong( pack->checksum );
pack->pure_checksum = LittleLong( pack->pure_checksum );
Z_Free(fs_headerLongs);
pack->buildBuffer = buildBuffer;
return pack;
}
/*
=================
FS_FreePak
Frees a pak structure and releases all associated resources
=================
*/
void FS_FreePak(pack_t *thepak)
{
unzClose(thepak->handle);
Z_Free(thepak->buildBuffer);
Z_Free(thepak);
}
/*
=================
FS_GetZipChecksum
Compares whether the given pak file matches a referenced checksum
=================
*/
qboolean FS_CompareZipChecksum(const char *zipfile)
{
pack_t *thepak;
int index, checksum;
thepak = FS_LoadZipFile(zipfile, "");
if(!thepak)
return qfalse;
checksum = thepak->checksum;
FS_FreePak(thepak);
for(index = 0; index < fs_numServerReferencedPaks; index++)
{
if(checksum == fs_serverReferencedPaks[index])
return qtrue;
}
return qfalse;
}
/*
=================================================================================
DIRECTORY SCANNING FUNCTIONS
=================================================================================
*/
#define MAX_FOUND_FILES 0x1000
static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) {
int len, at, newdep;
newdep = 0;
zpath[0] = 0;
len = 0;
at = 0;
while(zname[at] != 0)
{
if (zname[at]=='/' || zname[at]=='\\') {
len = at;
newdep++;
}
at++;
}
strcpy(zpath, zname);
zpath[len] = 0;
*depth = newdep;
return len;
}
/*
==================
FS_AddFileToList
==================
*/
static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) {
int i;
if ( nfiles == MAX_FOUND_FILES - 1 ) {
return nfiles;
}
for ( i = 0 ; i < nfiles ; i++ ) {
if ( !Q_stricmp( name, list[i] ) ) {
return nfiles; // allready in list
}
}
list[nfiles] = CopyString( name );
nfiles++;
return nfiles;
}
/*
===============
FS_ListFilteredFiles
Returns a uniqued list of files that match the given criteria
from all search paths
===============
*/
char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles ) {
int nfiles;
char **listCopy;
char *list[MAX_FOUND_FILES];
searchpath_t *search;
int i;
int pathLength;
int extensionLength;
int length, pathDepth, temp;
pack_t *pak;
fileInPack_t *buildBuffer;
char zpath[MAX_ZPATH];
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
}
if ( !path ) {
*numfiles = 0;
return NULL;
}
if ( !extension ) {
extension = "";
}
pathLength = strlen( path );
if ( path[pathLength-1] == '\\' || path[pathLength-1] == '/' ) {
pathLength--;
}
extensionLength = strlen( extension );
nfiles = 0;
FS_ReturnPath(path, zpath, &pathDepth);
//
// search through the path, one element at a time, adding to list
//
for (search = fs_searchpaths ; search ; search = search->next) {
// is the element a pak file?
if (search->pack) {
//ZOID: If we are pure, don't search for files on paks that
// aren't on the pure list
if ( !FS_PakIsPure(search->pack) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
buildBuffer = pak->buildBuffer;
for (i = 0; i < pak->numfiles; i++) {
char *name;
int zpathLen, depth;
// check for directory match
name = buildBuffer[i].name;
//
if (filter) {
// case insensitive
if (!Com_FilterPath( filter, name, qfalse ))
continue;
// unique the match
nfiles = FS_AddFileToList( name, list, nfiles );
}
else {
zpathLen = FS_ReturnPath(name, zpath, &depth);
if ( (depth-pathDepth)>2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) {
continue;
}
// check for extension match
length = strlen( name );
if ( length < extensionLength ) {
continue;
}
if ( Q_stricmp( name + length - extensionLength, extension ) ) {
continue;
}
// unique the match
temp = pathLength;
if (pathLength) {
temp++; // include the '/'
}
nfiles = FS_AddFileToList( name + temp, list, nfiles );
}
}
} else if (search->dir) { // scan for files in the filesystem
char *netpath;
int numSysFiles;
char **sysFiles;
char *name;
// don't scan directories for files if we are pure or restricted
if ( fs_numServerPaks &&
(!extension || Q_stricmp(extension, "fcf")) )
{
//rww - allow scanning for fcf files outside of pak even if pure
continue;
}
else
{
netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path );
sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse );
for ( i = 0 ; i < numSysFiles ; i++ ) {
// unique the match
name = sysFiles[i];
nfiles = FS_AddFileToList( name, list, nfiles );
}
Sys_FreeFileList( sysFiles );
}
}
}
// return a copy of the list
*numfiles = nfiles;
if ( !nfiles ) {
return NULL;
}
listCopy = (char **)Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ), TAG_FILESYS );
for ( i = 0 ; i < nfiles ; i++ ) {
listCopy[i] = list[i];
}
listCopy[i] = NULL;
return listCopy;
}
/*
=================
FS_ListFiles
=================
*/
char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) {
return FS_ListFilteredFiles( path, extension, NULL, numfiles );
}
/*
=================
FS_FreeFileList
=================
*/
void FS_FreeFileList( char **fileList ) {
//rwwRMG - changed to fileList to not conflict with list type
int i;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
}
if ( !fileList ) {
return;
}
for ( i = 0 ; fileList[i] ; i++ ) {
Z_Free( fileList[i] );
}
Z_Free( fileList );
}
/*
================
FS_GetFileList
================
*/
int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
int nFiles, i, nTotal, nLen;
char **pFiles = NULL;
*listbuf = 0;
nFiles = 0;
nTotal = 0;
if (Q_stricmp(path, "$modlist") == 0) {
return FS_GetModList(listbuf, bufsize);
}
pFiles = FS_ListFiles(path, extension, &nFiles);
for (i =0; i < nFiles; i++) {
nLen = strlen(pFiles[i]) + 1;
if (nTotal + nLen + 1 < bufsize) {
strcpy(listbuf, pFiles[i]);
listbuf += nLen;
nTotal += nLen;
}
else {
nFiles = i;
break;
}
}
FS_FreeFileList(pFiles);
return nFiles;
}
/*
=======================
Sys_ConcatenateFileLists
mkv: Naive implementation. Concatenates three lists into a
new list, and frees the old lists from the heap.
bk001129 - from cvs1.17 (mkv)
FIXME TTimo those two should move to common.c next to Sys_ListFiles
=======================
*/
static unsigned int Sys_CountFileList(char **fileList)
{
int i = 0;
if (fileList)
{
while (*fileList)
{
fileList++;
i++;
}
}
return i;
}
static char** Sys_ConcatenateFileLists( char **list0, char **list1, char **list2 )
{
int totalLength = 0;
char** cat = NULL, **dst, **src;
totalLength += Sys_CountFileList(list0);
totalLength += Sys_CountFileList(list1);
totalLength += Sys_CountFileList(list2);
/* Create new list. */
dst = cat = (char **)Z_Malloc( ( totalLength + 1 ) * sizeof( char* ), TAG_FILESYS, qtrue );
/* Copy over lists. */
if (list0) {
for (src = list0; *src; src++, dst++)
*dst = *src;
}
if (list1) {
for (src = list1; *src; src++, dst++)
*dst = *src;
}
if (list2) {
for (src = list2; *src; src++, dst++)
*dst = *src;
}
// Terminate the list
*dst = NULL;
// Free our old lists.
// NOTE: not freeing their content, it's been merged in dst and still being used
if (list0) Z_Free( list0 );
if (list1) Z_Free( list1 );
if (list2) Z_Free( list2 );
return cat;
}
//#endif
// For base game mod listing
const char *SE_GetString( const char *psPackageAndStringReference );
/*
================
FS_GetModList
Returns a list of mod directory names
A mod directory is a peer to base with a pk3 in it
The directories are searched in base path, cd path and home path
================
*/
int FS_GetModList( char *listbuf, int bufsize ) {
int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen;
char **pFiles = NULL;
char **pPaks = NULL;
char *name, *path;
char descPath[MAX_OSPATH];
fileHandle_t descHandle;
int dummy;
char **pFiles0 = NULL;
char **pFiles1 = NULL;
char **pFiles2 = NULL;
qboolean bDrop = qfalse;
*listbuf = 0;
nMods = nPotential = nTotal = 0;
pFiles0 = Sys_ListFiles( fs_homepath->string, NULL, NULL, &dummy, qtrue );
pFiles1 = Sys_ListFiles( fs_basepath->string, NULL, NULL, &dummy, qtrue );
pFiles2 = Sys_ListFiles( fs_cdpath->string, NULL, NULL, &dummy, qtrue );
// we searched for mods in the three paths
// it is likely that we have duplicate names now, which we will cleanup below
pFiles = Sys_ConcatenateFileLists( pFiles0, pFiles1, pFiles2 );
nPotential = Sys_CountFileList(pFiles);
for ( i = 0 ; i < nPotential ; i++ ) {
name = pFiles[i];
// NOTE: cleaner would involve more changes
// ignore duplicate mod directories
if (i!=0) {
bDrop = qfalse;
for(j=0; j<i; j++)
{
if (Q_stricmp(pFiles[j],name)==0) {
// this one can be dropped
bDrop = qtrue;
break;
}
}
}
if (bDrop) {
continue;
}
// we drop "." and ".."
if (Q_stricmpn(name, ".", 1)) {
// now we need to find some .pk3 files to validate the mod
// NOTE TTimo: (actually I'm not sure why .. what if it's a mod under developement with no .pk3?)
// we didn't keep the information when we merged the directory names, as to what OS Path it was found under
// so it could be in base path, cd path or home path
// we will try each three of them here (yes, it's a bit messy)
path = FS_BuildOSPath( fs_basepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse);
Sys_FreeFileList( pPaks ); // we only use Sys_ListFiles to check wether .pk3 files are present
/* Try on cd path */
if( nPaks <= 0 ) {
path = FS_BuildOSPath( fs_cdpath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
/* try on home path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_homepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
if (nPaks > 0) {
bool isBase = !Q_stricmp( name, BASEGAME );
nLen = isBase ? 1 : strlen(name) + 1;
// nLen is the length of the mod path
// we need to see if there is a description available
descPath[0] = '\0';
strcpy(descPath, name);
strcat(descPath, "/description.txt");
nDescLen = FS_SV_FOpenFileRead( descPath, &descHandle );
if ( nDescLen > 0 && descHandle) {
FILE *file;
file = FS_FileForHandle(descHandle);
Com_Memset( descPath, 0, sizeof( descPath ) );
nDescLen = fread(descPath, 1, 48, file);
if (nDescLen >= 0) {
descPath[nDescLen] = '\0';
}
FS_FCloseFile(descHandle);
} else if ( isBase ) {
strcpy(descPath, SE_GetString("MENUS_JEDI_ACADEMY"));
} else {
strcpy(descPath, name);
}
nDescLen = strlen(descPath) + 1;
if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) {
if ( isBase )
strcpy(listbuf, "");
else
strcpy(listbuf, name);
listbuf += nLen;
strcpy(listbuf, descPath);
listbuf += nDescLen;
nTotal += nLen + nDescLen;
nMods++;
}
else {
break;
}
}
}
}
Sys_FreeFileList( pFiles );
return nMods;
}
//============================================================================
/*
================
FS_Dir_f
================
*/
void FS_Dir_f( void ) {
char *path;
char *extension;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) {
Com_Printf( "usage: dir <directory> [extension]\n" );
return;
}
if ( Cmd_Argc() == 2 ) {
path = Cmd_Argv( 1 );
extension = "";
} else {
path = Cmd_Argv( 1 );
extension = Cmd_Argv( 2 );
}
Com_Printf( "Directory of %s %s\n", path, extension );
Com_Printf( "---------------\n" );
dirnames = FS_ListFiles( path, extension, &ndirs );
for ( i = 0; i < ndirs; i++ ) {
Com_Printf( "%s\n", dirnames[i] );
}
FS_FreeFileList( dirnames );
}
/*
===========
FS_ConvertPath
===========
*/
void FS_ConvertPath( char *s ) {
while (*s) {
if ( *s == '\\' || *s == ':' ) {
*s = '/';
}
s++;
}
}
/*
===========
FS_PathCmp
Ignore case and separator char distinctions
===========
*/
int FS_PathCmp( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if (c1 >= 'a' && c1 <= 'z') {
c1 -= ('a' - 'A');
}
if (c2 >= 'a' && c2 <= 'z') {
c2 -= ('a' - 'A');
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if (c1 < c2) {
return -1; // strings not equal
}
if (c1 > c2) {
return 1;
}
} while (c1);
return 0; // strings are equal
}
/*
================
FS_SortFileList
================
*/
void FS_SortFileList(char **filelist, int numfiles) {
int i, j, k, numsortedfiles;
char **sortedlist;
sortedlist = (char **)Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ), TAG_FILESYS, qtrue );
sortedlist[0] = NULL;
numsortedfiles = 0;
for (i = 0; i < numfiles; i++) {
for (j = 0; j < numsortedfiles; j++) {
if (FS_PathCmp(filelist[i], sortedlist[j]) < 0) {
break;
}
}
for (k = numsortedfiles; k > j; k--) {
sortedlist[k] = sortedlist[k-1];
}
sortedlist[j] = filelist[i];
numsortedfiles++;
}
Com_Memcpy(filelist, sortedlist, numfiles * sizeof( *filelist ) );
Z_Free(sortedlist);
}
/*
================
FS_NewDir_f
================
*/
void FS_NewDir_f( void ) {
char *filter;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 ) {
Com_Printf( "usage: fdir <filter>\n" );
Com_Printf( "example: fdir *ffa*.bsp\n");
return;
}
filter = Cmd_Argv( 1 );
Com_Printf( "---------------\n" );
dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs );
FS_SortFileList(dirnames, ndirs);
for ( i = 0; i < ndirs; i++ ) {
FS_ConvertPath(dirnames[i]);
Com_Printf( "%s\n", dirnames[i] );
}
Com_Printf( "%d files listed\n", ndirs );
FS_FreeFileList( dirnames );
}
/*
============
FS_Path_f
============
*/
void FS_Path_f( void ) {
searchpath_t *s;
int i;
Com_Printf ("Current search path:\n");
for (s = fs_searchpaths; s; s = s->next) {
if (s->pack) {
Com_Printf ("%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles);
if ( fs_numServerPaks ) {
if ( !FS_PakIsPure(s->pack) ) {
Com_Printf( " not on the pure list\n" );
} else {
Com_Printf( " on the pure list\n" );
}
}
} else {
Com_Printf ("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir );
}
}
Com_Printf( "\n" );
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o ) {
Com_Printf( "handle %i: %s\n", i, fsh[i].name );
}
}
}
/*
============
FS_TouchFile_f
The only purpose of this function is to allow game script files to copy
arbitrary files furing an "fs_copyfiles 1" run.
============
*/
void FS_TouchFile_f( void ) {
fileHandle_t f;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: touchFile <file>\n" );
return;
}
FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse );
if ( f ) {
FS_FCloseFile( f );
}
}
/*
============
FS_Which_f
============
*/
void FS_Which_f( void ) {
searchpath_t *search;
char *filename;
filename = Cmd_Argv(1);
if ( !filename[0] ) {
Com_Printf( "Usage: which <file>\n" );
return;
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
return;
}
// just wants to see if file is there
for ( search=fs_searchpaths; search; search=search->next ) {
if ( search->pack ) {
long hash = FS_HashFileName( filename, search->pack->hashSize );
// is the element a pak file?
if ( search->pack->hashTable[hash]) {
// look through all the pak file elements
pack_t* pak = search->pack;
fileInPack_t* pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
// found it!
Com_Printf( "File \"%s\" found in \"%s\"\n", filename, pak->pakFilename );
return;
}
pakFile = pakFile->next;
} while ( pakFile != NULL );
}
} else if (search->dir) {
directory_t* dir = search->dir;
char* netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename );
FILE* filep = fopen(netpath, "rb");
if ( filep ) {
fclose( filep );
char buf[MAX_OSPATH];
Com_sprintf( buf, sizeof( buf ), "%s%c%s", dir->path, PATH_SEP, dir->gamedir );
FS_ReplaceSeparators( buf );
Com_Printf( "File \"%s\" found at \"%s\"\n", filename, buf );
return;
}
}
}
Com_Printf( "File not found: \"%s\"\n", filename );
}
//===========================================================================
static int QDECL paksort( const void *a, const void *b ) {
char *aa, *bb;
aa = *(char **)a;
bb = *(char **)b;
return FS_PathCmp( aa, bb );
}
/*
================
FS_AddGameDirectory
Sets fs_gamedir, adds the directory to the head of the path,
then loads the zip headers
================
*/
#define MAX_PAKFILES 1024
static void FS_AddGameDirectory( const char *path, const char *dir ) {
searchpath_t *sp;
int i;
searchpath_t *search;
searchpath_t *thedir;
pack_t *pak;
char curpath[MAX_OSPATH + 1], *pakfile;
int numfiles;
char **pakfiles;
char *sorted[MAX_PAKFILES];
// this fixes the case where fs_basepath is the same as fs_cdpath
// which happens on full installs
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->dir && Sys_PathCmp(sp->dir->path, path) && !Q_stricmp(sp->dir->gamedir, dir)) {
return; // we've already got this one
}
}
Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) );
// find all pak files in this directory
Q_strncpyz(curpath, FS_BuildOSPath(path, dir, ""), sizeof(curpath));
curpath[strlen(curpath) - 1] = '\0'; // strip the trailing slash
//
// add the directory to the search path
//
search = (struct searchpath_s *)Z_Malloc (sizeof(searchpath_t), TAG_FILESYS, qtrue);
search->dir = (directory_t *)Z_Malloc( sizeof( *search->dir ), TAG_FILESYS, qtrue );
Q_strncpyz( search->dir->path, path, sizeof( search->dir->path ) );
Q_strncpyz( search->dir->fullpath, curpath, sizeof( search->dir->fullpath ) );
Q_strncpyz( search->dir->gamedir, dir, sizeof( search->dir->gamedir ) );
search->next = fs_searchpaths;
fs_searchpaths = search;
thedir = search;
pakfiles = Sys_ListFiles( curpath, ".pk3", NULL, &numfiles, qfalse );
// sort them so that later alphabetic matches override
// earlier ones. This makes pak1.pk3 override pak0.pk3
if ( numfiles > MAX_PAKFILES ) {
numfiles = MAX_PAKFILES;
}
for ( i = 0 ; i < numfiles ; i++ ) {
sorted[i] = pakfiles[i];
}
qsort( sorted, numfiles, sizeof(char*), paksort );
for ( i = 0 ; i < numfiles ; i++ ) {
pakfile = FS_BuildOSPath( path, dir, sorted[i] );
if ( ( pak = FS_LoadZipFile( pakfile, sorted[i] ) ) == 0 )
continue;
Q_strncpyz(pak->pakPathname, curpath, sizeof(pak->pakPathname));
// store the game name for downloading
Q_strncpyz(pak->pakGamename, dir, sizeof(pak->pakGamename));
fs_packFiles += pak->numfiles;
search = (searchpath_s *)Z_Malloc (sizeof(searchpath_t), TAG_FILESYS, qtrue);
search->pack = pak;
if (fs_dirbeforepak && fs_dirbeforepak->integer && thedir)
{
searchpath_t *oldnext = thedir->next;
thedir->next = search;
while (oldnext)
{
search->next = oldnext;
search = search->next;
oldnext = oldnext->next;
}
}
else
{
search->next = fs_searchpaths;
fs_searchpaths = search;
}
}
// done
Sys_FreeFileList( pakfiles );
}
/*
================
FS_idPak
================
*/
qboolean FS_idPak( char *pak, char *base ) {
int i;
for (i = 0; i < NUM_ID_PAKS; i++) {
if ( !FS_FilenameCompare(pak, va("%s/assets%d", base, i)) ) {
break;
}
}
if (i < NUM_ID_PAKS) {
return qtrue;
}
return qfalse;
}
/*
================
FS_CheckDirTraversal
Check whether the string contains stuff like "../" to prevent directory traversal bugs
and return qtrue if it does.
================
*/
qboolean FS_CheckDirTraversal(const char *checkdir)
{
if(strstr(checkdir, "../") || strstr(checkdir, "..\\"))
return qtrue;
return qfalse;
}
/*
================
FS_ComparePaks
if dlstring == qtrue
Returns a list of pak files that we should download from the server. They all get stored
in the current gamedir and an FS_Restart will be fired up after we download them all.
The string is the format:
@remotename@localname [repeat]
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS];
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS];
----------------
dlstring == qfalse
we are not interested in a download string format, we want something human-readable
(this is used for diagnostics while connecting to a pure server)
================
*/
qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring ) {
searchpath_t *sp;
qboolean havepak;
char *origpos = neededpaks;
int i;
if ( !fs_numServerReferencedPaks ) {
return qfalse; // Server didn't send any pack information along
}
*neededpaks = 0;
for ( i = 0 ; i < fs_numServerReferencedPaks ; i++ ) {
// Ok, see if we have this pak file
havepak = qfalse;
// never autodownload any of the id paks
if ( FS_idPak(fs_serverReferencedPakNames[i], "base") || FS_idPak(fs_serverReferencedPakNames[i], "missionpack") ) {
continue;
}
// Make sure the server cannot make us write to non-quake3 directories.
if(FS_CheckDirTraversal(fs_serverReferencedPakNames[i]))
{
Com_Printf("WARNING: Invalid download name %s\n", fs_serverReferencedPakNames[i]);
continue;
}
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i] ) {
havepak = qtrue; // This is it!
break;
}
}
if ( !havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i] ) {
// Don't got it
if (dlstring)
{
// We need this to make sure we won't hit the end of the buffer or the server could
// overwrite non-pk3 files on clients by writing so much crap into neededpaks that
// Q_strcat cuts off the .pk3 extension.
origpos += strlen(origpos);
// Remote name
Q_strcat( neededpaks, len, "@");
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Local name
Q_strcat( neededpaks, len, "@");
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) ) {
char st[MAX_ZPATH];
// We already have one called this, we need to download it to another name
// Make something up with the checksum in it
Com_sprintf( st, sizeof( st ), "%s.%08x.pk3", fs_serverReferencedPakNames[i], fs_serverReferencedPaks[i] );
Q_strcat( neededpaks, len, st );
} else {
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
}
// Find out whether it might have overflowed the buffer and don't add this file to the
// list if that is the case.
if(strlen(origpos) + (origpos - neededpaks) >= (unsigned)(len - 1))
{
*origpos = '\0';
break;
}
}
else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
{
Q_strcat( neededpaks, len, " (local file exists with wrong checksum)");
}
Q_strcat( neededpaks, len, "\n");
}
}
}
if ( *neededpaks ) {
return qtrue;
}
return qfalse; // We have them all
}
/*
================
FS_Shutdown
Frees all resources and closes all files
================
*/
void FS_Shutdown( qboolean closemfp ) {
searchpath_t *p, *next;
int i;
#if defined(_WIN32)
// Delete temporary files
fs_temporaryFileWriteIdx = 0;
for ( size_t i = 0; i < ARRAY_LEN(fs_temporaryFileNames); i++ )
{
if (fs_temporaryFileNames[i][0] != '\0')
{
if ( !DeleteFile(fs_temporaryFileNames[i]) )
{
DWORD error = GetLastError();
Com_DPrintf("FS_Shutdown: failed to delete '%s'. "
"Win32 error code: 0x08x",
fs_temporaryFileNames[i],
error);
}
fs_temporaryFileNames[i][0] = '\0';
}
}
#endif
for(i = 0; i < MAX_FILE_HANDLES; i++) {
if (fsh[i].fileSize) {
FS_FCloseFile(i);
}
}
// free everything
for ( p = fs_searchpaths ; p ; p = next ) {
next = p->next;
if ( p->pack ) {
FS_FreePak( p->pack );
}
if ( p->dir ) {
Z_Free( p->dir );
}
Z_Free( p );
}
// any FS_ calls will now be an error until reinitialized
fs_searchpaths = NULL;
Cmd_RemoveCommand( "path" );
Cmd_RemoveCommand( "dir" );
Cmd_RemoveCommand( "fdir" );
Cmd_RemoveCommand( "touchFile" );
Cmd_RemoveCommand( "which" );
#ifdef FS_MISSING
if (closemfp) {
fclose(missingFiles);
}
#endif
}
//rww - add search paths in for received svc_setgame
//Ensiform - this is so wrong rww
void FS_UpdateGamedir(void)
{
if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, BASEGAME ) )
{
if (fs_cdpath->string[0])
{
FS_AddGameDirectory(fs_cdpath->string, fs_gamedirvar->string);
}
if (fs_basepath->string[0])
{
FS_AddGameDirectory(fs_basepath->string, fs_gamedirvar->string);
}
if (fs_homepath->string[0] && !Sys_PathCmp(fs_homepath->string, fs_basepath->string))
{
FS_AddGameDirectory(fs_homepath->string, fs_gamedirvar->string);
}
}
}
/*
================
FS_ReorderPurePaks
NOTE TTimo: the reordering that happens here is not reflected in the cvars (\cvarlist *pak*)
this can lead to misleading situations, see https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
================
*/
static void FS_ReorderPurePaks()
{
searchpath_t *s;
int i;
searchpath_t **p_insert_index, // for linked list reordering
**p_previous; // when doing the scan
// only relevant when connected to pure server
if ( !fs_numServerPaks )
return;
fs_reordered = qfalse;
p_insert_index = &fs_searchpaths; // we insert in order at the beginning of the list
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
p_previous = p_insert_index; // track the pointer-to-current-item
for (s = *p_insert_index; s; s = s->next) {
// the part of the list before p_insert_index has been sorted already
if (s->pack && fs_serverPaks[i] == s->pack->checksum) {
fs_reordered = qtrue;
// move this element to the insert list
*p_previous = s->next;
s->next = *p_insert_index;
*p_insert_index = s;
// increment insert list
p_insert_index = &s->next;
break; // iterate to next server pack
}
p_previous = &s->next;
}
}
}
/**
@brief Mount the asset archives (.pk3) and register commands.
Mounts in this order the archives from:
1. <fs_cdpath>/<gameName>/
2. <fs_basepath>/<gameName>/
3. <fs_apppath>/<gameName>/ (Mac Only)
4. <fs_homepath>/<gameName>/
5. <fs_cdpath>/<fs_basegame>/
6. <fs_basepath>/<fs_basegame>/
7. <fs_homepath>/<fs_basegame>/
8. <fs_cdpath>/<fs_game>/
9. <fs_basepath>/<fs_game>/
10. <fs_homepath>/<fs_game>/
@param gameName Name of the default folder (i.e. always BASEGAME = "base" in OpenJK)
*/
void FS_Startup( const char *gameName ) {
const char *homePath;
Com_Printf( "----- FS_Startup -----\n" );
fs_packFiles = 0;
fs_debug = Cvar_Get( "fs_debug", "0", 0 );
fs_copyfiles = Cvar_Get( "fs_copyfiles", "0", CVAR_INIT );
fs_cdpath = Cvar_Get ("fs_cdpath", "", CVAR_INIT|CVAR_PROTECTED, "(Read Only) Location for development files" );
fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT|CVAR_PROTECTED, "(Read Only) Location for game files" );
fs_basegame = Cvar_Get ("fs_basegame", "", CVAR_INIT );
homePath = Sys_DefaultHomePath();
if (!homePath || !homePath[0]) {
homePath = fs_basepath->string;
}
fs_homepath = Cvar_Get ("fs_homepath", homePath, CVAR_INIT|CVAR_PROTECTED, "(Read/Write) Location for user generated files" );
fs_gamedirvar = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO, "Mod directory" );
fs_dirbeforepak = Cvar_Get("fs_dirbeforepak", "0", CVAR_INIT|CVAR_PROTECTED, "Prioritize directories before paks if not pure" );
// add search path elements in reverse priority order (lowest priority first)
if (fs_cdpath->string[0]) {
FS_AddGameDirectory( fs_cdpath->string, gameName );
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory( fs_basepath->string, gameName );
}
#ifdef MACOS_X
fs_apppath = Cvar_Get ("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT|CVAR_PROTECTED, "(Read Only) Location of OSX .app bundle" );
// Make MacOSX also include the base path included with the .app bundle
if (fs_apppath->string[0]) {
FS_AddGameDirectory( fs_apppath->string, gameName );
}
#endif
// fs_homepath is somewhat particular to *nix systems, only add if relevant
// NOTE: same filtering below for mods and basegame
if (fs_homepath->string[0] && !Sys_PathCmp(fs_homepath->string, fs_basepath->string)) {
FS_CreatePath ( fs_homepath->string );
FS_AddGameDirectory ( fs_homepath->string, gameName );
}
// check for additional base game so mods can be based upon other mods
if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) ) {
if (fs_cdpath->string[0]) {
FS_AddGameDirectory(fs_cdpath->string, fs_basegame->string);
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory(fs_basepath->string, fs_basegame->string);
}
if (fs_homepath->string[0] && !Sys_PathCmp(fs_homepath->string, fs_basepath->string)) {
FS_AddGameDirectory(fs_homepath->string, fs_basegame->string);
}
}
// check for additional game folder for mods
if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) ) {
if (fs_cdpath->string[0]) {
FS_AddGameDirectory(fs_cdpath->string, fs_gamedirvar->string);
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory(fs_basepath->string, fs_gamedirvar->string);
}
if (fs_homepath->string[0] && !Sys_PathCmp(fs_homepath->string, fs_basepath->string)) {
FS_AddGameDirectory(fs_homepath->string, fs_gamedirvar->string);
}
}
// add our commands
Cmd_AddCommand ("path", FS_Path_f, "Lists search paths" );
Cmd_AddCommand ("dir", FS_Dir_f, "Lists a folder" );
Cmd_AddCommand ("fdir", FS_NewDir_f, "Lists a folder with filters" );
Cmd_AddCommand ("touchFile", FS_TouchFile_f, "Touches a file" );
Cmd_AddCommand ("which", FS_Which_f, "Determines which search path a file was loaded from" );
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=506
// reorder the pure pk3 files according to server order
FS_ReorderPurePaks();
// print the current search paths
FS_Path_f();
fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified
Com_Printf( "----------------------\n" );
#ifdef FS_MISSING
if (missingFiles == NULL) {
missingFiles = fopen( "\\missing.txt", "ab" );
}
#endif
Com_Printf( "%d files in pk3 files\n", fs_packFiles );
}
/*
=====================
FS_LoadedPakChecksums
Returns a space separated string containing the checksums of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) );
}
return info;
}
/*
=====================
FS_LoadedPakNames
Returns a space separated string containing the names of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
if (*info) {
Q_strcat(info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
return info;
}
/*
=====================
FS_LoadedPakPureChecksums
Returns a space separated string containing the pure checksums of all loaded pk3 files.
Servers with sv_pure use these checksums to compare with the checksums the clients send
back to the server.
=====================
*/
const char *FS_LoadedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) );
}
return info;
}
/*
=====================
FS_ReferencedPakChecksums
Returns a space separated string containing the checksums of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, BASEGAME, strlen(BASEGAME))) {
Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) );
}
}
}
return info;
}
/*
=====================
FS_ReferencedPakPureChecksums
Returns a space separated string containing the pure checksums of all referenced pk3 files.
Servers with sv_pure set will get this string back from clients for pure validation
The string has a specific order, "cgame ui @ ref1 ref2 ref3 ..."
=====================
*/
const char *FS_ReferencedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
int nFlags, numPaks, checksum;
info[0] = 0;
checksum = fs_checksumFeed;
numPaks = 0;
for (nFlags = FS_CGAME_REF; nFlags; nFlags = nFlags >> 1) {
if (nFlags & FS_GENERAL_REF) {
// add a delimter between must haves and general refs
//Q_strcat(info, sizeof(info), "@ ");
info[strlen(info)+1] = '\0';
info[strlen(info)+2] = '\0';
info[strlen(info)] = '@';
info[strlen(info)] = ' ';
}
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file and has it been referenced based on flag?
if ( search->pack && (search->pack->referenced & nFlags)) {
Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) );
if (nFlags & (FS_CGAME_REF | FS_UI_REF)) {
break;
}
checksum ^= search->pack->pure_checksum;
numPaks++;
}
}
if (fs_fakeChkSum != 0) {
// only added if a non-pure file is referenced
Q_strcat( info, sizeof( info ), va("%i ", fs_fakeChkSum ) );
}
}
// last checksum is the encoded number of referenced pk3s
checksum ^= numPaks;
Q_strcat( info, sizeof( info ), va("%i ", checksum ) );
return info;
}
/*
=====================
FS_ReferencedPakNames
Returns a space separated string containing the names of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
// we want to return ALL pk3's from the fs_game path
// and referenced one's from base
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, BASEGAME, strlen(BASEGAME))) {
if (*info) {
Q_strcat(info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakGamename );
Q_strcat( info, sizeof( info ), "/" );
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
}
}
return info;
}
/*
=====================
FS_ClearPakReferences
=====================
*/
void FS_ClearPakReferences( int flags ) {
searchpath_t *search;
if ( !flags ) {
flags = -1;
}
for ( search = fs_searchpaths; search; search = search->next ) {
// is the element a pak file and has it been referenced?
if ( search->pack ) {
search->pack->referenced &= ~flags;
}
}
}
/*
=====================
FS_PureServerSetLoadedPaks
If the string is empty, all data sources will be allowed.
If not empty, only pk3 files that match one of the space
separated checksums will be checked for files, with the
exception of .cfg and .dat files.
=====================
*/
void FS_PureServerSetLoadedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
fs_numServerPaks = c;
for ( i = 0 ; i < c ; i++ ) {
fs_serverPaks[i] = atoi( Cmd_Argv( i ) );
}
if (fs_numServerPaks) {
Com_DPrintf( "Connected to a pure server.\n" );
}
else
{
if (fs_reordered)
{
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
// force a restart to make sure the search order will be correct
Com_DPrintf( "FS search reorder is required\n" );
FS_Restart(fs_checksumFeed);
return;
}
}
for ( i = 0 ; i < c ; i++ ) {
if (fs_serverPakNames[i]) {
Z_Free(fs_serverPakNames[i]);
}
fs_serverPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if ( d > MAX_SEARCH_PATHS ) {
d = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < d ; i++ ) {
fs_serverPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
}
/*
=====================
FS_PureServerSetReferencedPaks
The checksums and names of the pk3 files referenced at the server
are sent to the client and stored here. The client will use these
checksums to see if any pk3 files need to be auto-downloaded.
=====================
*/
void FS_PureServerSetReferencedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d = 0;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < c ; i++ ) {
fs_serverReferencedPaks[i] = atoi( Cmd_Argv( i ) );
}
for (i = 0 ; i < (int)ARRAY_LEN(fs_serverReferencedPakNames); i++)
{
if(fs_serverReferencedPakNames[i])
Z_Free(fs_serverReferencedPakNames[i]);
fs_serverReferencedPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if ( d > c ) {
d = c;
}
for ( i = 0 ; i < d ; i++ ) {
fs_serverReferencedPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
// ensure that there are as many checksums as there are pak names.
if(d < c)
c = d;
fs_numServerReferencedPaks = c;
}
/*
================
FS_InitFilesystem
Called only at inital startup, not when the filesystem
is resetting due to a game change
================
*/
void FS_InitFilesystem( void ) {
// allow command line parms to override our defaults
// we have to specially handle this, because normal command
// line variable sets don't happen until after the filesystem
// has already been initialized
Com_StartupVariable( "fs_cdpath" );
Com_StartupVariable( "fs_basepath" );
Com_StartupVariable( "fs_homepath" );
Com_StartupVariable( "fs_game" );
Com_StartupVariable( "fs_copyfiles" );
Com_StartupVariable( "fs_dirbeforepak" );
#ifdef MACOS_X
Com_StartupVariable( "fs_apppath" );
#endif
if(!FS_FilenameCompare(Cvar_VariableString("fs_game"), BASEGAME))
Cvar_Set("fs_game", "");
// try to start up normally
FS_Startup( BASEGAME );
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "mpdefault.cfg", NULL ) <= 0 ) {
Com_Error( ERR_FATAL, "Couldn't load mpdefault.cfg" );
// bk001208 - SafeMode see below, FIXME?
}
Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
#if defined(_WIN32)
Com_Memset(fs_temporaryFileNames, 0, sizeof(fs_temporaryFileNames));
#endif
// bk001208 - SafeMode see below, FIXME?
}
/*
================
FS_Restart
================
*/
void FS_Restart( int checksumFeed ) {
// free anything we currently have loaded
FS_Shutdown(qfalse);
// set the checksum feed
fs_checksumFeed = checksumFeed;
// clear pak references
FS_ClearPakReferences(0);
// try to start up normally
FS_Startup( BASEGAME );
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "mpdefault.cfg", NULL ) <= 0 ) {
// this might happen when connecting to a pure server not using BASEGAME/pak0.pk3
// (for instance a TA demo server)
if (lastValidBase[0]) {
FS_PureServerSetLoadedPaks("", "");
Cvar_Set("fs_basepath", lastValidBase);
Cvar_Set("fs_game", lastValidGame);
lastValidBase[0] = '\0';
lastValidGame[0] = '\0';
FS_Restart(checksumFeed);
Com_Error( ERR_DROP, "Invalid game folder\n" );
return;
}
Com_Error( ERR_FATAL, "Couldn't load mpdefault.cfg" );
}
if ( Q_stricmp(fs_gamedirvar->string, lastValidGame) ) {
// skip the jampconfig.cfg if "safe" is on the command line
if ( !Com_SafeMode() ) {
Cbuf_AddText ("exec " Q3CONFIG_CFG "\n");
}
}
Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
}
/*
=================
FS_ConditionalRestart
restart if necessary
=================
*/
qboolean FS_ConditionalRestart( int checksumFeed ) {
if( fs_gamedirvar->modified || checksumFeed != fs_checksumFeed ) {
FS_Restart( checksumFeed );
return qtrue;
}
#if 0
if(fs_gamedirvar->modified)
{
if(FS_FilenameCompare(lastValidGame, fs_gamedirvar->string) &&
(*lastValidGame || FS_FilenameCompare(fs_gamedirvar->string, BASEGAME)) &&
(*fs_gamedirvar->string || FS_FilenameCompare(lastValidGame, BASEGAME)))
{
FS_Restart(checksumFeed);
//Cvar_Restart(qtrue);
return qtrue;
}
else
fs_gamedirvar->modified = qfalse;
}
if(checksumFeed != fs_checksumFeed)
FS_Restart(checksumFeed);
else if(fs_numServerPaks && !fs_reordered)
FS_ReorderPurePaks();
#endif
return qfalse;
}
/*
========================================================================================
Handle based file calls for virtual machines
========================================================================================
*/
int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
int r;
qboolean sync;
sync = qfalse;
switch( mode ) {
case FS_READ:
r = FS_FOpenFileRead( qpath, f, qtrue );
break;
case FS_WRITE:
*f = FS_FOpenFileWrite( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
case FS_APPEND_SYNC:
sync = qtrue;
case FS_APPEND:
*f = FS_FOpenFileAppend( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
default:
Com_Error( ERR_FATAL, "FSH_FOpenFile: bad mode" );
return -1;
}
if (!f) {
return r;
}
if ( *f ) {
fsh[*f].fileSize = r;
}
fsh[*f].handleSync = sync;
return r;
}
int FS_FTell( fileHandle_t f ) {
int pos;
if (fsh[f].zipFile == qtrue) {
pos = unztell(fsh[f].handleFiles.file.z);
} else {
pos = ftell(fsh[f].handleFiles.file.o);
}
return pos;
}
void FS_Flush( fileHandle_t f ) {
fflush(fsh[f].handleFiles.file.o);
}
void FS_FilenameCompletion( const char *dir, const char *ext, qboolean stripExt, callbackFunc_t callback, qboolean allowNonPureFilesOnDisk ) {
int nfiles;
char **filenames, filename[MAX_STRING_CHARS];
filenames = FS_ListFilteredFiles( dir, ext, NULL, &nfiles );
FS_SortFileList( filenames, nfiles );
// pass all the files to callback (FindMatches)
for ( int i=0; i<nfiles; i++ ) {
FS_ConvertPath( filenames[i] );
Q_strncpyz( filename, filenames[i], MAX_STRING_CHARS );
if ( stripExt )
COM_StripExtension( filename, filename, sizeof( filename ) );
callback( filename );
}
FS_FreeFileList( filenames );
}
const char *FS_GetCurrentGameDir(bool emptybase)
{
if(fs_gamedirvar->string[0])
return fs_gamedirvar->string;
return emptybase ? "" : BASEGAME;
}
#ifdef MACOS_X
bool FS_LoadMachOBundle( const char *name )
{
int len;
void *data;
fileHandle_t f;
char *fn;
unzFile dll;
byte* buf;
char dllName[MAX_QPATH];
char *tempName;
unz_file_info zfi;
//read zipped bundle from pk3
len = FS_ReadFile(name, &data);
if (len < 1) {
return false;
}
//write temporary file of zipped bundle to e.g. uixxxxxx
//unique filename to avoid any clashes
Com_sprintf( dllName, sizeof(dllName), "%sXXXXXX", name );
tempName = mktemp( dllName );
f = FS_FOpenFileWrite( dllName );
if ( !f )
{
FS_FreeFile(data);
return false;
}
if (FS_Write( data, len, f ) < len)
{
FS_FreeFile(data);
return false;
}
FS_FCloseFile( f );
FS_FreeFile(data);
//unzOpen zipped bundle, find the dylib, and try to write it
fn = FS_BuildOSPath( fs_homepath->string, fs_gamedir, dllName );
dll = unzOpen( fn );
Com_sprintf (dllName, sizeof(dllName), "%s.bundle/Contents/MacOS/%s", name, name);
if (unzLocateFile(dll, dllName, 0) != UNZ_OK)
{
unzClose(dll);
remove( fn );
return false;
}
unzOpenCurrentFile( dll );
Com_sprintf( dllName, sizeof(dllName), "%s_pk3" DLL_EXT, name );
f = FS_FOpenFileWrite( dllName, qfalse );
if ( !f )
{
unzCloseCurrentFile( dll );
unzClose( dll );
remove( fn );
return false;
}
unzGetCurrentFileInfo( dll, &zfi, NULL, 0, NULL, 0, NULL, 0 );
len = zfi.uncompressed_size;
buf = (byte*)Z_Malloc( len+1, TAG_FILESYS, qfalse);
if (unzReadCurrentFile( dll, buf, len ) < len)
{
FS_FCloseFile( f );
unzCloseCurrentFile( dll );
unzClose( dll );
return false;
}
if (FS_Write(buf, len, f) < len)
{
FS_FCloseFile( f );
unzCloseCurrentFile( dll );
unzClose( dll );
return false;
}
FS_FCloseFile( f );
unzCloseCurrentFile( dll );
unzClose( dll );
Z_Free( buf );
//remove temporary zipped bundle
remove( fn );
return true;
}
#endif
qboolean FS_WriteToTemporaryFile( const void *data, size_t dataLength, char **tempFilePath )
{
#if defined(_WIN32)
DWORD error;
TCHAR tempPath[MAX_PATH];
DWORD tempPathResult = GetTempPath(MAX_PATH, tempPath);
if ( tempPathResult )
{
TCHAR tempFileName[MAX_PATH];
UINT tempFileNameResult = GetTempFileName(tempPath, "OJK", 0, tempFileName);
if ( tempFileNameResult )
{
HANDLE file = CreateFile(
tempFileName, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if ( file != INVALID_HANDLE_VALUE )
{
DWORD bytesWritten = 0;
if (WriteFile(file, data, dataLength, &bytesWritten, NULL))
{
int deletesRemaining = ARRAY_LEN(fs_temporaryFileNames);
CloseHandle(file);
while ( deletesRemaining > 0 &&
fs_temporaryFileNames[fs_temporaryFileWriteIdx][0] != '\0' )
{
// Delete old temporary file as we need to
if ( DeleteFile(fs_temporaryFileNames[fs_temporaryFileWriteIdx]) )
{
break;
}
error = GetLastError();
Com_DPrintf("FS_WriteToTemporaryFile failed for '%s'. "
"Win32 error code: 0x%08x\n",
fs_temporaryFileNames[fs_temporaryFileWriteIdx],
error);
// Failed to delete, possibly because DLL was still in use. This can
// happen when running a listen server and you continually restart
// the map. The game DLL is reloaded, but cgame and ui DLLs are not.
fs_temporaryFileWriteIdx =
(fs_temporaryFileWriteIdx + 1) % ARRAY_LEN(fs_temporaryFileNames);
deletesRemaining--;
}
// If this happened, then all slots are used and we some how have 8 DLLs
// loaded at once?!
assert(deletesRemaining > 0);
Q_strncpyz(fs_temporaryFileNames[fs_temporaryFileWriteIdx],
tempFileName, sizeof(fs_temporaryFileNames[0]));
fs_temporaryFileWriteIdx =
(fs_temporaryFileWriteIdx + 1) % ARRAY_LEN(fs_temporaryFileNames);
if ( tempFilePath )
{
size_t fileNameLen = strlen(tempFileName);
*tempFilePath = (char *)Z_Malloc(fileNameLen + 1, TAG_FILESYS);
Q_strncpyz(*tempFilePath, tempFileName, fileNameLen + 1);
}
return qtrue;
}
else
{
error = GetLastError();
Com_DPrintf("FS_WriteToTemporaryFile failed to write '%s'. "
"Win32 error code: 0x%08x\n",
tempFileName, error);
}
}
else
{
error = GetLastError();
Com_DPrintf("FS_WriteToTemporaryFile failed to create '%s'. "
"Win32 error code: 0x%08x\n",
tempFileName, error);
}
}
else
{
error = GetLastError();
Com_DPrintf("FS_WriteToTemporaryFile failed to generate temporary file name. "
"Win32 error code: 0x%08x\n", error);
}
}
else
{
error = GetLastError();
Com_DPrintf("FS_WriteToTemporaryFile failed to get temporary file folder. "
"Win32 error code: 0x%08x\n", error);
}
#endif
return qfalse;
}
| ./CrossVul/dataset_final_sorted/CWE-269/cpp/good_3234_3 |
crossvul-cpp_data_bad_3234_3 | /*
===========================================================================
Copyright (C) 1999 - 2005, Id Software, Inc.
Copyright (C) 2000 - 2013, Raven Software, Inc.
Copyright (C) 2001 - 2013, Activision, Inc.
Copyright (C) 2005 - 2015, ioquake3 contributors
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
/*****************************************************************************
* name: files.cpp
*
* desc: file code
*
*****************************************************************************/
#include "qcommon/qcommon.h"
#ifndef DEDICATED
#ifndef FINAL_BUILD
#include "client/client.h"
#endif
#endif
#include <minizip/unzip.h>
#if defined(_WIN32)
#include <windows.h>
#endif
// for rmdir
#if defined (_MSC_VER)
#include <direct.h>
#else
#include <unistd.h>
#endif
/*
=============================================================================
QUAKE3 FILESYSTEM
All of Quake's data access is through a hierarchical file system, but the contents of
the file system can be transparently merged from several sources.
A "qpath" is a reference to game file data. MAX_ZPATH is 256 characters, which must include
a terminating zero. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any
references outside the quake directory system.
The "base path" is the path to the directory holding all the game directories and usually
the executable. It defaults to ".", but can be overridden with a "+set fs_basepath c:\quake3"
command line to allow code debugging in a different directory. Basepath cannot
be modified at all after startup. Any files that are created (demos, screenshots,
etc) will be created relative to the base path, so base path should usually be writable.
The "home path" is the path used for all write access. On win32 systems we have "base path"
== "home path", but on *nix systems the base installation is usually readonly, and
"home path" points to ~/.q3a or similar
The user can also install custom mods and content in "home path", so it should be searched
along with "home path" and "cd path" for game content.
The "base game" is the directory under the paths where data comes from by default, and
can be either "baseq3" or "demoq3".
The "current game" may be the same as the base game, or it may be the name of another
directory under the paths that should be searched for files before looking in the base game.
This is the basis for addons.
Clients automatically set the game directory after receiving a gamestate from a server,
so only servers need to worry about +set fs_game.
No other directories outside of the base game and current game will ever be referenced by
filesystem functions.
To save disk space and speed loading, directory trees can be collapsed into zip files.
The files use a ".pk3" extension to prevent users from unzipping them accidentally, but
otherwise the are simply normal uncompressed zip files. A game directory can have multiple
zip files of the form "pak0.pk3", "pak1.pk3", etc. Zip files are searched in decending order
from the highest number to the lowest, and will always take precedence over the filesystem.
This allows a pk3 distributed as a patch to override all existing data.
Because we will have updated executables freely available online, there is no point to
trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
should be exactly the same executables as release versions, but with different data that
automatically restricts where game media can come from to prevent add-ons from working.
File search order: when FS_FOpenFileRead gets called it will go through the fs_searchpaths
structure and stop on the first successful hit. fs_searchpaths is built with successive
calls to FS_AddGameDirectory
Additionaly, we search in several subdirectories:
current game is the current mode
base game is a variable to allow mods based on other mods
(such as baseq3 + missionpack content combination in a mod for instance)
BASEGAME is the hardcoded base game ("baseq3")
e.g. the qpath "sound/newstuff/test.wav" would be searched for in the following places:
home path + current game's zip files
home path + current game's directory
base path + current game's zip files
base path + current game's directory
cd path + current game's zip files
cd path + current game's directory
home path + base game's zip file
home path + base game's directory
base path + base game's zip file
base path + base game's directory
cd path + base game's zip file
cd path + base game's directory
home path + BASEGAME's zip file
home path + BASEGAME's directory
base path + BASEGAME's zip file
base path + BASEGAME's directory
cd path + BASEGAME's zip file
cd path + BASEGAME's directory
server download, to be written to home path + current game's directory
The filesystem can be safely shutdown and reinitialized with different
basedir / cddir / game combinations, but all other subsystems that rely on it
(sound, video) must also be forced to restart.
Because the same files are loaded by both the clip model (CM_) and renderer (TR_)
subsystems, a simple single-file caching scheme is used. The CM_ subsystems will
load the file with a request to cache. Only one file will be kept cached at a time,
so any models that are going to be referenced by both subsystems should alternate
between the CM_ load function and the ref load function.
TODO: A qpath that starts with a leading slash will always refer to the base game, even if another
game is currently active. This allows character models, skins, and sounds to be downloaded
to a common directory no matter which game is active.
How to prevent downloading zip files?
Pass pk3 file names in systeminfo, and download before FS_Restart()?
Aborting a download disconnects the client from the server.
How to mark files as downloadable? Commercial add-ons won't be downloadable.
Non-commercial downloads will want to download the entire zip file.
the game would have to be reset to actually read the zip in
Auto-update information
Path separators
Casing
separate server gamedir and client gamedir, so if the user starts
a local game after having connected to a network game, it won't stick
with the network game.
allow menu options for game selection?
Read / write config to floppy option.
Different version coexistance?
When building a pak file, make sure a q3config.cfg isn't present in it,
or configs will never get loaded from disk!
todo:
downloading (outside fs?)
game directory passing and restarting
=============================================================================
*/
#define MAX_ZPATH 256
#define MAX_SEARCH_PATHS 4096
#define MAX_FILEHASH_SIZE 1024
typedef struct fileInPack_s {
char *name; // name of the file
unsigned long pos; // file info position in zip
unsigned long len; // uncompress file size
struct fileInPack_s* next; // next file in the hash
} fileInPack_t;
typedef struct pack_s {
char pakPathname[MAX_OSPATH]; // c:\jediacademy\gamedata\base
char pakFilename[MAX_OSPATH]; // c:\jediacademy\gamedata\base\assets0.pk3
char pakBasename[MAX_OSPATH]; // assets0
char pakGamename[MAX_OSPATH]; // base
unzFile handle; // handle to zip file
int checksum; // regular checksum
int pure_checksum; // checksum for pure
int numfiles; // number of files in pk3
int referenced; // referenced file flags
int hashSize; // hash table size (power of 2)
fileInPack_t* *hashTable; // hash table
fileInPack_t* buildBuffer; // buffer with the filenames etc.
} pack_t;
typedef struct directory_s {
char path[MAX_OSPATH]; // c:\jediacademy\gamedata
char fullpath[MAX_OSPATH]; // c:\jediacademy\gamedata\base
char gamedir[MAX_OSPATH]; // base
} directory_t;
typedef struct searchpath_s {
struct searchpath_s *next;
pack_t *pack; // only one of pack / dir will be non NULL
directory_t *dir;
} searchpath_t;
static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators
static cvar_t *fs_debug;
static cvar_t *fs_homepath;
#ifdef MACOS_X
// Also search the .app bundle for .pk3 files
static cvar_t *fs_apppath;
#endif
static cvar_t *fs_basepath;
static cvar_t *fs_basegame;
static cvar_t *fs_cdpath;
static cvar_t *fs_copyfiles;
static cvar_t *fs_gamedirvar;
static cvar_t *fs_dirbeforepak; //rww - when building search path, keep directories at top and insert pk3's under them
static searchpath_t *fs_searchpaths;
static int fs_readCount; // total bytes read
static int fs_loadCount; // total files read
static int fs_packFiles = 0; // total number of files in packs
static int fs_fakeChkSum;
static int fs_checksumFeed;
typedef union qfile_gus {
FILE* o;
unzFile z;
} qfile_gut;
typedef struct qfile_us {
qfile_gut file;
qboolean unique;
} qfile_ut;
typedef struct fileHandleData_s {
qfile_ut handleFiles;
qboolean handleSync;
int fileSize;
int zipFilePos;
int zipFileLen;
qboolean zipFile;
char name[MAX_ZPATH];
} fileHandleData_t;
static fileHandleData_t fsh[MAX_FILE_HANDLES];
// TTimo - https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
// wether we did a reorder on the current search path when joining the server
static qboolean fs_reordered = qfalse;
// never load anything from pk3 files that are not present at the server when pure
static int fs_numServerPaks = 0;
static int fs_serverPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverPakNames[MAX_SEARCH_PATHS]; // pk3 names
// only used for autodownload, to make sure the client has at least
// all the pk3 files that are referenced at the server side
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS]; // pk3 names
#if defined(_WIN32)
// temporary files - store them in a circular buffer. We're pretty
// much guaranteed to not need more than 8 temp files at a time.
static int fs_temporaryFileWriteIdx = 0;
static char fs_temporaryFileNames[8][MAX_OSPATH];
#endif
// last valid game folder used
char lastValidBase[MAX_OSPATH];
char lastValidGame[MAX_OSPATH];
#ifdef FS_MISSING
FILE* missingFiles = NULL;
#endif
/* C99 defines __func__ */
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2 || _MSC_VER >= 1300
# define __func__ __FUNCTION__
# else
# define __func__ "(unknown)"
# endif
#endif
/*
==============
FS_Initialized
==============
*/
qboolean FS_Initialized( void ) {
return (qboolean)(fs_searchpaths != NULL);
}
static void FS_AssertInitialised( void ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
}
}
/*
=================
FS_PakIsPure
=================
*/
qboolean FS_PakIsPure( pack_t *pack ) {
int i;
if ( fs_numServerPaks ) {
// NOTE TTimo we are matching checksums without checking the pak names
// this means you can have the same pk3 as the server under a different name, you will still get through sv_pure validation
// (what happens when two pk3's have the same checkums? is it a likely situation?)
// also, if there's a wrong checksumed pk3 and autodownload is enabled, the checksum will be appended to the downloaded pk3 name
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
// FIXME: also use hashed file names
if ( pack->checksum == fs_serverPaks[i] ) {
return qtrue; // on the aproved list
}
}
return qfalse; // not on the pure server pak list
}
return qtrue;
}
/*
================
return a hash value for the filename
================
*/
static long FS_HashFileName( const char *fname, int hashSize ) {
int i;
long hash;
char letter;
hash = 0;
i = 0;
while (fname[i] != '\0') {
letter = tolower(fname[i]);
if (letter =='.') break; // don't include extension
if (letter =='\\') letter = '/'; // damn path names
if (letter == PATH_SEP) letter = '/'; // damn path names
hash+=(long)(letter)*(i+119);
i++;
}
hash = (hash ^ (hash >> 10) ^ (hash >> 20));
hash &= (hashSize-1);
return hash;
}
static fileHandle_t FS_HandleForFile(void) {
int i;
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o == NULL ) {
return i;
}
}
Com_Error( ERR_DROP, "FS_HandleForFile: none free" );
return 0;
}
static FILE *FS_FileForHandle( fileHandle_t f ) {
if ( f < 1 || f >= MAX_FILE_HANDLES ) {
Com_Error( ERR_DROP, "FS_FileForHandle: out of range" );
}
if (fsh[f].zipFile == qtrue) {
Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" );
}
if ( ! fsh[f].handleFiles.file.o ) {
Com_Error( ERR_DROP, "FS_FileForHandle: NULL" );
}
return fsh[f].handleFiles.file.o;
}
void FS_ForceFlush( fileHandle_t f ) {
FILE *file;
file = FS_FileForHandle(f);
setvbuf( file, NULL, _IONBF, 0 );
}
/*
================
FS_fplength
================
*/
long FS_fplength(FILE *h)
{
long pos;
long end;
pos = ftell(h);
if ( pos == EOF )
return EOF;
fseek(h, 0, SEEK_END);
end = ftell(h);
fseek(h, pos, SEEK_SET);
return end;
}
/*
================
FS_filelength
If this is called on a non-unique FILE (from a pak file),
it will return the size of the pak file, not the expected
size of the file.
================
*/
int FS_filelength( fileHandle_t f ) {
FILE *h;
h = FS_FileForHandle(f);
if(h == NULL)
return EOF;
else
return FS_fplength(h);
}
/*
====================
FS_ReplaceSeparators
Fix things up differently for win/unix/mac
====================
*/
void FS_ReplaceSeparators( char *path ) {
char *s;
qboolean lastCharWasSep = qfalse;
for ( s = path ; *s ; s++ ) {
if ( *s == '/' || *s == '\\' ) {
if ( !lastCharWasSep ) {
*s = PATH_SEP;
lastCharWasSep = qtrue;
} else {
memmove (s, s + 1, strlen (s));
}
} else {
lastCharWasSep = qfalse;
}
}
}
/*
===================
FS_BuildOSPath
Qpath may have either forward or backwards slashes
===================
*/
char *FS_BuildOSPath( const char *qpath ) {
char temp[MAX_OSPATH];
static char ospath[4][MAX_OSPATH];
static int toggle;
int nextToggle = (toggle + 1)&3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement)
toggle = nextToggle;
// Fix for filenames that are given to FS with a leading "/" (/botfiles/Foo)
if (qpath[0] == '\\' || qpath[0] == '/')
qpath++;
Com_sprintf( temp, sizeof(temp), "/base/%s", qpath );
FS_ReplaceSeparators( temp );
Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", fs_basepath->string, temp );
return ospath[toggle];
}
char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) {
char temp[MAX_OSPATH];
static char ospath[4][MAX_OSPATH];
static int toggle;
int nextToggle = (toggle + 1)&3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement)
toggle = nextToggle;
if( !game || !game[0] ) {
game = fs_gamedir;
}
Com_sprintf( temp, sizeof(temp), "/%s/%s", game, qpath );
FS_ReplaceSeparators( temp );
Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp );
return ospath[toggle];
}
/*
============
FS_CreatePath
Creates any directories needed to store the given filename
============
*/
qboolean FS_CreatePath (char *OSPath) {
char *ofs;
char path[MAX_OSPATH];
// make absolutely sure that it can't back up the path
// FIXME: is c: allowed???
if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) {
Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath );
return qtrue;
}
Q_strncpyz( path, OSPath, sizeof( path ) );
FS_ReplaceSeparators( path );
// Skip creation of the root directory as it will always be there
ofs = strchr( path, PATH_SEP );
if ( ofs ) {
ofs++;
}
for (; ofs != NULL && *ofs ; ofs++) {
if (*ofs == PATH_SEP) {
// create the directory
*ofs = 0;
if (!Sys_Mkdir (path)) {
Com_Error( ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"",
path );
}
*ofs = PATH_SEP;
}
}
return qfalse;
}
/*
=================
FS_CheckFilenameIsMutable
ERR_FATAL if trying to maniuplate a file with the platform library, or pk3 extension
=================
*/
static void FS_CheckFilenameIsMutable( const char *filename, const char *function )
{
// Check if the filename ends with the library, or pk3 extension
if( COM_CompareExtension( filename, DLL_EXT )
|| COM_CompareExtension( filename, ".pk3" ) )
{
Com_Error( ERR_FATAL, "%s: Not allowed to manipulate '%s' due "
"to %s extension", function, filename, COM_GetExtension( filename ) );
}
}
/*
=================
FS_CopyFile
Copy a fully specified file from one place to another
=================
*/
void FS_CopyFile( char *fromOSPath, char *toOSPath ) {
FILE *f;
int len;
byte *buf;
FS_CheckFilenameIsMutable( fromOSPath, __func__ );
Com_Printf( "copy %s to %s\n", fromOSPath, toOSPath );
if (strstr(fromOSPath, "journal.dat") || strstr(fromOSPath, "journaldata.dat")) {
Com_Printf( "Ignoring journal files\n");
return;
}
f = fopen( fromOSPath, "rb" );
if ( !f ) {
return;
}
fseek (f, 0, SEEK_END);
len = ftell (f);
fseek (f, 0, SEEK_SET);
if ( len == EOF )
{
fclose( f );
Com_Error( ERR_FATAL, "Bad file length in FS_CopyFile()" );
}
// we are using direct malloc instead of Z_Malloc here, so it
// probably won't work on a mac... Its only for developers anyway...
buf = (unsigned char *)malloc( len );
if (fread( buf, 1, len, f ) != (unsigned)len)
{
fclose( f );
free ( buf );
Com_Error( ERR_FATAL, "Short read in FS_Copyfiles()\n" );
}
fclose( f );
if( FS_CreatePath( toOSPath ) ) {
free ( buf );
return;
}
f = fopen( toOSPath, "wb" );
if ( !f ) {
free ( buf );
return;
}
if (fwrite( buf, 1, len, f ) != (unsigned)len)
{
fclose( f );
free ( buf );
Com_Error( ERR_FATAL, "Short write in FS_Copyfiles()\n" );
}
fclose( f );
free( buf );
}
/*
===========
FS_Remove
===========
*/
void FS_Remove( const char *osPath ) {
FS_CheckFilenameIsMutable( osPath, __func__ );
remove( osPath );
}
/*
===========
FS_HomeRemove
===========
*/
void FS_HomeRemove( const char *homePath ) {
FS_CheckFilenameIsMutable( homePath, __func__ );
remove( FS_BuildOSPath( fs_homepath->string,
fs_gamedir, homePath ) );
}
/*
===========
FS_Rmdir
Removes a directory, optionally deleting all files under it
===========
*/
void FS_Rmdir( const char *osPath, qboolean recursive ) {
FS_CheckFilenameIsMutable( osPath, __func__ );
if ( recursive ) {
int numfiles;
int i;
char **filesToRemove = Sys_ListFiles( osPath, "", NULL, &numfiles, qfalse );
for ( i = 0; i < numfiles; i++ ) {
char fileOsPath[MAX_OSPATH];
Com_sprintf( fileOsPath, sizeof( fileOsPath ), "%s/%s", osPath, filesToRemove[i] );
FS_Remove( fileOsPath );
}
FS_FreeFileList( filesToRemove );
char **directoriesToRemove = Sys_ListFiles( osPath, "/", NULL, &numfiles, qfalse );
for ( i = 0; i < numfiles; i++ ) {
if ( !Q_stricmp( directoriesToRemove[i], "." ) || !Q_stricmp( directoriesToRemove[i], ".." ) ) {
continue;
}
char directoryOsPath[MAX_OSPATH];
Com_sprintf( directoryOsPath, sizeof( directoryOsPath ), "%s/%s", osPath, directoriesToRemove[i] );
FS_Rmdir( directoryOsPath, qtrue );
}
FS_FreeFileList( directoriesToRemove );
}
rmdir( osPath );
}
/*
===========
FS_HomeRmdir
Removes a directory, optionally deleting all files under it
===========
*/
void FS_HomeRmdir( const char *homePath, qboolean recursive ) {
FS_CheckFilenameIsMutable( homePath, __func__ );
FS_Rmdir( FS_BuildOSPath( fs_homepath->string,
fs_gamedir, homePath ), recursive );
}
/*
================
FS_FileInPathExists
Tests if path and file exists
================
*/
qboolean FS_FileInPathExists(const char *testpath)
{
FILE *filep;
filep = fopen(testpath, "rb");
if(filep)
{
fclose(filep);
return qtrue;
}
return qfalse;
}
/*
================
FS_FileExists
Tests if the file exists in the current gamedir, this DOES NOT
search the paths. This is to determine if opening a file to write
(which always goes into the current gamedir) will cause any overwrites.
NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards
================
*/
qboolean FS_FileExists( const char *file )
{
return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file));
}
/*
================
FS_SV_FileExists
Tests if the file exists
================
*/
qboolean FS_SV_FileExists( const char *file )
{
char *testpath;
testpath = FS_BuildOSPath( fs_homepath->string, file, "");
testpath[strlen(testpath)-1] = '\0';
return FS_FileInPathExists(testpath);
}
/*
===========
FS_SV_FOpenFileWrite
===========
*/
fileHandle_t FS_SV_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
FS_AssertInitialised();
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileWrite: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = fopen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_SV_FOpenFileRead
search for a file somewhere below the home path, base path or cd path
we search in that order, matching FS_SV_FOpenFileRead order
===========
*/
int FS_SV_FOpenFileRead( const char *filename, fileHandle_t *fp ) {
char *ospath;
fileHandle_t f = 0;
FS_AssertInitialised();
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
S_ClearSoundBuffer();
// search homepath
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
// remove trailing slash
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o)
{
// NOTE TTimo on non *nix systems, fs_homepath == fs_basepath, might want to avoid
if (Q_stricmp(fs_homepath->string,fs_basepath->string))
{
// search basepath
ospath = FS_BuildOSPath( fs_basepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
if ( !fsh[f].handleFiles.file.o )
{
f = 0;
}
}
if (!fsh[f].handleFiles.file.o)
{
// search cd path
ospath = FS_BuildOSPath( fs_cdpath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if (fs_debug->integer)
{
Com_Printf( "FS_SV_FOpenFileRead (fs_cdpath) : %s\n", ospath );
}
fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
fsh[f].handleSync = qfalse;
if ( !fsh[f].handleFiles.file.o )
{
f = 0;
}
}
*fp = f;
if (f) {
return FS_filelength(f);
}
return 0;
}
/*
===========
FS_SV_Rename
===========
*/
void FS_SV_Rename( const char *from, const char *to, qboolean safe ) {
char *from_ospath, *to_ospath;
FS_AssertInitialised();
// don't let sound stutter
S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, from, "" );
to_ospath = FS_BuildOSPath( fs_homepath->string, to, "" );
from_ospath[strlen(from_ospath)-1] = '\0';
to_ospath[strlen(to_ospath)-1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath );
}
if ( safe ) {
FS_CheckFilenameIsMutable( to_ospath, __func__ );
}
if (rename( from_ospath, to_ospath )) {
// Failed, try copying it and deleting the original
FS_CopyFile ( from_ospath, to_ospath );
FS_Remove ( from_ospath );
}
}
/*
===========
FS_Rename
===========
*/
void FS_Rename( const char *from, const char *to ) {
char *from_ospath, *to_ospath;
FS_AssertInitialised();
// don't let sound stutter
S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from );
to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to );
if ( fs_debug->integer ) {
Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath );
}
FS_CheckFilenameIsMutable( to_ospath, __func__ );
if (rename( from_ospath, to_ospath )) {
// Failed, try copying it and deleting the original
FS_CopyFile ( from_ospath, to_ospath );
FS_Remove ( from_ospath );
}
}
/*
===========
FS_FCloseFile
Close a file.
There are three cases handled:
* normal file: closed with fclose.
* file in pak3 archive: subfile is closed with unzCloseCurrentFile, but the
minizip handle to the pak3 remains open.
* file in pak3 archive, opened with "unique" flag: This file did not use
the system minizip handle to the pak3 file, but its own dedicated one.
The dedicated handle is closed with unzClose.
===========
*/
void FS_FCloseFile( fileHandle_t f ) {
FS_AssertInitialised();
if (fsh[f].zipFile == qtrue) {
unzCloseCurrentFile( fsh[f].handleFiles.file.z );
if ( fsh[f].handleFiles.unique ) {
unzClose( fsh[f].handleFiles.file.z );
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
return;
}
// we didn't find it as a pak, so close it as a unique file
if (fsh[f].handleFiles.file.o) {
fclose (fsh[f].handleFiles.file.o);
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
}
/*
===========
FS_FOpenFileWrite
===========
*/
fileHandle_t FS_FOpenFileWrite( const char *filename, qboolean safe ) {
char *ospath;
fileHandle_t f;
FS_AssertInitialised();
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileWrite: %s\n", ospath );
}
if ( safe ) {
FS_CheckFilenameIsMutable( ospath, __func__ );
}
if( FS_CreatePath( ospath ) ) {
return 0;
}
// enabling the following line causes a recursive function call loop
// when running with +set logfile 1 +set developer 1
//Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = fopen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_FOpenFileAppend
===========
*/
fileHandle_t FS_FOpenFileAppend( const char *filename ) {
char *ospath;
fileHandle_t f;
FS_AssertInitialised();
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileAppend: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
fsh[f].handleFiles.file.o = fopen( ospath, "ab" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_FilenameCompare
Ignore case and separator char distinctions
===========
*/
qboolean FS_FilenameCompare( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if (c1 >= 'a' && c1 <= 'z') {
c1 -= ('a' - 'A');
}
if (c2 >= 'a' && c2 <= 'z') {
c2 -= ('a' - 'A');
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if (c1 != c2) {
return qtrue; // strings not equal
}
} while (c1);
return qfalse; // strings are equal
}
/*
===========
FS_IsExt
Return qtrue if ext matches file extension filename
===========
*/
qboolean FS_IsExt(const char *filename, const char *ext, int namelen)
{
int extlen;
extlen = strlen(ext);
if(extlen > namelen)
return qfalse;
filename += namelen - extlen;
return (qboolean)!Q_stricmp(filename, ext);
}
/*
===========
FS_IsDemoExt
Return qtrue if filename has a demo extension
===========
*/
#define DEMO_EXTENSION "dm_"
qboolean FS_IsDemoExt(const char *filename, int namelen)
{
const char *ext_test;
ext_test = strrchr(filename, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMO_EXTENSION, ARRAY_LEN(DEMO_EXTENSION) - 1))
{
int protocol = atoi(ext_test + ARRAY_LEN(DEMO_EXTENSION));
if(protocol == PROTOCOL_VERSION)
return qtrue;
}
return qfalse;
}
#ifdef _WIN32
bool Sys_GetFileTime(LPCSTR psFileName, FILETIME &ft)
{
bool bSuccess = false;
HANDLE hFile = INVALID_HANDLE_VALUE;
hFile = CreateFile( psFileName, // LPCTSTR lpFileName, // pointer to name of the file
GENERIC_READ, // DWORD dwDesiredAccess, // access (read-write) mode
FILE_SHARE_READ, // DWORD dwShareMode, // share mode
NULL, // LPSECURITY_ATTRIBUTES lpSecurityAttributes, // pointer to security attributes
OPEN_EXISTING, // DWORD dwCreationDisposition, // how to create
FILE_FLAG_NO_BUFFERING,// DWORD dwFlagsAndAttributes, // file attributes
NULL // HANDLE hTemplateFile // handle to file with attributes to
);
if (hFile != INVALID_HANDLE_VALUE)
{
if (GetFileTime(hFile, // handle to file
NULL, // LPFILETIME lpCreationTime
NULL, // LPFILETIME lpLastAccessTime
&ft // LPFILETIME lpLastWriteTime
)
)
{
bSuccess = true;
}
CloseHandle(hFile);
}
return bSuccess;
}
bool Sys_FileOutOfDate( LPCSTR psFinalFileName /* dest */, LPCSTR psDataFileName /* src */ )
{
FILETIME ftFinalFile, ftDataFile;
if (Sys_GetFileTime(psFinalFileName, ftFinalFile) && Sys_GetFileTime(psDataFileName, ftDataFile))
{
// timer res only accurate to within 2 seconds on FAT, so can't do exact compare...
//
//LONG l = CompareFileTime( &ftFinalFile, &ftDataFile );
if ( (fabs((double)(ftFinalFile.dwLowDateTime - ftDataFile.dwLowDateTime)) <= 20000000 ) &&
ftFinalFile.dwHighDateTime == ftDataFile.dwHighDateTime
)
{
return false; // file not out of date, ie use it.
}
return true; // flag return code to copy over a replacement version of this file
}
// extra error check, report as suspicious if you find a file locally but not out on the net.,.
//
if (com_developer->integer)
{
if (!Sys_GetFileTime(psDataFileName, ftDataFile))
{
Com_Printf( "Sys_FileOutOfDate: reading %s but it's not on the net!\n", psFinalFileName);
}
}
return false;
}
#endif // _WIN32
bool FS_FileCacheable(const char* const filename)
{
extern cvar_t *com_buildScript;
if (com_buildScript && com_buildScript->integer)
{
return true;
}
return( strchr(filename, '/') != 0 );
}
/*
===========
FS_FOpenFileRead
Finds the file in the search path.
Returns filesize and an open FILE pointer.
Used for streaming data out of either a
separate file or a ZIP file.
===========
*/
extern qboolean com_fullyInitialized;
long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean uniqueFILE ) {
searchpath_t *search;
char *netpath;
pack_t *pak;
fileInPack_t *pakFile;
directory_t *dir;
long hash;
//unz_s *zfi;
//void *temp;
int l;
hash = 0;
FS_AssertInitialised();
if ( file == NULL ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'file' parameter passed\n" );
}
if ( !filename ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" );
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
*file = 0;
return -1;
}
// make sure the q3key file is only readable by the quake3.exe at initialization
// any other time the key should only be accessed in memory using the provided functions
if( com_fullyInitialized && strstr( filename, "q3key" ) ) {
*file = 0;
return -1;
}
//
// search through the path, one element at a time
//
*file = FS_HandleForFile();
fsh[*file].handleFiles.unique = uniqueFILE;
// this new bool is in for an optimisation, if you (eg) opened a BSP file under fs_copyfiles==2,
// then it triggered a copy operation to update your local HD version, then this will re-open the
// file handle on your local version, not the net build. This uses a bit more CPU to re-do the loop
// logic, but should read faster than accessing the net version a second time.
//
qboolean bFasterToReOpenUsingNewLocalFile = qfalse;
do
{
bFasterToReOpenUsingNewLocalFile = qfalse;
for ( search = fs_searchpaths ; search ; search = search->next ) {
//
if ( search->pack ) {
hash = FS_HashFileName(filename, search->pack->hashSize);
}
// is the element a pak file?
if ( search->pack && search->pack->hashTable[hash] ) {
// disregard if it doesn't match one of the allowed pure pak files
if ( !FS_PakIsPure(search->pack) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
// found it!
// mark the pak as having been referenced and mark specifics on cgame and ui
// shaders, txt, arena files by themselves do not count as a reference as
// these are loaded from all pk3s
// from every pk3 file..
// The x86.dll suffixes are needed in order for sv_pure to continue to
// work on non-x86/windows systems...
l = strlen( filename );
if ( !(pak->referenced & FS_GENERAL_REF)) {
if( !FS_IsExt(filename, ".shader", l) &&
!FS_IsExt(filename, ".txt", l) &&
!FS_IsExt(filename, ".str", l) &&
!FS_IsExt(filename, ".cfg", l) &&
!FS_IsExt(filename, ".config", l) &&
!FS_IsExt(filename, ".bot", l) &&
!FS_IsExt(filename, ".arena", l) &&
!FS_IsExt(filename, ".menu", l) &&
!FS_IsExt(filename, ".fcf", l) &&
Q_stricmp(filename, "jampgamex86.dll") != 0 &&
//Q_stricmp(filename, "vm/qagame.qvm") != 0 &&
!strstr(filename, "levelshots"))
{
pak->referenced |= FS_GENERAL_REF;
}
}
if (!(pak->referenced & FS_CGAME_REF))
{
if ( Q_stricmp( filename, "cgame.qvm" ) == 0 ||
Q_stricmp( filename, "cgamex86.dll" ) == 0 )
{
pak->referenced |= FS_CGAME_REF;
}
}
if (!(pak->referenced & FS_UI_REF))
{
if ( Q_stricmp( filename, "ui.qvm" ) == 0 ||
Q_stricmp( filename, "uix86.dll" ) == 0 )
{
pak->referenced |= FS_UI_REF;
}
}
if ( uniqueFILE ) {
// open a new file on the pakfile
fsh[*file].handleFiles.file.z = unzOpen (pak->pakFilename);
if (fsh[*file].handleFiles.file.z == NULL) {
Com_Error (ERR_FATAL, "Couldn't open %s", pak->pakFilename);
}
} else {
fsh[*file].handleFiles.file.z = pak->handle;
}
Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) );
fsh[*file].zipFile = qtrue;
// set the file position in the zip file (also sets the current file info)
unzSetOffset(fsh[*file].handleFiles.file.z, pakFile->pos);
// open the file in the zip
unzOpenCurrentFile(fsh[*file].handleFiles.file.z);
#if 0
zfi = (unz_s *)fsh[*file].handleFiles.file.z;
// in case the file was new
temp = zfi->filestream;
// set the file position in the zip file (also sets the current file info)
unzSetOffset(pak->handle, pakFile->pos);
// copy the file info into the unzip structure
Com_Memcpy( zfi, pak->handle, sizeof(unz_s) );
// we copy this back into the structure
zfi->filestream = temp;
// open the file in the zip
unzOpenCurrentFile( fsh[*file].handleFiles.file.z );
#endif
fsh[*file].zipFilePos = pakFile->pos;
fsh[*file].zipFileLen = pakFile->len;
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileRead: %s (found in '%s')\n",
filename, pak->pakFilename );
}
#ifndef DEDICATED
#ifndef FINAL_BUILD
// Check for unprecached files when in game but not in the menus
if((cls.state == CA_ACTIVE) && !(Key_GetCatcher( ) & KEYCATCH_UI))
{
Com_Printf(S_COLOR_YELLOW "WARNING: File %s not precached\n", filename);
}
#endif
#endif // DEDICATED
return pakFile->len;
}
pakFile = pakFile->next;
} while(pakFile != NULL);
} else if ( search->dir ) {
// check a file in the directory tree
// if we are running restricted, the only files we
// will allow to come from the directory are .cfg files
l = strlen( filename );
// FIXME TTimo I'm not sure about the fs_numServerPaks test
// if you are using FS_ReadFile to find out if a file exists,
// this test can make the search fail although the file is in the directory
// I had the problem on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8
// turned out I used FS_FileExists instead
if ( fs_numServerPaks ) {
if ( !FS_IsExt( filename, ".cfg", l ) && // for config files
!FS_IsExt( filename, ".fcf", l ) && // force configuration files
!FS_IsExt( filename, ".menu", l ) && // menu files
!FS_IsExt( filename, ".game", l ) && // menu files
!FS_IsExt( filename, ".dat", l ) && // for journal files
!FS_IsDemoExt( filename, l ) ) { // demos
continue;
}
}
dir = search->dir;
netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename );
fsh[*file].handleFiles.file.o = fopen (netpath, "rb");
if ( !fsh[*file].handleFiles.file.o ) {
continue;
}
if ( !FS_IsExt( filename, ".cfg", l ) && // for config files
!FS_IsExt( filename, ".fcf", l ) && // force configuration files
!FS_IsExt( filename, ".menu", l ) && // menu files
!FS_IsExt( filename, ".game", l ) && // menu files
!FS_IsExt( filename, ".dat", l ) && // for journal files
!FS_IsDemoExt( filename, l ) ) { // demos
fs_fakeChkSum = Q_flrand(0.0f, 1.0f);
}
#ifdef _WIN32
// if running with fs_copyfiles 2, and search path == local, then we need to fail to open
// if the time/date stamp != the network version (so it'll loop round again and use the network path,
// which comes later in the search order)
//
if ( fs_copyfiles->integer == 2 && fs_cdpath->string[0] && !Q_stricmp( dir->path, fs_basepath->string )
&& FS_FileCacheable(filename) )
{
if ( Sys_FileOutOfDate( netpath, FS_BuildOSPath( fs_cdpath->string, dir->gamedir, filename ) ))
{
fclose(fsh[*file].handleFiles.file.o);
fsh[*file].handleFiles.file.o = 0;
continue; //carry on to find the cdpath version.
}
}
#endif
Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) );
fsh[*file].zipFile = qfalse;
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename,
dir->path, PATH_SEP, dir->gamedir );
}
#ifdef _WIN32
// if we are getting it from the cdpath, optionally copy it
// to the basepath
if ( fs_copyfiles->integer && !Q_stricmp( dir->path, fs_cdpath->string ) ) {
char *copypath;
copypath = FS_BuildOSPath( fs_basepath->string, dir->gamedir, filename );
switch ( fs_copyfiles->integer )
{
default:
case 1:
{
FS_CopyFile( netpath, copypath );
}
break;
case 2:
{
if (FS_FileCacheable(filename) )
{
// maybe change this to Com_DPrintf? On the other hand...
//
Com_Printf( "fs_copyfiles(2), Copying: %s to %s\n", netpath, copypath );
FS_CreatePath( copypath );
bool bOk = true;
if (!CopyFile( netpath, copypath, FALSE ))
{
DWORD dwAttrs = GetFileAttributes(copypath);
SetFileAttributes(copypath, dwAttrs & ~FILE_ATTRIBUTE_READONLY);
bOk = !!CopyFile( netpath, copypath, FALSE );
}
if (bOk)
{
// clear this handle and setup for re-opening of the new local copy...
//
bFasterToReOpenUsingNewLocalFile = qtrue;
fclose(fsh[*file].handleFiles.file.o);
fsh[*file].handleFiles.file.o = NULL;
}
}
}
break;
}
}
#endif
if (bFasterToReOpenUsingNewLocalFile)
{
break; // and re-read the local copy, not the net version
}
#ifndef DEDICATED
#ifndef FINAL_BUILD
// Check for unprecached files when in game but not in the menus
if((cls.state == CA_ACTIVE) && !(Key_GetCatcher( ) & KEYCATCH_UI))
{
Com_Printf(S_COLOR_YELLOW "WARNING: File %s not precached\n", filename);
}
#endif
#endif // dedicated
return FS_fplength(fsh[*file].handleFiles.file.o);
}
}
}
while ( bFasterToReOpenUsingNewLocalFile );
Com_DPrintf ("Can't find %s\n", filename);
#ifdef FS_MISSING
if (missingFiles) {
fprintf(missingFiles, "%s\n", filename);
}
#endif
*file = 0;
return -1;
}
// This is a bit of a hack but it is used for other OS'/arch to still be acceptable with pure servers.
// Intentionally looking for x86.dll because this is all that exists in pk3s.
qboolean FS_FindPureDLL(const char *name)
{
char dllName[MAX_OSPATH];
fileHandle_t h;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
if ( !Cvar_VariableValue( "sv_pure" ) )
return qtrue;
Com_sprintf(dllName, sizeof(dllName), "%sx86.dll", name);
if(FS_FOpenFileRead(dllName, &h, qtrue) > 0)
{
FS_FCloseFile( h );
return qtrue;
}
return qfalse;
}
/*
=================
FS_Read
Properly handles partial reads
=================
*/
int FS_Read( void *buffer, int len, fileHandle_t f ) {
int block, remaining;
int read;
byte *buf;
int tries;
FS_AssertInitialised();
if ( !f ) {
return 0;
}
buf = (byte *)buffer;
fs_readCount += len;
if (fsh[f].zipFile == qfalse) {
remaining = len;
tries = 0;
while (remaining) {
block = remaining;
read = fread (buf, 1, block, fsh[f].handleFiles.file.o);
if (read == 0) {
// we might have been trying to read from a CD, which
// sometimes returns a 0 read on windows
if (!tries) {
tries = 1;
} else {
return len-remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read");
}
}
if (read == -1) {
Com_Error (ERR_FATAL, "FS_Read: -1 bytes read");
}
remaining -= read;
buf += read;
}
return len;
} else {
return unzReadCurrentFile(fsh[f].handleFiles.file.z, buffer, len);
}
}
/*
=================
FS_Write
Properly handles partial writes
=================
*/
int FS_Write( const void *buffer, int len, fileHandle_t h ) {
int block, remaining;
int written;
byte *buf;
int tries;
FILE *f;
FS_AssertInitialised();
if ( !h ) {
return 0;
}
f = FS_FileForHandle(h);
buf = (byte *)buffer;
remaining = len;
tries = 0;
while (remaining) {
block = remaining;
written = fwrite (buf, 1, block, f);
if (written == 0) {
if (!tries) {
tries = 1;
} else {
Com_Printf( "FS_Write: 0 bytes written\n" );
return 0;
}
}
if (written == -1) {
Com_Printf( "FS_Write: -1 bytes written\n" );
return 0;
}
remaining -= written;
buf += written;
}
if ( fsh[h].handleSync ) {
fflush( f );
}
return len;
}
void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start (argptr,fmt);
Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
va_end (argptr);
FS_Write(msg, strlen(msg), h);
}
#define PK3_SEEK_BUFFER_SIZE 65536
/*
=================
FS_Seek
=================
*/
int FS_Seek( fileHandle_t f, long offset, int origin ) {
int _origin;
FS_AssertInitialised();
if (fsh[f].zipFile == qtrue) {
//FIXME: this is really, really crappy
//(but better than what was here before)
byte buffer[PK3_SEEK_BUFFER_SIZE];
int remainder;
int currentPosition = FS_FTell( f );
// change negative offsets into FS_SEEK_SET
if ( offset < 0 ) {
switch( origin ) {
case FS_SEEK_END:
remainder = fsh[f].zipFileLen + offset;
break;
case FS_SEEK_CUR:
remainder = currentPosition + offset;
break;
case FS_SEEK_SET:
default:
remainder = 0;
break;
}
if ( remainder < 0 ) {
remainder = 0;
}
origin = FS_SEEK_SET;
} else {
if ( origin == FS_SEEK_END ) {
remainder = fsh[f].zipFileLen - currentPosition + offset;
} else {
remainder = offset;
}
}
switch( origin ) {
case FS_SEEK_SET:
if ( remainder == currentPosition ) {
return offset;
}
unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
unzOpenCurrentFile(fsh[f].handleFiles.file.z);
//fallthrough
case FS_SEEK_END:
case FS_SEEK_CUR:
while( remainder > PK3_SEEK_BUFFER_SIZE ) {
FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f );
remainder -= PK3_SEEK_BUFFER_SIZE;
}
FS_Read( buffer, remainder, f );
return offset;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
return -1;
}
} else {
FILE *file;
file = FS_FileForHandle(f);
switch( origin ) {
case FS_SEEK_CUR:
_origin = SEEK_CUR;
break;
case FS_SEEK_END:
_origin = SEEK_END;
break;
case FS_SEEK_SET:
_origin = SEEK_SET;
break;
default:
_origin = SEEK_CUR;
Com_Error( ERR_FATAL, "Bad origin in FS_Seek\n" );
break;
}
return fseek( file, offset, _origin );
}
}
/*
======================================================================================
CONVENIENCE FUNCTIONS FOR ENTIRE FILES
======================================================================================
*/
int FS_FileIsInPAK(const char *filename, int *pChecksum ) {
searchpath_t *search;
pack_t *pak;
fileInPack_t *pakFile;
long hash = 0;
FS_AssertInitialised();
if ( !filename ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" );
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
return -1;
}
//
// search through the path, one element at a time
//
for ( search = fs_searchpaths ; search ; search = search->next ) {
//
if (search->pack) {
hash = FS_HashFileName(filename, search->pack->hashSize);
}
// is the element a pak file?
if ( search->pack && search->pack->hashTable[hash] ) {
// disregard if it doesn't match one of the allowed pure pak files
if ( !FS_PakIsPure(search->pack) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
if (pChecksum) {
*pChecksum = pak->pure_checksum;
}
return 1;
}
pakFile = pakFile->next;
} while(pakFile != NULL);
}
}
return -1;
}
/*
============
FS_ReadFile
Filename are relative to the quake search path
a null buffer will just return the file length without loading
============
*/
long FS_ReadFile( const char *qpath, void **buffer ) {
fileHandle_t h;
byte* buf;
qboolean isConfig;
long len;
FS_AssertInitialised();
if ( !qpath || !qpath[0] ) {
Com_Error( ERR_FATAL, "FS_ReadFile with empty name\n" );
}
buf = NULL; // quiet compiler warning
// if this is a .cfg file and we are playing back a journal, read
// it from the journal file
if ( strstr( qpath, ".cfg" ) ) {
isConfig = qtrue;
if ( com_journal && com_journal->integer == 2 ) {
int r;
Com_DPrintf( "Loading %s from journal file.\n", qpath );
r = FS_Read( &len, sizeof( len ), com_journalDataFile );
if ( r != sizeof( len ) ) {
if (buffer != NULL) *buffer = NULL;
return -1;
}
// if the file didn't exist when the journal was created
if (!len) {
if (buffer == NULL) {
return 1; // hack for old journal files
}
*buffer = NULL;
return -1;
}
if (buffer == NULL) {
return len;
}
buf = (unsigned char *)Hunk_AllocateTempMemory(len+1);
*buffer = buf;
r = FS_Read( buf, len, com_journalDataFile );
if ( r != len ) {
Com_Error( ERR_FATAL, "Read from journalDataFile failed" );
}
fs_loadCount++;
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
return len;
}
} else {
isConfig = qfalse;
}
// look for it in the filesystem or pack files
len = FS_FOpenFileRead( qpath, &h, qfalse );
if ( h == 0 ) {
if ( buffer ) {
*buffer = NULL;
}
// if we are journalling and it is a config file, write a zero to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing zero for %s to journal file.\n", qpath );
len = 0;
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return -1;
}
if ( !buffer ) {
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing len for %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
FS_FCloseFile( h);
return len;
}
fs_loadCount++;
buf = (byte*)Z_Malloc( len+1, TAG_FILESYS, qfalse);
buf[len]='\0'; // because we're not calling Z_Malloc with optional trailing 'bZeroIt' bool
*buffer = buf;
// Z_Label(buf, qpath);
FS_Read (buf, len, h);
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
FS_FCloseFile( h );
// if we are journalling and it is a config file, write it to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Write( buf, len, com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return len;
}
/*
=============
FS_FreeFile
=============
*/
void FS_FreeFile( void *buffer ) {
FS_AssertInitialised();
if ( !buffer ) {
Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" );
}
Z_Free( buffer );
}
/*
============
FS_WriteFile
Filename are reletive to the quake search path
============
*/
void FS_WriteFile( const char *qpath, const void *buffer, int size ) {
fileHandle_t f;
FS_AssertInitialised();
if ( !qpath || !buffer ) {
Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" );
}
f = FS_FOpenFileWrite( qpath );
if ( !f ) {
Com_Printf( "Failed to open %s\n", qpath );
return;
}
FS_Write( buffer, size, f );
FS_FCloseFile( f );
}
/*
==========================================================================
ZIP FILE LOADING
==========================================================================
*/
/*
=================
FS_LoadZipFile
Creates a new pak_t in the search chain for the contents
of a zip file.
=================
*/
static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename )
{
fileInPack_t *buildBuffer;
pack_t *pack;
unzFile uf;
int err;
unz_global_info gi;
char filename_inzip[MAX_ZPATH];
unz_file_info file_info;
int len;
size_t i;
long hash;
int fs_numHeaderLongs;
int *fs_headerLongs;
char *namePtr;
fs_numHeaderLongs = 0;
uf = unzOpen(zipfile);
err = unzGetGlobalInfo (uf,&gi);
if (err != UNZ_OK)
return NULL;
len = 0;
unzGoToFirstFile(uf);
for (i = 0; i < gi.number_entry; i++)
{
err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
if (err != UNZ_OK) {
break;
}
len += strlen(filename_inzip) + 1;
unzGoToNextFile(uf);
}
buildBuffer = (struct fileInPack_s *)Z_Malloc( (gi.number_entry * sizeof( fileInPack_t )) + len, TAG_FILESYS, qtrue );
namePtr = ((char *) buildBuffer) + gi.number_entry * sizeof( fileInPack_t );
fs_headerLongs = (int *)Z_Malloc( ( gi.number_entry + 1 ) * sizeof(int), TAG_FILESYS, qtrue );
fs_headerLongs[ fs_numHeaderLongs++ ] = LittleLong( fs_checksumFeed );
// get the hash table size from the number of files in the zip
// because lots of custom pk3 files have less than 32 or 64 files
for (i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1) {
if (i > gi.number_entry) {
break;
}
}
pack = (pack_t *)Z_Malloc( sizeof( pack_t ) + i * sizeof(fileInPack_t *), TAG_FILESYS, qtrue );
pack->hashSize = i;
pack->hashTable = (fileInPack_t **) (((char *) pack) + sizeof( pack_t ));
for(int j = 0; j < pack->hashSize; j++) {
pack->hashTable[j] = NULL;
}
Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) );
Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) );
// strip .pk3 if needed
if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) {
pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0;
}
pack->handle = uf;
pack->numfiles = gi.number_entry;
unzGoToFirstFile(uf);
for (i = 0; i < gi.number_entry; i++)
{
err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
if (err != UNZ_OK) {
break;
}
if (file_info.uncompressed_size > 0) {
fs_headerLongs[fs_numHeaderLongs++] = LittleLong(file_info.crc);
}
Q_strlwr( filename_inzip );
hash = FS_HashFileName(filename_inzip, pack->hashSize);
buildBuffer[i].name = namePtr;
strcpy( buildBuffer[i].name, filename_inzip );
namePtr += strlen(filename_inzip) + 1;
// store the file position in the zip
buildBuffer[i].pos = unzGetOffset(uf);
buildBuffer[i].len = file_info.uncompressed_size;
buildBuffer[i].next = pack->hashTable[hash];
pack->hashTable[hash] = &buildBuffer[i];
unzGoToNextFile(uf);
}
pack->checksum = Com_BlockChecksum( &fs_headerLongs[ 1 ], sizeof(*fs_headerLongs) * ( fs_numHeaderLongs - 1 ) );
pack->pure_checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs );
pack->checksum = LittleLong( pack->checksum );
pack->pure_checksum = LittleLong( pack->pure_checksum );
Z_Free(fs_headerLongs);
pack->buildBuffer = buildBuffer;
return pack;
}
/*
=================
FS_FreePak
Frees a pak structure and releases all associated resources
=================
*/
void FS_FreePak(pack_t *thepak)
{
unzClose(thepak->handle);
Z_Free(thepak->buildBuffer);
Z_Free(thepak);
}
/*
=================
FS_GetZipChecksum
Compares whether the given pak file matches a referenced checksum
=================
*/
qboolean FS_CompareZipChecksum(const char *zipfile)
{
pack_t *thepak;
int index, checksum;
thepak = FS_LoadZipFile(zipfile, "");
if(!thepak)
return qfalse;
checksum = thepak->checksum;
FS_FreePak(thepak);
for(index = 0; index < fs_numServerReferencedPaks; index++)
{
if(checksum == fs_serverReferencedPaks[index])
return qtrue;
}
return qfalse;
}
/*
=================================================================================
DIRECTORY SCANNING FUNCTIONS
=================================================================================
*/
#define MAX_FOUND_FILES 0x1000
static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) {
int len, at, newdep;
newdep = 0;
zpath[0] = 0;
len = 0;
at = 0;
while(zname[at] != 0)
{
if (zname[at]=='/' || zname[at]=='\\') {
len = at;
newdep++;
}
at++;
}
strcpy(zpath, zname);
zpath[len] = 0;
*depth = newdep;
return len;
}
/*
==================
FS_AddFileToList
==================
*/
static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) {
int i;
if ( nfiles == MAX_FOUND_FILES - 1 ) {
return nfiles;
}
for ( i = 0 ; i < nfiles ; i++ ) {
if ( !Q_stricmp( name, list[i] ) ) {
return nfiles; // allready in list
}
}
list[nfiles] = CopyString( name );
nfiles++;
return nfiles;
}
/*
===============
FS_ListFilteredFiles
Returns a uniqued list of files that match the given criteria
from all search paths
===============
*/
char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles ) {
int nfiles;
char **listCopy;
char *list[MAX_FOUND_FILES];
searchpath_t *search;
int i;
int pathLength;
int extensionLength;
int length, pathDepth, temp;
pack_t *pak;
fileInPack_t *buildBuffer;
char zpath[MAX_ZPATH];
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
}
if ( !path ) {
*numfiles = 0;
return NULL;
}
if ( !extension ) {
extension = "";
}
pathLength = strlen( path );
if ( path[pathLength-1] == '\\' || path[pathLength-1] == '/' ) {
pathLength--;
}
extensionLength = strlen( extension );
nfiles = 0;
FS_ReturnPath(path, zpath, &pathDepth);
//
// search through the path, one element at a time, adding to list
//
for (search = fs_searchpaths ; search ; search = search->next) {
// is the element a pak file?
if (search->pack) {
//ZOID: If we are pure, don't search for files on paks that
// aren't on the pure list
if ( !FS_PakIsPure(search->pack) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
buildBuffer = pak->buildBuffer;
for (i = 0; i < pak->numfiles; i++) {
char *name;
int zpathLen, depth;
// check for directory match
name = buildBuffer[i].name;
//
if (filter) {
// case insensitive
if (!Com_FilterPath( filter, name, qfalse ))
continue;
// unique the match
nfiles = FS_AddFileToList( name, list, nfiles );
}
else {
zpathLen = FS_ReturnPath(name, zpath, &depth);
if ( (depth-pathDepth)>2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) {
continue;
}
// check for extension match
length = strlen( name );
if ( length < extensionLength ) {
continue;
}
if ( Q_stricmp( name + length - extensionLength, extension ) ) {
continue;
}
// unique the match
temp = pathLength;
if (pathLength) {
temp++; // include the '/'
}
nfiles = FS_AddFileToList( name + temp, list, nfiles );
}
}
} else if (search->dir) { // scan for files in the filesystem
char *netpath;
int numSysFiles;
char **sysFiles;
char *name;
// don't scan directories for files if we are pure or restricted
if ( fs_numServerPaks &&
(!extension || Q_stricmp(extension, "fcf")) )
{
//rww - allow scanning for fcf files outside of pak even if pure
continue;
}
else
{
netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path );
sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse );
for ( i = 0 ; i < numSysFiles ; i++ ) {
// unique the match
name = sysFiles[i];
nfiles = FS_AddFileToList( name, list, nfiles );
}
Sys_FreeFileList( sysFiles );
}
}
}
// return a copy of the list
*numfiles = nfiles;
if ( !nfiles ) {
return NULL;
}
listCopy = (char **)Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ), TAG_FILESYS );
for ( i = 0 ; i < nfiles ; i++ ) {
listCopy[i] = list[i];
}
listCopy[i] = NULL;
return listCopy;
}
/*
=================
FS_ListFiles
=================
*/
char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) {
return FS_ListFilteredFiles( path, extension, NULL, numfiles );
}
/*
=================
FS_FreeFileList
=================
*/
void FS_FreeFileList( char **fileList ) {
//rwwRMG - changed to fileList to not conflict with list type
int i;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
}
if ( !fileList ) {
return;
}
for ( i = 0 ; fileList[i] ; i++ ) {
Z_Free( fileList[i] );
}
Z_Free( fileList );
}
/*
================
FS_GetFileList
================
*/
int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
int nFiles, i, nTotal, nLen;
char **pFiles = NULL;
*listbuf = 0;
nFiles = 0;
nTotal = 0;
if (Q_stricmp(path, "$modlist") == 0) {
return FS_GetModList(listbuf, bufsize);
}
pFiles = FS_ListFiles(path, extension, &nFiles);
for (i =0; i < nFiles; i++) {
nLen = strlen(pFiles[i]) + 1;
if (nTotal + nLen + 1 < bufsize) {
strcpy(listbuf, pFiles[i]);
listbuf += nLen;
nTotal += nLen;
}
else {
nFiles = i;
break;
}
}
FS_FreeFileList(pFiles);
return nFiles;
}
/*
=======================
Sys_ConcatenateFileLists
mkv: Naive implementation. Concatenates three lists into a
new list, and frees the old lists from the heap.
bk001129 - from cvs1.17 (mkv)
FIXME TTimo those two should move to common.c next to Sys_ListFiles
=======================
*/
static unsigned int Sys_CountFileList(char **fileList)
{
int i = 0;
if (fileList)
{
while (*fileList)
{
fileList++;
i++;
}
}
return i;
}
static char** Sys_ConcatenateFileLists( char **list0, char **list1, char **list2 )
{
int totalLength = 0;
char** cat = NULL, **dst, **src;
totalLength += Sys_CountFileList(list0);
totalLength += Sys_CountFileList(list1);
totalLength += Sys_CountFileList(list2);
/* Create new list. */
dst = cat = (char **)Z_Malloc( ( totalLength + 1 ) * sizeof( char* ), TAG_FILESYS, qtrue );
/* Copy over lists. */
if (list0) {
for (src = list0; *src; src++, dst++)
*dst = *src;
}
if (list1) {
for (src = list1; *src; src++, dst++)
*dst = *src;
}
if (list2) {
for (src = list2; *src; src++, dst++)
*dst = *src;
}
// Terminate the list
*dst = NULL;
// Free our old lists.
// NOTE: not freeing their content, it's been merged in dst and still being used
if (list0) Z_Free( list0 );
if (list1) Z_Free( list1 );
if (list2) Z_Free( list2 );
return cat;
}
//#endif
// For base game mod listing
const char *SE_GetString( const char *psPackageAndStringReference );
/*
================
FS_GetModList
Returns a list of mod directory names
A mod directory is a peer to base with a pk3 in it
The directories are searched in base path, cd path and home path
================
*/
int FS_GetModList( char *listbuf, int bufsize ) {
int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen;
char **pFiles = NULL;
char **pPaks = NULL;
char *name, *path;
char descPath[MAX_OSPATH];
fileHandle_t descHandle;
int dummy;
char **pFiles0 = NULL;
char **pFiles1 = NULL;
char **pFiles2 = NULL;
qboolean bDrop = qfalse;
*listbuf = 0;
nMods = nPotential = nTotal = 0;
pFiles0 = Sys_ListFiles( fs_homepath->string, NULL, NULL, &dummy, qtrue );
pFiles1 = Sys_ListFiles( fs_basepath->string, NULL, NULL, &dummy, qtrue );
pFiles2 = Sys_ListFiles( fs_cdpath->string, NULL, NULL, &dummy, qtrue );
// we searched for mods in the three paths
// it is likely that we have duplicate names now, which we will cleanup below
pFiles = Sys_ConcatenateFileLists( pFiles0, pFiles1, pFiles2 );
nPotential = Sys_CountFileList(pFiles);
for ( i = 0 ; i < nPotential ; i++ ) {
name = pFiles[i];
// NOTE: cleaner would involve more changes
// ignore duplicate mod directories
if (i!=0) {
bDrop = qfalse;
for(j=0; j<i; j++)
{
if (Q_stricmp(pFiles[j],name)==0) {
// this one can be dropped
bDrop = qtrue;
break;
}
}
}
if (bDrop) {
continue;
}
// we drop "." and ".."
if (Q_stricmpn(name, ".", 1)) {
// now we need to find some .pk3 files to validate the mod
// NOTE TTimo: (actually I'm not sure why .. what if it's a mod under developement with no .pk3?)
// we didn't keep the information when we merged the directory names, as to what OS Path it was found under
// so it could be in base path, cd path or home path
// we will try each three of them here (yes, it's a bit messy)
path = FS_BuildOSPath( fs_basepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse);
Sys_FreeFileList( pPaks ); // we only use Sys_ListFiles to check wether .pk3 files are present
/* Try on cd path */
if( nPaks <= 0 ) {
path = FS_BuildOSPath( fs_cdpath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
/* try on home path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_homepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
if (nPaks > 0) {
bool isBase = !Q_stricmp( name, BASEGAME );
nLen = isBase ? 1 : strlen(name) + 1;
// nLen is the length of the mod path
// we need to see if there is a description available
descPath[0] = '\0';
strcpy(descPath, name);
strcat(descPath, "/description.txt");
nDescLen = FS_SV_FOpenFileRead( descPath, &descHandle );
if ( nDescLen > 0 && descHandle) {
FILE *file;
file = FS_FileForHandle(descHandle);
Com_Memset( descPath, 0, sizeof( descPath ) );
nDescLen = fread(descPath, 1, 48, file);
if (nDescLen >= 0) {
descPath[nDescLen] = '\0';
}
FS_FCloseFile(descHandle);
} else if ( isBase ) {
strcpy(descPath, SE_GetString("MENUS_JEDI_ACADEMY"));
} else {
strcpy(descPath, name);
}
nDescLen = strlen(descPath) + 1;
if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) {
if ( isBase )
strcpy(listbuf, "");
else
strcpy(listbuf, name);
listbuf += nLen;
strcpy(listbuf, descPath);
listbuf += nDescLen;
nTotal += nLen + nDescLen;
nMods++;
}
else {
break;
}
}
}
}
Sys_FreeFileList( pFiles );
return nMods;
}
//============================================================================
/*
================
FS_Dir_f
================
*/
void FS_Dir_f( void ) {
char *path;
char *extension;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) {
Com_Printf( "usage: dir <directory> [extension]\n" );
return;
}
if ( Cmd_Argc() == 2 ) {
path = Cmd_Argv( 1 );
extension = "";
} else {
path = Cmd_Argv( 1 );
extension = Cmd_Argv( 2 );
}
Com_Printf( "Directory of %s %s\n", path, extension );
Com_Printf( "---------------\n" );
dirnames = FS_ListFiles( path, extension, &ndirs );
for ( i = 0; i < ndirs; i++ ) {
Com_Printf( "%s\n", dirnames[i] );
}
FS_FreeFileList( dirnames );
}
/*
===========
FS_ConvertPath
===========
*/
void FS_ConvertPath( char *s ) {
while (*s) {
if ( *s == '\\' || *s == ':' ) {
*s = '/';
}
s++;
}
}
/*
===========
FS_PathCmp
Ignore case and separator char distinctions
===========
*/
int FS_PathCmp( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if (c1 >= 'a' && c1 <= 'z') {
c1 -= ('a' - 'A');
}
if (c2 >= 'a' && c2 <= 'z') {
c2 -= ('a' - 'A');
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if (c1 < c2) {
return -1; // strings not equal
}
if (c1 > c2) {
return 1;
}
} while (c1);
return 0; // strings are equal
}
/*
================
FS_SortFileList
================
*/
void FS_SortFileList(char **filelist, int numfiles) {
int i, j, k, numsortedfiles;
char **sortedlist;
sortedlist = (char **)Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ), TAG_FILESYS, qtrue );
sortedlist[0] = NULL;
numsortedfiles = 0;
for (i = 0; i < numfiles; i++) {
for (j = 0; j < numsortedfiles; j++) {
if (FS_PathCmp(filelist[i], sortedlist[j]) < 0) {
break;
}
}
for (k = numsortedfiles; k > j; k--) {
sortedlist[k] = sortedlist[k-1];
}
sortedlist[j] = filelist[i];
numsortedfiles++;
}
Com_Memcpy(filelist, sortedlist, numfiles * sizeof( *filelist ) );
Z_Free(sortedlist);
}
/*
================
FS_NewDir_f
================
*/
void FS_NewDir_f( void ) {
char *filter;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 ) {
Com_Printf( "usage: fdir <filter>\n" );
Com_Printf( "example: fdir *ffa*.bsp\n");
return;
}
filter = Cmd_Argv( 1 );
Com_Printf( "---------------\n" );
dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs );
FS_SortFileList(dirnames, ndirs);
for ( i = 0; i < ndirs; i++ ) {
FS_ConvertPath(dirnames[i]);
Com_Printf( "%s\n", dirnames[i] );
}
Com_Printf( "%d files listed\n", ndirs );
FS_FreeFileList( dirnames );
}
/*
============
FS_Path_f
============
*/
void FS_Path_f( void ) {
searchpath_t *s;
int i;
Com_Printf ("Current search path:\n");
for (s = fs_searchpaths; s; s = s->next) {
if (s->pack) {
Com_Printf ("%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles);
if ( fs_numServerPaks ) {
if ( !FS_PakIsPure(s->pack) ) {
Com_Printf( " not on the pure list\n" );
} else {
Com_Printf( " on the pure list\n" );
}
}
} else {
Com_Printf ("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir );
}
}
Com_Printf( "\n" );
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o ) {
Com_Printf( "handle %i: %s\n", i, fsh[i].name );
}
}
}
/*
============
FS_TouchFile_f
The only purpose of this function is to allow game script files to copy
arbitrary files furing an "fs_copyfiles 1" run.
============
*/
void FS_TouchFile_f( void ) {
fileHandle_t f;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: touchFile <file>\n" );
return;
}
FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse );
if ( f ) {
FS_FCloseFile( f );
}
}
/*
============
FS_Which_f
============
*/
void FS_Which_f( void ) {
searchpath_t *search;
char *filename;
filename = Cmd_Argv(1);
if ( !filename[0] ) {
Com_Printf( "Usage: which <file>\n" );
return;
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
return;
}
// just wants to see if file is there
for ( search=fs_searchpaths; search; search=search->next ) {
if ( search->pack ) {
long hash = FS_HashFileName( filename, search->pack->hashSize );
// is the element a pak file?
if ( search->pack->hashTable[hash]) {
// look through all the pak file elements
pack_t* pak = search->pack;
fileInPack_t* pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
// found it!
Com_Printf( "File \"%s\" found in \"%s\"\n", filename, pak->pakFilename );
return;
}
pakFile = pakFile->next;
} while ( pakFile != NULL );
}
} else if (search->dir) {
directory_t* dir = search->dir;
char* netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename );
FILE* filep = fopen(netpath, "rb");
if ( filep ) {
fclose( filep );
char buf[MAX_OSPATH];
Com_sprintf( buf, sizeof( buf ), "%s%c%s", dir->path, PATH_SEP, dir->gamedir );
FS_ReplaceSeparators( buf );
Com_Printf( "File \"%s\" found at \"%s\"\n", filename, buf );
return;
}
}
}
Com_Printf( "File not found: \"%s\"\n", filename );
}
//===========================================================================
static int QDECL paksort( const void *a, const void *b ) {
char *aa, *bb;
aa = *(char **)a;
bb = *(char **)b;
return FS_PathCmp( aa, bb );
}
/*
================
FS_AddGameDirectory
Sets fs_gamedir, adds the directory to the head of the path,
then loads the zip headers
================
*/
#define MAX_PAKFILES 1024
static void FS_AddGameDirectory( const char *path, const char *dir ) {
searchpath_t *sp;
int i;
searchpath_t *search;
searchpath_t *thedir;
pack_t *pak;
char curpath[MAX_OSPATH + 1], *pakfile;
int numfiles;
char **pakfiles;
char *sorted[MAX_PAKFILES];
// this fixes the case where fs_basepath is the same as fs_cdpath
// which happens on full installs
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->dir && Sys_PathCmp(sp->dir->path, path) && !Q_stricmp(sp->dir->gamedir, dir)) {
return; // we've already got this one
}
}
Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) );
// find all pak files in this directory
Q_strncpyz(curpath, FS_BuildOSPath(path, dir, ""), sizeof(curpath));
curpath[strlen(curpath) - 1] = '\0'; // strip the trailing slash
//
// add the directory to the search path
//
search = (struct searchpath_s *)Z_Malloc (sizeof(searchpath_t), TAG_FILESYS, qtrue);
search->dir = (directory_t *)Z_Malloc( sizeof( *search->dir ), TAG_FILESYS, qtrue );
Q_strncpyz( search->dir->path, path, sizeof( search->dir->path ) );
Q_strncpyz( search->dir->fullpath, curpath, sizeof( search->dir->fullpath ) );
Q_strncpyz( search->dir->gamedir, dir, sizeof( search->dir->gamedir ) );
search->next = fs_searchpaths;
fs_searchpaths = search;
thedir = search;
pakfiles = Sys_ListFiles( curpath, ".pk3", NULL, &numfiles, qfalse );
// sort them so that later alphabetic matches override
// earlier ones. This makes pak1.pk3 override pak0.pk3
if ( numfiles > MAX_PAKFILES ) {
numfiles = MAX_PAKFILES;
}
for ( i = 0 ; i < numfiles ; i++ ) {
sorted[i] = pakfiles[i];
}
qsort( sorted, numfiles, sizeof(char*), paksort );
for ( i = 0 ; i < numfiles ; i++ ) {
pakfile = FS_BuildOSPath( path, dir, sorted[i] );
if ( ( pak = FS_LoadZipFile( pakfile, sorted[i] ) ) == 0 )
continue;
Q_strncpyz(pak->pakPathname, curpath, sizeof(pak->pakPathname));
// store the game name for downloading
Q_strncpyz(pak->pakGamename, dir, sizeof(pak->pakGamename));
fs_packFiles += pak->numfiles;
search = (searchpath_s *)Z_Malloc (sizeof(searchpath_t), TAG_FILESYS, qtrue);
search->pack = pak;
if (fs_dirbeforepak && fs_dirbeforepak->integer && thedir)
{
searchpath_t *oldnext = thedir->next;
thedir->next = search;
while (oldnext)
{
search->next = oldnext;
search = search->next;
oldnext = oldnext->next;
}
}
else
{
search->next = fs_searchpaths;
fs_searchpaths = search;
}
}
// done
Sys_FreeFileList( pakfiles );
}
/*
================
FS_idPak
================
*/
qboolean FS_idPak( char *pak, char *base ) {
int i;
for (i = 0; i < NUM_ID_PAKS; i++) {
if ( !FS_FilenameCompare(pak, va("%s/assets%d", base, i)) ) {
break;
}
}
if (i < NUM_ID_PAKS) {
return qtrue;
}
return qfalse;
}
/*
================
FS_CheckDirTraversal
Check whether the string contains stuff like "../" to prevent directory traversal bugs
and return qtrue if it does.
================
*/
qboolean FS_CheckDirTraversal(const char *checkdir)
{
if(strstr(checkdir, "../") || strstr(checkdir, "..\\"))
return qtrue;
return qfalse;
}
/*
================
FS_ComparePaks
if dlstring == qtrue
Returns a list of pak files that we should download from the server. They all get stored
in the current gamedir and an FS_Restart will be fired up after we download them all.
The string is the format:
@remotename@localname [repeat]
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS];
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS];
----------------
dlstring == qfalse
we are not interested in a download string format, we want something human-readable
(this is used for diagnostics while connecting to a pure server)
================
*/
qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring ) {
searchpath_t *sp;
qboolean havepak;
char *origpos = neededpaks;
int i;
if ( !fs_numServerReferencedPaks ) {
return qfalse; // Server didn't send any pack information along
}
*neededpaks = 0;
for ( i = 0 ; i < fs_numServerReferencedPaks ; i++ ) {
// Ok, see if we have this pak file
havepak = qfalse;
// never autodownload any of the id paks
if ( FS_idPak(fs_serverReferencedPakNames[i], "base") || FS_idPak(fs_serverReferencedPakNames[i], "missionpack") ) {
continue;
}
// Make sure the server cannot make us write to non-quake3 directories.
if(FS_CheckDirTraversal(fs_serverReferencedPakNames[i]))
{
Com_Printf("WARNING: Invalid download name %s\n", fs_serverReferencedPakNames[i]);
continue;
}
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i] ) {
havepak = qtrue; // This is it!
break;
}
}
if ( !havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i] ) {
// Don't got it
if (dlstring)
{
// We need this to make sure we won't hit the end of the buffer or the server could
// overwrite non-pk3 files on clients by writing so much crap into neededpaks that
// Q_strcat cuts off the .pk3 extension.
origpos += strlen(origpos);
// Remote name
Q_strcat( neededpaks, len, "@");
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Local name
Q_strcat( neededpaks, len, "@");
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) ) {
char st[MAX_ZPATH];
// We already have one called this, we need to download it to another name
// Make something up with the checksum in it
Com_sprintf( st, sizeof( st ), "%s.%08x.pk3", fs_serverReferencedPakNames[i], fs_serverReferencedPaks[i] );
Q_strcat( neededpaks, len, st );
} else {
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
}
// Find out whether it might have overflowed the buffer and don't add this file to the
// list if that is the case.
if(strlen(origpos) + (origpos - neededpaks) >= (unsigned)(len - 1))
{
*origpos = '\0';
break;
}
}
else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
{
Q_strcat( neededpaks, len, " (local file exists with wrong checksum)");
}
Q_strcat( neededpaks, len, "\n");
}
}
}
if ( *neededpaks ) {
return qtrue;
}
return qfalse; // We have them all
}
/*
================
FS_Shutdown
Frees all resources and closes all files
================
*/
void FS_Shutdown( qboolean closemfp ) {
searchpath_t *p, *next;
int i;
#if defined(_WIN32)
// Delete temporary files
fs_temporaryFileWriteIdx = 0;
for ( size_t i = 0; i < ARRAY_LEN(fs_temporaryFileNames); i++ )
{
if (fs_temporaryFileNames[i][0] != '\0')
{
if ( !DeleteFile(fs_temporaryFileNames[i]) )
{
DWORD error = GetLastError();
Com_DPrintf("FS_Shutdown: failed to delete '%s'. "
"Win32 error code: 0x08x",
fs_temporaryFileNames[i],
error);
}
fs_temporaryFileNames[i][0] = '\0';
}
}
#endif
for(i = 0; i < MAX_FILE_HANDLES; i++) {
if (fsh[i].fileSize) {
FS_FCloseFile(i);
}
}
// free everything
for ( p = fs_searchpaths ; p ; p = next ) {
next = p->next;
if ( p->pack ) {
FS_FreePak( p->pack );
}
if ( p->dir ) {
Z_Free( p->dir );
}
Z_Free( p );
}
// any FS_ calls will now be an error until reinitialized
fs_searchpaths = NULL;
Cmd_RemoveCommand( "path" );
Cmd_RemoveCommand( "dir" );
Cmd_RemoveCommand( "fdir" );
Cmd_RemoveCommand( "touchFile" );
Cmd_RemoveCommand( "which" );
#ifdef FS_MISSING
if (closemfp) {
fclose(missingFiles);
}
#endif
}
//rww - add search paths in for received svc_setgame
//Ensiform - this is so wrong rww
void FS_UpdateGamedir(void)
{
if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, BASEGAME ) )
{
if (fs_cdpath->string[0])
{
FS_AddGameDirectory(fs_cdpath->string, fs_gamedirvar->string);
}
if (fs_basepath->string[0])
{
FS_AddGameDirectory(fs_basepath->string, fs_gamedirvar->string);
}
if (fs_homepath->string[0] && !Sys_PathCmp(fs_homepath->string, fs_basepath->string))
{
FS_AddGameDirectory(fs_homepath->string, fs_gamedirvar->string);
}
}
}
/*
================
FS_ReorderPurePaks
NOTE TTimo: the reordering that happens here is not reflected in the cvars (\cvarlist *pak*)
this can lead to misleading situations, see https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
================
*/
static void FS_ReorderPurePaks()
{
searchpath_t *s;
int i;
searchpath_t **p_insert_index, // for linked list reordering
**p_previous; // when doing the scan
// only relevant when connected to pure server
if ( !fs_numServerPaks )
return;
fs_reordered = qfalse;
p_insert_index = &fs_searchpaths; // we insert in order at the beginning of the list
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
p_previous = p_insert_index; // track the pointer-to-current-item
for (s = *p_insert_index; s; s = s->next) {
// the part of the list before p_insert_index has been sorted already
if (s->pack && fs_serverPaks[i] == s->pack->checksum) {
fs_reordered = qtrue;
// move this element to the insert list
*p_previous = s->next;
s->next = *p_insert_index;
*p_insert_index = s;
// increment insert list
p_insert_index = &s->next;
break; // iterate to next server pack
}
p_previous = &s->next;
}
}
}
/**
@brief Mount the asset archives (.pk3) and register commands.
Mounts in this order the archives from:
1. <fs_cdpath>/<gameName>/
2. <fs_basepath>/<gameName>/
3. <fs_apppath>/<gameName>/ (Mac Only)
4. <fs_homepath>/<gameName>/
5. <fs_cdpath>/<fs_basegame>/
6. <fs_basepath>/<fs_basegame>/
7. <fs_homepath>/<fs_basegame>/
8. <fs_cdpath>/<fs_game>/
9. <fs_basepath>/<fs_game>/
10. <fs_homepath>/<fs_game>/
@param gameName Name of the default folder (i.e. always BASEGAME = "base" in OpenJK)
*/
void FS_Startup( const char *gameName ) {
const char *homePath;
Com_Printf( "----- FS_Startup -----\n" );
fs_packFiles = 0;
fs_debug = Cvar_Get( "fs_debug", "0", 0 );
fs_copyfiles = Cvar_Get( "fs_copyfiles", "0", CVAR_INIT );
fs_cdpath = Cvar_Get ("fs_cdpath", "", CVAR_INIT|CVAR_PROTECTED, "(Read Only) Location for development files" );
fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT|CVAR_PROTECTED, "(Read Only) Location for game files" );
fs_basegame = Cvar_Get ("fs_basegame", "", CVAR_INIT );
homePath = Sys_DefaultHomePath();
if (!homePath || !homePath[0]) {
homePath = fs_basepath->string;
}
fs_homepath = Cvar_Get ("fs_homepath", homePath, CVAR_INIT|CVAR_PROTECTED, "(Read/Write) Location for user generated files" );
fs_gamedirvar = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO, "Mod directory" );
fs_dirbeforepak = Cvar_Get("fs_dirbeforepak", "0", CVAR_INIT|CVAR_PROTECTED, "Prioritize directories before paks if not pure" );
// add search path elements in reverse priority order (lowest priority first)
if (fs_cdpath->string[0]) {
FS_AddGameDirectory( fs_cdpath->string, gameName );
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory( fs_basepath->string, gameName );
}
#ifdef MACOS_X
fs_apppath = Cvar_Get ("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT|CVAR_PROTECTED, "(Read Only) Location of OSX .app bundle" );
// Make MacOSX also include the base path included with the .app bundle
if (fs_apppath->string[0]) {
FS_AddGameDirectory( fs_apppath->string, gameName );
}
#endif
// fs_homepath is somewhat particular to *nix systems, only add if relevant
// NOTE: same filtering below for mods and basegame
if (fs_homepath->string[0] && !Sys_PathCmp(fs_homepath->string, fs_basepath->string)) {
FS_CreatePath ( fs_homepath->string );
FS_AddGameDirectory ( fs_homepath->string, gameName );
}
// check for additional base game so mods can be based upon other mods
if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) ) {
if (fs_cdpath->string[0]) {
FS_AddGameDirectory(fs_cdpath->string, fs_basegame->string);
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory(fs_basepath->string, fs_basegame->string);
}
if (fs_homepath->string[0] && !Sys_PathCmp(fs_homepath->string, fs_basepath->string)) {
FS_AddGameDirectory(fs_homepath->string, fs_basegame->string);
}
}
// check for additional game folder for mods
if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) ) {
if (fs_cdpath->string[0]) {
FS_AddGameDirectory(fs_cdpath->string, fs_gamedirvar->string);
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory(fs_basepath->string, fs_gamedirvar->string);
}
if (fs_homepath->string[0] && !Sys_PathCmp(fs_homepath->string, fs_basepath->string)) {
FS_AddGameDirectory(fs_homepath->string, fs_gamedirvar->string);
}
}
// add our commands
Cmd_AddCommand ("path", FS_Path_f, "Lists search paths" );
Cmd_AddCommand ("dir", FS_Dir_f, "Lists a folder" );
Cmd_AddCommand ("fdir", FS_NewDir_f, "Lists a folder with filters" );
Cmd_AddCommand ("touchFile", FS_TouchFile_f, "Touches a file" );
Cmd_AddCommand ("which", FS_Which_f, "Determines which search path a file was loaded from" );
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=506
// reorder the pure pk3 files according to server order
FS_ReorderPurePaks();
// print the current search paths
FS_Path_f();
fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified
Com_Printf( "----------------------\n" );
#ifdef FS_MISSING
if (missingFiles == NULL) {
missingFiles = fopen( "\\missing.txt", "ab" );
}
#endif
Com_Printf( "%d files in pk3 files\n", fs_packFiles );
}
/*
=====================
FS_LoadedPakChecksums
Returns a space separated string containing the checksums of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) );
}
return info;
}
/*
=====================
FS_LoadedPakNames
Returns a space separated string containing the names of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
if (*info) {
Q_strcat(info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
return info;
}
/*
=====================
FS_LoadedPakPureChecksums
Returns a space separated string containing the pure checksums of all loaded pk3 files.
Servers with sv_pure use these checksums to compare with the checksums the clients send
back to the server.
=====================
*/
const char *FS_LoadedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) );
}
return info;
}
/*
=====================
FS_ReferencedPakChecksums
Returns a space separated string containing the checksums of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, BASEGAME, strlen(BASEGAME))) {
Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) );
}
}
}
return info;
}
/*
=====================
FS_ReferencedPakPureChecksums
Returns a space separated string containing the pure checksums of all referenced pk3 files.
Servers with sv_pure set will get this string back from clients for pure validation
The string has a specific order, "cgame ui @ ref1 ref2 ref3 ..."
=====================
*/
const char *FS_ReferencedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
int nFlags, numPaks, checksum;
info[0] = 0;
checksum = fs_checksumFeed;
numPaks = 0;
for (nFlags = FS_CGAME_REF; nFlags; nFlags = nFlags >> 1) {
if (nFlags & FS_GENERAL_REF) {
// add a delimter between must haves and general refs
//Q_strcat(info, sizeof(info), "@ ");
info[strlen(info)+1] = '\0';
info[strlen(info)+2] = '\0';
info[strlen(info)] = '@';
info[strlen(info)] = ' ';
}
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file and has it been referenced based on flag?
if ( search->pack && (search->pack->referenced & nFlags)) {
Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) );
if (nFlags & (FS_CGAME_REF | FS_UI_REF)) {
break;
}
checksum ^= search->pack->pure_checksum;
numPaks++;
}
}
if (fs_fakeChkSum != 0) {
// only added if a non-pure file is referenced
Q_strcat( info, sizeof( info ), va("%i ", fs_fakeChkSum ) );
}
}
// last checksum is the encoded number of referenced pk3s
checksum ^= numPaks;
Q_strcat( info, sizeof( info ), va("%i ", checksum ) );
return info;
}
/*
=====================
FS_ReferencedPakNames
Returns a space separated string containing the names of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
// we want to return ALL pk3's from the fs_game path
// and referenced one's from base
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, BASEGAME, strlen(BASEGAME))) {
if (*info) {
Q_strcat(info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakGamename );
Q_strcat( info, sizeof( info ), "/" );
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
}
}
return info;
}
/*
=====================
FS_ClearPakReferences
=====================
*/
void FS_ClearPakReferences( int flags ) {
searchpath_t *search;
if ( !flags ) {
flags = -1;
}
for ( search = fs_searchpaths; search; search = search->next ) {
// is the element a pak file and has it been referenced?
if ( search->pack ) {
search->pack->referenced &= ~flags;
}
}
}
/*
=====================
FS_PureServerSetLoadedPaks
If the string is empty, all data sources will be allowed.
If not empty, only pk3 files that match one of the space
separated checksums will be checked for files, with the
exception of .cfg and .dat files.
=====================
*/
void FS_PureServerSetLoadedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
fs_numServerPaks = c;
for ( i = 0 ; i < c ; i++ ) {
fs_serverPaks[i] = atoi( Cmd_Argv( i ) );
}
if (fs_numServerPaks) {
Com_DPrintf( "Connected to a pure server.\n" );
}
else
{
if (fs_reordered)
{
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
// force a restart to make sure the search order will be correct
Com_DPrintf( "FS search reorder is required\n" );
FS_Restart(fs_checksumFeed);
return;
}
}
for ( i = 0 ; i < c ; i++ ) {
if (fs_serverPakNames[i]) {
Z_Free(fs_serverPakNames[i]);
}
fs_serverPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if ( d > MAX_SEARCH_PATHS ) {
d = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < d ; i++ ) {
fs_serverPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
}
/*
=====================
FS_PureServerSetReferencedPaks
The checksums and names of the pk3 files referenced at the server
are sent to the client and stored here. The client will use these
checksums to see if any pk3 files need to be auto-downloaded.
=====================
*/
void FS_PureServerSetReferencedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d = 0;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < c ; i++ ) {
fs_serverReferencedPaks[i] = atoi( Cmd_Argv( i ) );
}
for (i = 0 ; i < (int)ARRAY_LEN(fs_serverReferencedPakNames); i++)
{
if(fs_serverReferencedPakNames[i])
Z_Free(fs_serverReferencedPakNames[i]);
fs_serverReferencedPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if ( d > c ) {
d = c;
}
for ( i = 0 ; i < d ; i++ ) {
fs_serverReferencedPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
// ensure that there are as many checksums as there are pak names.
if(d < c)
c = d;
fs_numServerReferencedPaks = c;
}
/*
================
FS_InitFilesystem
Called only at inital startup, not when the filesystem
is resetting due to a game change
================
*/
void FS_InitFilesystem( void ) {
// allow command line parms to override our defaults
// we have to specially handle this, because normal command
// line variable sets don't happen until after the filesystem
// has already been initialized
Com_StartupVariable( "fs_cdpath" );
Com_StartupVariable( "fs_basepath" );
Com_StartupVariable( "fs_homepath" );
Com_StartupVariable( "fs_game" );
Com_StartupVariable( "fs_copyfiles" );
Com_StartupVariable( "fs_dirbeforepak" );
#ifdef MACOS_X
Com_StartupVariable( "fs_apppath" );
#endif
if(!FS_FilenameCompare(Cvar_VariableString("fs_game"), BASEGAME))
Cvar_Set("fs_game", "");
// try to start up normally
FS_Startup( BASEGAME );
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "mpdefault.cfg", NULL ) <= 0 ) {
Com_Error( ERR_FATAL, "Couldn't load mpdefault.cfg" );
// bk001208 - SafeMode see below, FIXME?
}
Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
#if defined(_WIN32)
Com_Memset(fs_temporaryFileNames, 0, sizeof(fs_temporaryFileNames));
#endif
// bk001208 - SafeMode see below, FIXME?
}
/*
================
FS_Restart
================
*/
void FS_Restart( int checksumFeed ) {
// free anything we currently have loaded
FS_Shutdown(qfalse);
// set the checksum feed
fs_checksumFeed = checksumFeed;
// clear pak references
FS_ClearPakReferences(0);
// try to start up normally
FS_Startup( BASEGAME );
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "mpdefault.cfg", NULL ) <= 0 ) {
// this might happen when connecting to a pure server not using BASEGAME/pak0.pk3
// (for instance a TA demo server)
if (lastValidBase[0]) {
FS_PureServerSetLoadedPaks("", "");
Cvar_Set("fs_basepath", lastValidBase);
Cvar_Set("fs_game", lastValidGame);
lastValidBase[0] = '\0';
lastValidGame[0] = '\0';
FS_Restart(checksumFeed);
Com_Error( ERR_DROP, "Invalid game folder\n" );
return;
}
Com_Error( ERR_FATAL, "Couldn't load mpdefault.cfg" );
}
if ( Q_stricmp(fs_gamedirvar->string, lastValidGame) ) {
// skip the jampconfig.cfg if "safe" is on the command line
if ( !Com_SafeMode() ) {
Cbuf_AddText ("exec " Q3CONFIG_CFG "\n");
}
}
Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
}
/*
=================
FS_ConditionalRestart
restart if necessary
=================
*/
qboolean FS_ConditionalRestart( int checksumFeed ) {
if( fs_gamedirvar->modified || checksumFeed != fs_checksumFeed ) {
FS_Restart( checksumFeed );
return qtrue;
}
#if 0
if(fs_gamedirvar->modified)
{
if(FS_FilenameCompare(lastValidGame, fs_gamedirvar->string) &&
(*lastValidGame || FS_FilenameCompare(fs_gamedirvar->string, BASEGAME)) &&
(*fs_gamedirvar->string || FS_FilenameCompare(lastValidGame, BASEGAME)))
{
FS_Restart(checksumFeed);
//Cvar_Restart(qtrue);
return qtrue;
}
else
fs_gamedirvar->modified = qfalse;
}
if(checksumFeed != fs_checksumFeed)
FS_Restart(checksumFeed);
else if(fs_numServerPaks && !fs_reordered)
FS_ReorderPurePaks();
#endif
return qfalse;
}
/*
========================================================================================
Handle based file calls for virtual machines
========================================================================================
*/
int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
int r;
qboolean sync;
sync = qfalse;
switch( mode ) {
case FS_READ:
r = FS_FOpenFileRead( qpath, f, qtrue );
break;
case FS_WRITE:
*f = FS_FOpenFileWrite( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
case FS_APPEND_SYNC:
sync = qtrue;
case FS_APPEND:
*f = FS_FOpenFileAppend( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
default:
Com_Error( ERR_FATAL, "FSH_FOpenFile: bad mode" );
return -1;
}
if (!f) {
return r;
}
if ( *f ) {
fsh[*f].fileSize = r;
}
fsh[*f].handleSync = sync;
return r;
}
int FS_FTell( fileHandle_t f ) {
int pos;
if (fsh[f].zipFile == qtrue) {
pos = unztell(fsh[f].handleFiles.file.z);
} else {
pos = ftell(fsh[f].handleFiles.file.o);
}
return pos;
}
void FS_Flush( fileHandle_t f ) {
fflush(fsh[f].handleFiles.file.o);
}
void FS_FilenameCompletion( const char *dir, const char *ext, qboolean stripExt, callbackFunc_t callback, qboolean allowNonPureFilesOnDisk ) {
int nfiles;
char **filenames, filename[MAX_STRING_CHARS];
filenames = FS_ListFilteredFiles( dir, ext, NULL, &nfiles );
FS_SortFileList( filenames, nfiles );
// pass all the files to callback (FindMatches)
for ( int i=0; i<nfiles; i++ ) {
FS_ConvertPath( filenames[i] );
Q_strncpyz( filename, filenames[i], MAX_STRING_CHARS );
if ( stripExt )
COM_StripExtension( filename, filename, sizeof( filename ) );
callback( filename );
}
FS_FreeFileList( filenames );
}
const char *FS_GetCurrentGameDir(bool emptybase)
{
if(fs_gamedirvar->string[0])
return fs_gamedirvar->string;
return emptybase ? "" : BASEGAME;
}
#ifdef MACOS_X
bool FS_LoadMachOBundle( const char *name )
{
int len;
void *data;
fileHandle_t f;
char *fn;
unzFile dll;
byte* buf;
char dllName[MAX_QPATH];
char *tempName;
unz_file_info zfi;
//read zipped bundle from pk3
len = FS_ReadFile(name, &data);
if (len < 1) {
return false;
}
//write temporary file of zipped bundle to e.g. uixxxxxx
//unique filename to avoid any clashes
Com_sprintf( dllName, sizeof(dllName), "%sXXXXXX", name );
tempName = mktemp( dllName );
f = FS_FOpenFileWrite( dllName );
if ( !f )
{
FS_FreeFile(data);
return false;
}
if (FS_Write( data, len, f ) < len)
{
FS_FreeFile(data);
return false;
}
FS_FCloseFile( f );
FS_FreeFile(data);
//unzOpen zipped bundle, find the dylib, and try to write it
fn = FS_BuildOSPath( fs_homepath->string, fs_gamedir, dllName );
dll = unzOpen( fn );
Com_sprintf (dllName, sizeof(dllName), "%s.bundle/Contents/MacOS/%s", name, name);
if (unzLocateFile(dll, dllName, 0) != UNZ_OK)
{
unzClose(dll);
remove( fn );
return false;
}
unzOpenCurrentFile( dll );
Com_sprintf( dllName, sizeof(dllName), "%s_pk3" DLL_EXT, name );
f = FS_FOpenFileWrite( dllName, qfalse );
if ( !f )
{
unzCloseCurrentFile( dll );
unzClose( dll );
remove( fn );
return false;
}
unzGetCurrentFileInfo( dll, &zfi, NULL, 0, NULL, 0, NULL, 0 );
len = zfi.uncompressed_size;
buf = (byte*)Z_Malloc( len+1, TAG_FILESYS, qfalse);
if (unzReadCurrentFile( dll, buf, len ) < len)
{
FS_FCloseFile( f );
unzCloseCurrentFile( dll );
unzClose( dll );
return false;
}
if (FS_Write(buf, len, f) < len)
{
FS_FCloseFile( f );
unzCloseCurrentFile( dll );
unzClose( dll );
return false;
}
FS_FCloseFile( f );
unzCloseCurrentFile( dll );
unzClose( dll );
Z_Free( buf );
//remove temporary zipped bundle
remove( fn );
return true;
}
#endif
qboolean FS_WriteToTemporaryFile( const void *data, size_t dataLength, char **tempFilePath )
{
#if defined(_WIN32)
DWORD error;
TCHAR tempPath[MAX_PATH];
DWORD tempPathResult = GetTempPath(MAX_PATH, tempPath);
if ( tempPathResult )
{
TCHAR tempFileName[MAX_PATH];
UINT tempFileNameResult = GetTempFileName(tempPath, "OJK", 0, tempFileName);
if ( tempFileNameResult )
{
HANDLE file = CreateFile(
tempFileName, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if ( file != INVALID_HANDLE_VALUE )
{
DWORD bytesWritten = 0;
if (WriteFile(file, data, dataLength, &bytesWritten, NULL))
{
int deletesRemaining = ARRAY_LEN(fs_temporaryFileNames);
CloseHandle(file);
while ( deletesRemaining > 0 &&
fs_temporaryFileNames[fs_temporaryFileWriteIdx][0] != '\0' )
{
// Delete old temporary file as we need to
if ( DeleteFile(fs_temporaryFileNames[fs_temporaryFileWriteIdx]) )
{
break;
}
error = GetLastError();
Com_DPrintf("FS_WriteToTemporaryFile failed for '%s'. "
"Win32 error code: 0x%08x\n",
fs_temporaryFileNames[fs_temporaryFileWriteIdx],
error);
// Failed to delete, possibly because DLL was still in use. This can
// happen when running a listen server and you continually restart
// the map. The game DLL is reloaded, but cgame and ui DLLs are not.
fs_temporaryFileWriteIdx =
(fs_temporaryFileWriteIdx + 1) % ARRAY_LEN(fs_temporaryFileNames);
deletesRemaining--;
}
// If this happened, then all slots are used and we some how have 8 DLLs
// loaded at once?!
assert(deletesRemaining > 0);
Q_strncpyz(fs_temporaryFileNames[fs_temporaryFileWriteIdx],
tempFileName, sizeof(fs_temporaryFileNames[0]));
fs_temporaryFileWriteIdx =
(fs_temporaryFileWriteIdx + 1) % ARRAY_LEN(fs_temporaryFileNames);
if ( tempFilePath )
{
size_t fileNameLen = strlen(tempFileName);
*tempFilePath = (char *)Z_Malloc(fileNameLen + 1, TAG_FILESYS);
Q_strncpyz(*tempFilePath, tempFileName, fileNameLen + 1);
}
return qtrue;
}
else
{
error = GetLastError();
Com_DPrintf("FS_WriteToTemporaryFile failed to write '%s'. "
"Win32 error code: 0x%08x\n",
tempFileName, error);
}
}
else
{
error = GetLastError();
Com_DPrintf("FS_WriteToTemporaryFile failed to create '%s'. "
"Win32 error code: 0x%08x\n",
tempFileName, error);
}
}
else
{
error = GetLastError();
Com_DPrintf("FS_WriteToTemporaryFile failed to generate temporary file name. "
"Win32 error code: 0x%08x\n", error);
}
}
else
{
error = GetLastError();
Com_DPrintf("FS_WriteToTemporaryFile failed to get temporary file folder. "
"Win32 error code: 0x%08x\n", error);
}
#endif
return qfalse;
}
| ./CrossVul/dataset_final_sorted/CWE-269/cpp/bad_3234_3 |
crossvul-cpp_data_good_3234_0 | /*
===========================================================================
Copyright (C) 1999 - 2005, Id Software, Inc.
Copyright (C) 2000 - 2013, Raven Software, Inc.
Copyright (C) 2001 - 2013, Activision, Inc.
Copyright (C) 2005 - 2015, ioquake3 contributors
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
// cl_main.c -- client main loop
#include "../server/exe_headers.h"
#include "client.h"
#include "client_ui.h"
#include <limits.h>
#include "../ghoul2/G2.h"
#include "qcommon/stringed_ingame.h"
#include "sys/sys_loadlib.h"
#include "qcommon/ojk_saved_game.h"
#define RETRANSMIT_TIMEOUT 3000 // time between connection packet retransmits
cvar_t *cl_renderer;
cvar_t *cl_nodelta;
cvar_t *cl_debugMove;
cvar_t *cl_noprint;
cvar_t *cl_timeout;
cvar_t *cl_packetdup;
cvar_t *cl_timeNudge;
cvar_t *cl_showTimeDelta;
cvar_t *cl_newClock=0;
cvar_t *cl_shownet;
cvar_t *cl_avidemo;
cvar_t *cl_pano;
cvar_t *cl_panoNumShots;
cvar_t *cl_skippingcin;
cvar_t *cl_endcredits;
cvar_t *cl_freelook;
cvar_t *cl_sensitivity;
cvar_t *cl_mouseAccel;
cvar_t *cl_showMouseRate;
cvar_t *cl_framerate;
cvar_t *m_pitch;
cvar_t *m_yaw;
cvar_t *m_forward;
cvar_t *m_side;
cvar_t *m_filter;
cvar_t *cl_activeAction;
cvar_t *cl_allowAltEnter;
cvar_t *cl_inGameVideo;
cvar_t *cl_consoleKeys;
cvar_t *cl_consoleUseScanCode;
clientActive_t cl;
clientConnection_t clc;
clientStatic_t cls;
// Structure containing functions exported from refresh DLL
refexport_t re;
static void *rendererLib = NULL;
//RAZFIXME: BAD BAD, maybe? had to move it out of ghoul2_shared.h -> CGhoul2Info_v at the least..
IGhoul2InfoArray &_TheGhoul2InfoArray( void ) {
return re.TheGhoul2InfoArray();
}
static void CL_ShutdownRef( qboolean restarting );
void CL_InitRef( void );
void CL_CheckForResend( void );
/*
=======================================================================
CLIENT RELIABLE COMMAND COMMUNICATION
=======================================================================
*/
/*
======================
CL_AddReliableCommand
The given command will be transmitted to the server, and is gauranteed to
not have future usercmd_t executed before it is executed
======================
*/
void CL_AddReliableCommand( const char *cmd ) {
int index;
// if we would be losing an old command that hasn't been acknowledged,
// we must drop the connection
if ( clc.reliableSequence - clc.reliableAcknowledge > MAX_RELIABLE_COMMANDS ) {
Com_Error( ERR_DROP, "Client command overflow" );
}
clc.reliableSequence++;
index = clc.reliableSequence & ( MAX_RELIABLE_COMMANDS - 1 );
if ( clc.reliableCommands[ index ] ) {
Z_Free( clc.reliableCommands[ index ] );
}
clc.reliableCommands[ index ] = CopyString( cmd );
}
//======================================================================
/*
=================
CL_FlushMemory
Called by CL_MapLoading, CL_Connect_f, and CL_ParseGamestate the only
ways a client gets into a game
Also called by Com_Error
=================
*/
void CL_FlushMemory( void ) {
// clear sounds (moved higher up within this func to avoid the odd sound stutter)
S_DisableSounds();
// unload the old VM
CL_ShutdownCGame();
CL_ShutdownUI();
if ( re.Shutdown ) {
re.Shutdown( qfalse, qfalse ); // don't destroy window or context
}
//rwwFIXMEFIXME: The game server appears to continue running, so clearing common bsp data causes crashing and other bad things
/*
CM_ClearMap();
*/
cls.soundRegistered = qfalse;
cls.rendererStarted = qfalse;
}
/*
=====================
CL_MapLoading
A local server is starting to load a map, so update the
screen to let the user know about it, then dump all client
memory on the hunk from cgame, ui, and renderer
=====================
*/
void CL_MapLoading( void ) {
if ( !com_cl_running->integer ) {
return;
}
Con_Close();
Key_SetCatcher( 0 );
// if we are already connected to the local host, stay connected
if ( cls.state >= CA_CONNECTED && !Q_stricmp( cls.servername, "localhost" ) ) {
cls.state = CA_CONNECTED; // so the connect screen is drawn
memset( cls.updateInfoString, 0, sizeof( cls.updateInfoString ) );
// memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) );
memset( &cl.gameState, 0, sizeof( cl.gameState ) );
clc.lastPacketSentTime = -9999;
SCR_UpdateScreen();
} else {
// clear nextmap so the cinematic shutdown doesn't execute it
Cvar_Set( "nextmap", "" );
CL_Disconnect();
Q_strncpyz( cls.servername, "localhost", sizeof(cls.servername) );
cls.state = CA_CHALLENGING; // so the connect screen is drawn
Key_SetCatcher( 0 );
SCR_UpdateScreen();
clc.connectTime = -RETRANSMIT_TIMEOUT;
NET_StringToAdr( cls.servername, &clc.serverAddress);
// we don't need a challenge on the localhost
CL_CheckForResend();
}
CL_FlushMemory();
}
/*
=====================
CL_ClearState
Called before parsing a gamestate
=====================
*/
void CL_ClearState (void) {
CL_ShutdownCGame();
S_StopAllSounds();
memset( &cl, 0, sizeof( cl ) );
}
/*
=====================
CL_FreeReliableCommands
Wipes all reliableCommands strings from clc
=====================
*/
void CL_FreeReliableCommands( void )
{
// wipe the client connection
for ( int i = 0 ; i < MAX_RELIABLE_COMMANDS ; i++ ) {
if ( clc.reliableCommands[i] ) {
Z_Free( clc.reliableCommands[i] );
clc.reliableCommands[i] = NULL;
}
}
}
/*
=====================
CL_Disconnect
Called when a connection, or cinematic is being terminated.
Goes from a connected state to either a menu state or a console state
Sends a disconnect message to the server
This is also called on Com_Error and Com_Quit, so it shouldn't cause any errors
=====================
*/
void CL_Disconnect( void ) {
if ( !com_cl_running || !com_cl_running->integer ) {
return;
}
if (cls.uiStarted)
UI_SetActiveMenu( NULL,NULL );
SCR_StopCinematic ();
S_ClearSoundBuffer();
// send a disconnect message to the server
// send it a few times in case one is dropped
if ( cls.state >= CA_CONNECTED ) {
CL_AddReliableCommand( "disconnect" );
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
CL_ClearState ();
CL_FreeReliableCommands();
extern void CL_FreeServerCommands(void);
CL_FreeServerCommands();
memset( &clc, 0, sizeof( clc ) );
cls.state = CA_DISCONNECTED;
// allow cheats locally
Cvar_Set( "timescale", "1" );//jic we were skipping
Cvar_Set( "skippingCinematic", "0" );//jic we were skipping
}
/*
===================
CL_ForwardCommandToServer
adds the current command line as a clientCommand
things like godmode, noclip, etc, are commands directed to the server,
so when they are typed in at the console, they will need to be forwarded.
===================
*/
void CL_ForwardCommandToServer( void ) {
const char *cmd;
char string[MAX_STRING_CHARS];
cmd = Cmd_Argv(0);
// ignore key up commands
if ( cmd[0] == '-' ) {
return;
}
if ( cls.state != CA_ACTIVE || cmd[0] == '+' ) {
Com_Printf ("Unknown command \"%s\"\n", cmd);
return;
}
if ( Cmd_Argc() > 1 ) {
Com_sprintf( string, sizeof(string), "%s %s", cmd, Cmd_Args() );
} else {
Q_strncpyz( string, cmd, sizeof(string) );
}
CL_AddReliableCommand( string );
}
/*
======================================================================
CONSOLE COMMANDS
======================================================================
*/
/*
==================
CL_ForwardToServer_f
==================
*/
void CL_ForwardToServer_f( void ) {
if ( cls.state != CA_ACTIVE ) {
Com_Printf ("Not connected to a server.\n");
return;
}
// don't forward the first argument
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand( Cmd_Args() );
}
}
/*
==================
CL_Disconnect_f
==================
*/
void CL_Disconnect_f( void ) {
SCR_StopCinematic();
//FIXME:
// TA codebase added additional CA_CINEMATIC check below, presumably so they could play cinematics
// in the menus when disconnected, although having the SCR_StopCinematic() call above is weird.
// Either there's a bug, or the new version of that function conditionally-doesn't stop cinematics...
//
if ( cls.state != CA_DISCONNECTED && cls.state != CA_CINEMATIC ) {
Com_Error (ERR_DISCONNECT, "Disconnected from server");
}
}
/*
=================
CL_Vid_Restart_f
Restart the video subsystem
=================
*/
void CL_Vid_Restart_f( void ) {
S_StopAllSounds(); // don't let them loop during the restart
S_BeginRegistration(); // all sound handles are now invalid
CL_ShutdownRef(qtrue);
CL_ShutdownUI();
CL_ShutdownCGame();
//rww - sof2mp does this here, but it seems to cause problems in this codebase.
// CM_ClearMap();
CL_InitRef();
cls.rendererStarted = qfalse;
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.soundRegistered = qfalse;
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
}
/*
=================
CL_Snd_Restart_f
Restart the sound subsystem
The cgame and game must also be forced to restart because
handles will be invalid
=================
*/
void CL_Snd_Restart_f( void ) {
S_Shutdown();
S_Init();
// CL_Vid_Restart_f();
extern qboolean s_soundMuted;
s_soundMuted = qfalse; // we can play again
S_RestartMusic();
extern void S_ReloadAllUsedSounds(void);
S_ReloadAllUsedSounds();
extern void AS_ParseSets(void);
AS_ParseSets();
}
/*
==================
CL_Configstrings_f
==================
*/
void CL_Configstrings_f( void ) {
int i;
int ofs;
if ( cls.state != CA_ACTIVE ) {
Com_Printf( "Not connected to a server.\n");
return;
}
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
ofs = cl.gameState.stringOffsets[ i ];
if ( !ofs ) {
continue;
}
Com_Printf( "%4i: %s\n", i, cl.gameState.stringData + ofs );
}
}
/*
==============
CL_Clientinfo_f
==============
*/
void CL_Clientinfo_f( void ) {
Com_Printf( "--------- Client Information ---------\n" );
Com_Printf( "state: %i\n", cls.state );
Com_Printf( "Server: %s\n", cls.servername );
Com_Printf ("User info settings:\n");
Info_Print( Cvar_InfoString( CVAR_USERINFO ) );
Com_Printf( "--------------------------------------\n" );
}
//====================================================================
void UI_UpdateConnectionString( const char *string );
/*
=================
CL_CheckForResend
Resend a connect message if the last one has timed out
=================
*/
void CL_CheckForResend( void ) {
int port;
char info[MAX_INFO_STRING];
// if ( cls.state == CA_CINEMATIC )
if ( cls.state == CA_CINEMATIC || CL_IsRunningInGameCinematic())
{
return;
}
// resend if we haven't gotten a reply yet
if ( cls.state < CA_CONNECTING || cls.state > CA_CHALLENGING ) {
return;
}
if ( cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT ) {
return;
}
clc.connectTime = cls.realtime; // for retransmit requests
clc.connectPacketCount++;
// requesting a challenge
switch ( cls.state ) {
case CA_CONNECTING:
UI_UpdateConnectionString( va("(%i)", clc.connectPacketCount ) );
NET_OutOfBandPrint(NS_CLIENT, clc.serverAddress, "getchallenge");
break;
case CA_CHALLENGING:
// sending back the challenge
port = Cvar_VariableIntegerValue("net_qport");
UI_UpdateConnectionString( va("(%i)", clc.connectPacketCount ) );
Q_strncpyz( info, Cvar_InfoString( CVAR_USERINFO ), sizeof( info ) );
Info_SetValueForKey( info, "protocol", va("%i", PROTOCOL_VERSION ) );
Info_SetValueForKey( info, "qport", va("%i", port ) );
Info_SetValueForKey( info, "challenge", va("%i", clc.challenge ) );
NET_OutOfBandPrint( NS_CLIENT, clc.serverAddress, "connect \"%s\"", info );
// the most current userinfo has been sent, so watch for any
// newer changes to userinfo variables
cvar_modifiedFlags &= ~CVAR_USERINFO;
break;
default:
Com_Error( ERR_FATAL, "CL_CheckForResend: bad cls.state" );
}
}
/*
===================
CL_DisconnectPacket
Sometimes the server can drop the client and the netchan based
disconnect can be lost. If the client continues to send packets
to the server, the server will send out of band disconnect packets
to the client so it doesn't have to wait for the full timeout period.
===================
*/
void CL_DisconnectPacket( netadr_t from ) {
if ( cls.state != CA_ACTIVE ) {
return;
}
// if not from our server, ignore it
if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
return;
}
// if we have received packets within three seconds, ignore it
// (it might be a malicious spoof)
if ( cls.realtime - clc.lastPacketTime < 3000 ) {
return;
}
// drop the connection (FIXME: connection dropped dialog)
Com_Printf( "Server disconnected for unknown reason\n" );
CL_Disconnect();
}
/*
=================
CL_ConnectionlessPacket
Responses to broadcasts, etc
=================
*/
void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) {
char *s;
const char *c;
MSG_BeginReading( msg );
MSG_ReadLong( msg ); // skip the -1
s = MSG_ReadStringLine( msg );
Cmd_TokenizeString( s );
c = Cmd_Argv(0);
Com_DPrintf ("CL packet %s: %s\n", NET_AdrToString(from), c);
// challenge from the server we are connecting to
if ( !strcmp(c, "challengeResponse") ) {
if ( cls.state != CA_CONNECTING ) {
Com_Printf( "Unwanted challenge response received. Ignored.\n" );
} else {
// start sending challenge repsonse instead of challenge request packets
clc.challenge = atoi(Cmd_Argv(1));
cls.state = CA_CHALLENGING;
clc.connectPacketCount = 0;
clc.connectTime = -99999;
// take this address as the new server address. This allows
// a server proxy to hand off connections to multiple servers
clc.serverAddress = from;
}
return;
}
// server connection
if ( !strcmp(c, "connectResponse") ) {
if ( cls.state >= CA_CONNECTED ) {
Com_Printf ("Dup connect received. Ignored.\n");
return;
}
if ( cls.state != CA_CHALLENGING ) {
Com_Printf ("connectResponse packet while not connecting. Ignored.\n");
return;
}
if ( !NET_CompareBaseAdr( from, clc.serverAddress ) ) {
Com_Printf( "connectResponse from a different address. Ignored.\n" );
Com_Printf( "%s should have been %s\n", NET_AdrToString( from ),
NET_AdrToString( clc.serverAddress ) );
return;
}
Netchan_Setup (NS_CLIENT, &clc.netchan, from, Cvar_VariableIntegerValue( "net_qport" ) );
cls.state = CA_CONNECTED;
clc.lastPacketSentTime = -9999; // send first packet immediately
return;
}
// a disconnect message from the server, which will happen if the server
// dropped the connection but it is still getting packets from us
if (!strcmp(c, "disconnect")) {
CL_DisconnectPacket( from );
return;
}
// echo request from server
if ( !strcmp(c, "echo") ) {
NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv(1) );
return;
}
// print request from server
if ( !strcmp(c, "print") ) {
s = MSG_ReadString( msg );
UI_UpdateConnectionMessageString( s );
Com_Printf( "%s", s );
return;
}
Com_DPrintf ("Unknown connectionless packet command.\n");
}
/*
=================
CL_PacketEvent
A packet has arrived from the main event loop
=================
*/
void CL_PacketEvent( netadr_t from, msg_t *msg ) {
clc.lastPacketTime = cls.realtime;
if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) {
CL_ConnectionlessPacket( from, msg );
return;
}
if ( cls.state < CA_CONNECTED ) {
return; // can't be a valid sequenced packet
}
if ( msg->cursize < 8 ) {
Com_Printf ("%s: Runt packet\n",NET_AdrToString( from ));
return;
}
//
// packet from server
//
if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
Com_DPrintf ("%s:sequenced packet without connection\n"
,NET_AdrToString( from ) );
// FIXME: send a client disconnect?
return;
}
if (!Netchan_Process( &clc.netchan, msg) ) {
return; // out of order, duplicated, etc
}
clc.lastPacketTime = cls.realtime;
CL_ParseServerMessage( msg );
}
/*
==================
CL_CheckTimeout
==================
*/
void CL_CheckTimeout( void ) {
//
// check timeout
//
if ( ( !CL_CheckPaused() || !sv_paused->integer )
// && cls.state >= CA_CONNECTED && cls.state != CA_CINEMATIC
&& cls.state >= CA_CONNECTED && (cls.state != CA_CINEMATIC && !CL_IsRunningInGameCinematic())
&& cls.realtime - clc.lastPacketTime > cl_timeout->value*1000) {
if (++cl.timeoutcount > 5) { // timeoutcount saves debugger
Com_Printf ("\nServer connection timed out.\n");
CL_Disconnect ();
return;
}
} else {
cl.timeoutcount = 0;
}
}
/*
==================
CL_CheckPaused
Check whether client has been paused.
==================
*/
qboolean CL_CheckPaused(void)
{
// if cl_paused->modified is set, the cvar has only been changed in
// this frame. Keep paused in this frame to ensure the server doesn't
// lag behind.
if(cl_paused->integer || cl_paused->modified)
return qtrue;
return qfalse;
}
//============================================================================
/*
==================
CL_CheckUserinfo
==================
*/
void CL_CheckUserinfo( void ) {
if ( cls.state < CA_CHALLENGING ) {
return;
}
// don't overflow the reliable command buffer when paused
if ( CL_CheckPaused() ) {
return;
}
// send a reliable userinfo update if needed
if ( cvar_modifiedFlags & CVAR_USERINFO ) {
cvar_modifiedFlags &= ~CVAR_USERINFO;
CL_AddReliableCommand( va("userinfo \"%s\"", Cvar_InfoString( CVAR_USERINFO ) ) );
}
}
/*
==================
CL_Frame
==================
*/
extern cvar_t *cl_newClock;
static unsigned int frameCount;
float avgFrametime=0.0;
void CL_Frame ( int msec,float fractionMsec ) {
if ( !com_cl_running->integer ) {
return;
}
// load the ref / cgame if needed
CL_StartHunkUsers();
if ( cls.state == CA_DISCONNECTED && !( Key_GetCatcher( ) & KEYCATCH_UI )
&& !com_sv_running->integer ) {
// if disconnected, bring up the menu
if (!CL_CheckPendingCinematic()) // this avoid having the menu flash for one frame before pending cinematics
{
UI_SetActiveMenu( "mainMenu",NULL );
}
}
// if recording an avi, lock to a fixed fps
if ( cl_avidemo->integer ) {
// save the current screen
if ( cls.state == CA_ACTIVE ) {
if (cl_avidemo->integer > 0) {
Cbuf_ExecuteText( EXEC_NOW, "screenshot silent\n" );
} else {
Cbuf_ExecuteText( EXEC_NOW, "screenshot_tga silent\n" );
}
}
// fixed time for next frame
if (cl_avidemo->integer > 0) {
msec = 1000 / cl_avidemo->integer;
} else {
msec = 1000 / -cl_avidemo->integer;
}
}
// save the msec before checking pause
cls.realFrametime = msec;
// decide the simulation time
cls.frametime = msec;
if(cl_framerate->integer)
{
avgFrametime+=msec;
char mess[256];
if(!(frameCount&0x1f))
{
sprintf(mess,"Frame rate=%f\n\n",1000.0f*(1.0/(avgFrametime/32.0f)));
// OutputDebugString(mess);
Com_Printf(mess);
avgFrametime=0.0f;
}
frameCount++;
}
cls.frametimeFraction=fractionMsec;
cls.realtime += msec;
cls.realtimeFraction+=fractionMsec;
if (cls.realtimeFraction>=1.0f)
{
if (cl_newClock&&cl_newClock->integer)
{
cls.realtime++;
}
cls.realtimeFraction-=1.0f;
}
if ( cl_timegraph->integer ) {
SCR_DebugGraph ( cls.realFrametime * 0.25, 0 );
}
// see if we need to update any userinfo
CL_CheckUserinfo();
// if we haven't gotten a packet in a long time,
// drop the connection
CL_CheckTimeout();
// send intentions now
CL_SendCmd();
// resend a connection request if necessary
CL_CheckForResend();
// decide on the serverTime to render
CL_SetCGameTime();
if (cl_pano->integer && cls.state == CA_ACTIVE) { //grab some panoramic shots
int i = 1;
int pref = cl_pano->integer;
int oldnoprint = cl_noprint->integer;
Con_Close();
cl_noprint->integer = 1; //hide the screen shot msgs
for (; i <= cl_panoNumShots->integer; i++) {
Cvar_SetValue( "pano", i );
SCR_UpdateScreen();// update the screen
Cbuf_ExecuteText( EXEC_NOW, va("screenshot %dpano%02d\n", pref, i) ); //grab this screen
}
Cvar_SetValue( "pano", 0 ); //done
cl_noprint->integer = oldnoprint;
}
if (cl_skippingcin->integer && !cl_endcredits->integer && !com_developer->integer ) {
if (cl_skippingcin->modified){
S_StopSounds(); //kill em all but music
cl_skippingcin->modified=qfalse;
Com_Printf (S_COLOR_YELLOW "%s", SE_GetString("CON_TEXT_SKIPPING"));
SCR_UpdateScreen();
}
} else {
// update the screen
SCR_UpdateScreen();
}
// update audio
S_Update();
// advance local effects for next frame
SCR_RunCinematic();
Con_RunConsole();
cls.framecount++;
}
//============================================================================
/*
============
CL_ShutdownRef
============
*/
static void CL_ShutdownRef( qboolean restarting ) {
if ( re.Shutdown ) {
re.Shutdown( qtrue, restarting );
}
memset( &re, 0, sizeof( re ) );
if ( rendererLib != NULL ) {
Sys_UnloadDll (rendererLib);
rendererLib = NULL;
}
}
/*
============================
CL_StartSound
Convenience function for the sound system to be started
REALLY early on Xbox, helps with memory fragmentation.
============================
*/
void CL_StartSound( void ) {
if ( !cls.soundStarted ) {
cls.soundStarted = qtrue;
S_Init();
}
if ( !cls.soundRegistered ) {
cls.soundRegistered = qtrue;
S_BeginRegistration();
}
}
/*
============
CL_InitRenderer
============
*/
void CL_InitRenderer( void ) {
// this sets up the renderer and calls R_Init
re.BeginRegistration( &cls.glconfig );
// load character sets
cls.charSetShader = re.RegisterShaderNoMip("gfx/2d/charsgrid_med");
cls.whiteShader = re.RegisterShader( "white" );
cls.consoleShader = re.RegisterShader( "console" );
g_console_field_width = cls.glconfig.vidWidth / SMALLCHAR_WIDTH - 2;
g_consoleField.widthInChars = g_console_field_width;
}
/*
============================
CL_StartHunkUsers
After the server has cleared the hunk, these will need to be restarted
This is the only place that any of these functions are called from
============================
*/
void CL_StartHunkUsers( void ) {
if ( !com_cl_running->integer ) {
return;
}
if ( !cls.rendererStarted ) {
cls.rendererStarted = qtrue;
CL_InitRenderer();
}
if ( !cls.soundStarted ) {
cls.soundStarted = qtrue;
S_Init();
}
if ( !cls.soundRegistered ) {
cls.soundRegistered = qtrue;
S_BeginRegistration();
}
//we require the ui to be loaded here or else it crashes trying to access the ui on command line map loads
if ( !cls.uiStarted ) {
cls.uiStarted = qtrue;
CL_InitUI();
}
// if ( !cls.cgameStarted && cls.state > CA_CONNECTED && cls.state != CA_CINEMATIC ) {
if ( !cls.cgameStarted && cls.state > CA_CONNECTED && (cls.state != CA_CINEMATIC && !CL_IsRunningInGameCinematic()) )
{
cls.cgameStarted = qtrue;
CL_InitCGame();
}
}
/*
================
CL_RefPrintf
DLL glue
================
*/
void QDECL CL_RefPrintf( int print_level, const char *fmt, ...) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start (argptr,fmt);
Q_vsnprintf(msg, sizeof(msg), fmt, argptr);
va_end (argptr);
if ( print_level == PRINT_ALL ) {
Com_Printf ("%s", msg);
} else if ( print_level == PRINT_WARNING ) {
Com_Printf (S_COLOR_YELLOW "%s", msg); // yellow
} else if ( print_level == PRINT_DEVELOPER ) {
Com_DPrintf (S_COLOR_RED "%s", msg); // red
}
}
/*
============
String_GetStringValue
DLL glue, but highly reusuable DLL glue at that
============
*/
const char *String_GetStringValue( const char *reference )
{
#ifndef JK2_MODE
return SE_GetString(reference);
#else
return JK2SP_GetStringTextString(reference);
#endif
}
extern qboolean gbAlreadyDoingLoad;
extern void *gpvCachedMapDiskImage;
extern char gsCachedMapDiskImage[MAX_QPATH];
extern qboolean gbUsingCachedMapDataRightNow;
char *get_gsCachedMapDiskImage( void )
{
return gsCachedMapDiskImage;
}
void *get_gpvCachedMapDiskImage( void )
{
return gpvCachedMapDiskImage;
}
qboolean *get_gbUsingCachedMapDataRightNow( void )
{
return &gbUsingCachedMapDataRightNow;
}
qboolean *get_gbAlreadyDoingLoad( void )
{
return &gbAlreadyDoingLoad;
}
int get_com_frameTime( void )
{
return com_frameTime;
}
void *CL_Malloc(int iSize, memtag_t eTag, qboolean bZeroit, int iAlign)
{
return Z_Malloc(iSize, eTag, bZeroit);
}
/*
============
CL_InitRef
============
*/
extern qboolean S_FileExists( const char *psFilename );
extern bool CM_CullWorldBox (const cplane_t *frustum, const vec3pair_t bounds);
extern qboolean SND_RegisterAudio_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel /* 99% qfalse */);
extern cvar_t *Cvar_Set2( const char *var_name, const char *value, qboolean force);
extern CMiniHeap *G2VertSpaceServer;
static CMiniHeap *GetG2VertSpaceServer( void ) {
return G2VertSpaceServer;
}
// NOTENOTE: If you change the output name of rd-vanilla, change this define too!
#ifdef JK2_MODE
#define DEFAULT_RENDER_LIBRARY "rdjosp-vanilla"
#else
#define DEFAULT_RENDER_LIBRARY "rdsp-vanilla"
#endif
void CL_InitRef( void ) {
refexport_t *ret;
static refimport_t rit;
char dllName[MAX_OSPATH];
GetRefAPI_t GetRefAPI;
Com_Printf( "----- Initializing Renderer ----\n" );
cl_renderer = Cvar_Get( "cl_renderer", DEFAULT_RENDER_LIBRARY, CVAR_ARCHIVE|CVAR_LATCH|CVAR_PROTECTED );
Com_sprintf( dllName, sizeof( dllName ), "%s_" ARCH_STRING DLL_EXT, cl_renderer->string );
if( !(rendererLib = Sys_LoadDll( dllName, qfalse )) && strcmp( cl_renderer->string, cl_renderer->resetString ) )
{
Com_Printf( "failed: trying to load fallback renderer\n" );
Cvar_ForceReset( "cl_renderer" );
Com_sprintf( dllName, sizeof( dllName ), DEFAULT_RENDER_LIBRARY "_" ARCH_STRING DLL_EXT );
rendererLib = Sys_LoadDll( dllName, qfalse );
}
if ( !rendererLib ) {
Com_Error( ERR_FATAL, "Failed to load renderer\n" );
}
memset( &rit, 0, sizeof( rit ) );
GetRefAPI = (GetRefAPI_t)Sys_LoadFunction( rendererLib, "GetRefAPI" );
if ( !GetRefAPI )
Com_Error( ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError() );
#define RIT(y) rit.y = y
RIT(CIN_PlayCinematic);
RIT(CIN_RunCinematic);
RIT(CIN_UploadCinematic);
RIT(CL_IsRunningInGameCinematic);
RIT(Cmd_AddCommand);
RIT(Cmd_Argc);
RIT(Cmd_ArgsBuffer);
RIT(Cmd_Argv);
RIT(Cmd_ExecuteString);
RIT(Cmd_RemoveCommand);
RIT(CM_ClusterPVS);
RIT(CM_CullWorldBox);
RIT(CM_DeleteCachedMap);
RIT(CM_DrawDebugSurface);
RIT(CM_PointContents);
RIT(Cvar_Get);
RIT(Cvar_Set);
RIT(Cvar_SetValue);
RIT(Cvar_CheckRange);
RIT(Cvar_VariableIntegerValue);
RIT(Cvar_VariableString);
RIT(Cvar_VariableStringBuffer);
RIT(Cvar_VariableValue);
RIT(FS_FCloseFile);
RIT(FS_FileIsInPAK);
RIT(FS_FOpenFileByMode);
RIT(FS_FOpenFileRead);
RIT(FS_FOpenFileWrite);
RIT(FS_FreeFile);
RIT(FS_FreeFileList);
RIT(FS_ListFiles);
RIT(FS_Read);
RIT(FS_ReadFile);
RIT(FS_Write);
RIT(FS_WriteFile);
RIT(Hunk_ClearToMark);
RIT(SND_RegisterAudio_LevelLoadEnd);
//RIT(SV_PointContents);
RIT(SV_Trace);
RIT(S_RestartMusic);
RIT(Z_Free);
rit.Malloc=CL_Malloc;
RIT(Z_MemSize);
RIT(Z_MorphMallocTag);
RIT(Hunk_ClearToMark);
rit.WIN_Init = WIN_Init;
rit.WIN_SetGamma = WIN_SetGamma;
rit.WIN_Shutdown = WIN_Shutdown;
rit.WIN_Present = WIN_Present;
rit.GL_GetProcAddress = WIN_GL_GetProcAddress;
rit.GL_ExtensionSupported = WIN_GL_ExtensionSupported;
rit.PD_Load = PD_Load;
rit.PD_Store = PD_Store;
rit.Error = Com_Error;
rit.FS_FileExists = S_FileExists;
rit.GetG2VertSpaceServer = GetG2VertSpaceServer;
rit.LowPhysicalMemory = Sys_LowPhysicalMemory;
rit.Milliseconds = Sys_Milliseconds2;
rit.Printf = CL_RefPrintf;
rit.SE_GetString = String_GetStringValue;
rit.SV_Trace = SV_Trace;
rit.gpvCachedMapDiskImage = get_gpvCachedMapDiskImage;
rit.gsCachedMapDiskImage = get_gsCachedMapDiskImage;
rit.gbUsingCachedMapDataRightNow = get_gbUsingCachedMapDataRightNow;
rit.gbAlreadyDoingLoad = get_gbAlreadyDoingLoad;
rit.com_frameTime = get_com_frameTime;
rit.SV_PointContents = SV_PointContents;
rit.saved_game = &ojk::SavedGame::get_instance();
ret = GetRefAPI( REF_API_VERSION, &rit );
if ( !ret ) {
Com_Error (ERR_FATAL, "Couldn't initialize refresh" );
}
re = *ret;
Com_Printf( "-------------------------------\n");
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
}
//===========================================================================================
void CL_CompleteCinematic( char *args, int argNum );
/*
====================
CL_Init
====================
*/
void CL_Init( void ) {
Com_Printf( "----- Client Initialization -----\n" );
#ifdef JK2_MODE
JK2SP_Register("con_text", SP_REGISTER_REQUIRED); //reference is CON_TEXT
JK2SP_Register("keynames", SP_REGISTER_REQUIRED); // reference is KEYNAMES
#endif
Con_Init ();
CL_ClearState ();
cls.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
//cls.keyCatchers = KEYCATCH_CONSOLE;
cls.realtime = 0;
cls.realtimeFraction=0.0f; // fraction of a msec accumulated
CL_InitInput ();
//
// register our variables
//
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
cl_timeout = Cvar_Get ("cl_timeout", "125", 0);
cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP );
cl_newClock = Cvar_Get ("cl_newClock", "1", 0);
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_avidemo = Cvar_Get ("cl_avidemo", "0", 0);
cl_pano = Cvar_Get ("pano", "0", 0);
cl_panoNumShots= Cvar_Get ("panoNumShots", "10", CVAR_ARCHIVE);
cl_skippingcin = Cvar_Get ("skippingCinematic", "0", CVAR_ROM);
cl_endcredits = Cvar_Get ("cg_endcredits", "0", 0);
cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE);
cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE);
cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", CVAR_ARCHIVE);
cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE );
cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE);
cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE);
cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE);
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE );
cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0);
cl_allowAltEnter = Cvar_Get ("cl_allowAltEnter", "1", CVAR_ARCHIVE);
cl_inGameVideo = Cvar_Get ("cl_inGameVideo", "1", CVAR_ARCHIVE);
cl_framerate = Cvar_Get ("cl_framerate", "0", CVAR_TEMP);
// init autoswitch so the ui will have it correctly even
// if the cgame hasn't been started
Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE);
m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE);
m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE);
m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE);
m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE);
m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE);
// ~ and `, as keys and characters
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60 0xb2", CVAR_ARCHIVE);
cl_consoleUseScanCode = Cvar_Get( "cl_consoleUseScanCode", "1", CVAR_ARCHIVE );
// userinfo
#ifdef JK2_MODE
Cvar_Get ("name", "Kyle", CVAR_USERINFO | CVAR_ARCHIVE );
#else
Cvar_Get ("name", "Jaden", CVAR_USERINFO | CVAR_ARCHIVE );
#endif
#ifdef JK2_MODE
// this is required for savegame compatibility - not ever actually used
Cvar_Get ("snaps", "20", CVAR_USERINFO );
Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_SAVEGAME );
#else
Cvar_Get ("sex", "f", CVAR_USERINFO | CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART );
Cvar_Get ("snd", "jaden_fmle", CVAR_USERINFO | CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART );//UI_SetSexandSoundForModel changes to match sounds.cfg for model
Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_SAVEGAME | CVAR_NORESTART);
#endif
//
// register our commands
//
Cmd_AddCommand ("cmd", CL_ForwardToServer_f);
Cmd_AddCommand ("configstrings", CL_Configstrings_f);
Cmd_AddCommand ("clientinfo", CL_Clientinfo_f);
Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f);
Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f);
Cmd_AddCommand ("disconnect", CL_Disconnect_f);
Cmd_AddCommand ("cinematic", CL_PlayCinematic_f);
Cmd_SetCommandCompletionFunc( "cinematic", CL_CompleteCinematic );
Cmd_AddCommand ("ingamecinematic", CL_PlayInGameCinematic_f);
Cmd_AddCommand ("uimenu", CL_GenericMenu_f);
Cmd_AddCommand ("datapad", CL_DataPad_f);
Cmd_AddCommand ("endscreendissolve", CL_EndScreenDissolve_f);
CL_InitRef();
CL_StartHunkUsers();
SCR_Init ();
Cbuf_Execute ();
Cvar_Set( "cl_running", "1" );
Com_Printf( "----- Client Initialization Complete -----\n" );
}
/*
===============
CL_Shutdown
===============
*/
void CL_Shutdown( void ) {
static qboolean recursive = qfalse;
if ( !com_cl_running || !com_cl_running->integer ) {
return;
}
Com_Printf( "----- CL_Shutdown -----\n" );
if ( recursive ) {
Com_Printf( "WARNING: Recursive shutdown\n" );
return;
}
recursive = qtrue;
CL_ShutdownUI();
CL_Disconnect();
S_Shutdown();
CL_ShutdownRef(qfalse);
Cmd_RemoveCommand ("cmd");
Cmd_RemoveCommand ("configstrings");
Cmd_RemoveCommand ("clientinfo");
Cmd_RemoveCommand ("snd_restart");
Cmd_RemoveCommand ("vid_restart");
Cmd_RemoveCommand ("disconnect");
Cmd_RemoveCommand ("cinematic");
Cmd_RemoveCommand ("ingamecinematic");
Cmd_RemoveCommand ("uimenu");
Cmd_RemoveCommand ("datapad");
Cmd_RemoveCommand ("endscreendissolve");
Cvar_Set( "cl_running", "0" );
recursive = qfalse;
memset( &cls, 0, sizeof( cls ) );
Com_Printf( "-----------------------\n" );
}
| ./CrossVul/dataset_final_sorted/CWE-269/cpp/good_3234_0 |
crossvul-cpp_data_bad_3234_0 | /*
===========================================================================
Copyright (C) 1999 - 2005, Id Software, Inc.
Copyright (C) 2000 - 2013, Raven Software, Inc.
Copyright (C) 2001 - 2013, Activision, Inc.
Copyright (C) 2005 - 2015, ioquake3 contributors
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
// cl_main.c -- client main loop
#include "../server/exe_headers.h"
#include "client.h"
#include "client_ui.h"
#include <limits.h>
#include "../ghoul2/G2.h"
#include "qcommon/stringed_ingame.h"
#include "sys/sys_loadlib.h"
#include "qcommon/ojk_saved_game.h"
#define RETRANSMIT_TIMEOUT 3000 // time between connection packet retransmits
cvar_t *cl_renderer;
cvar_t *cl_nodelta;
cvar_t *cl_debugMove;
cvar_t *cl_noprint;
cvar_t *cl_timeout;
cvar_t *cl_packetdup;
cvar_t *cl_timeNudge;
cvar_t *cl_showTimeDelta;
cvar_t *cl_newClock=0;
cvar_t *cl_shownet;
cvar_t *cl_avidemo;
cvar_t *cl_pano;
cvar_t *cl_panoNumShots;
cvar_t *cl_skippingcin;
cvar_t *cl_endcredits;
cvar_t *cl_freelook;
cvar_t *cl_sensitivity;
cvar_t *cl_mouseAccel;
cvar_t *cl_showMouseRate;
cvar_t *cl_framerate;
cvar_t *m_pitch;
cvar_t *m_yaw;
cvar_t *m_forward;
cvar_t *m_side;
cvar_t *m_filter;
cvar_t *cl_activeAction;
cvar_t *cl_allowAltEnter;
cvar_t *cl_inGameVideo;
cvar_t *cl_consoleKeys;
cvar_t *cl_consoleUseScanCode;
clientActive_t cl;
clientConnection_t clc;
clientStatic_t cls;
// Structure containing functions exported from refresh DLL
refexport_t re;
static void *rendererLib = NULL;
//RAZFIXME: BAD BAD, maybe? had to move it out of ghoul2_shared.h -> CGhoul2Info_v at the least..
IGhoul2InfoArray &_TheGhoul2InfoArray( void ) {
return re.TheGhoul2InfoArray();
}
static void CL_ShutdownRef( qboolean restarting );
void CL_InitRef( void );
void CL_CheckForResend( void );
/*
=======================================================================
CLIENT RELIABLE COMMAND COMMUNICATION
=======================================================================
*/
/*
======================
CL_AddReliableCommand
The given command will be transmitted to the server, and is gauranteed to
not have future usercmd_t executed before it is executed
======================
*/
void CL_AddReliableCommand( const char *cmd ) {
int index;
// if we would be losing an old command that hasn't been acknowledged,
// we must drop the connection
if ( clc.reliableSequence - clc.reliableAcknowledge > MAX_RELIABLE_COMMANDS ) {
Com_Error( ERR_DROP, "Client command overflow" );
}
clc.reliableSequence++;
index = clc.reliableSequence & ( MAX_RELIABLE_COMMANDS - 1 );
if ( clc.reliableCommands[ index ] ) {
Z_Free( clc.reliableCommands[ index ] );
}
clc.reliableCommands[ index ] = CopyString( cmd );
}
//======================================================================
/*
=================
CL_FlushMemory
Called by CL_MapLoading, CL_Connect_f, and CL_ParseGamestate the only
ways a client gets into a game
Also called by Com_Error
=================
*/
void CL_FlushMemory( void ) {
// clear sounds (moved higher up within this func to avoid the odd sound stutter)
S_DisableSounds();
// unload the old VM
CL_ShutdownCGame();
CL_ShutdownUI();
if ( re.Shutdown ) {
re.Shutdown( qfalse, qfalse ); // don't destroy window or context
}
//rwwFIXMEFIXME: The game server appears to continue running, so clearing common bsp data causes crashing and other bad things
/*
CM_ClearMap();
*/
cls.soundRegistered = qfalse;
cls.rendererStarted = qfalse;
}
/*
=====================
CL_MapLoading
A local server is starting to load a map, so update the
screen to let the user know about it, then dump all client
memory on the hunk from cgame, ui, and renderer
=====================
*/
void CL_MapLoading( void ) {
if ( !com_cl_running->integer ) {
return;
}
Con_Close();
Key_SetCatcher( 0 );
// if we are already connected to the local host, stay connected
if ( cls.state >= CA_CONNECTED && !Q_stricmp( cls.servername, "localhost" ) ) {
cls.state = CA_CONNECTED; // so the connect screen is drawn
memset( cls.updateInfoString, 0, sizeof( cls.updateInfoString ) );
// memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) );
memset( &cl.gameState, 0, sizeof( cl.gameState ) );
clc.lastPacketSentTime = -9999;
SCR_UpdateScreen();
} else {
// clear nextmap so the cinematic shutdown doesn't execute it
Cvar_Set( "nextmap", "" );
CL_Disconnect();
Q_strncpyz( cls.servername, "localhost", sizeof(cls.servername) );
cls.state = CA_CHALLENGING; // so the connect screen is drawn
Key_SetCatcher( 0 );
SCR_UpdateScreen();
clc.connectTime = -RETRANSMIT_TIMEOUT;
NET_StringToAdr( cls.servername, &clc.serverAddress);
// we don't need a challenge on the localhost
CL_CheckForResend();
}
CL_FlushMemory();
}
/*
=====================
CL_ClearState
Called before parsing a gamestate
=====================
*/
void CL_ClearState (void) {
CL_ShutdownCGame();
S_StopAllSounds();
memset( &cl, 0, sizeof( cl ) );
}
/*
=====================
CL_FreeReliableCommands
Wipes all reliableCommands strings from clc
=====================
*/
void CL_FreeReliableCommands( void )
{
// wipe the client connection
for ( int i = 0 ; i < MAX_RELIABLE_COMMANDS ; i++ ) {
if ( clc.reliableCommands[i] ) {
Z_Free( clc.reliableCommands[i] );
clc.reliableCommands[i] = NULL;
}
}
}
/*
=====================
CL_Disconnect
Called when a connection, or cinematic is being terminated.
Goes from a connected state to either a menu state or a console state
Sends a disconnect message to the server
This is also called on Com_Error and Com_Quit, so it shouldn't cause any errors
=====================
*/
void CL_Disconnect( void ) {
if ( !com_cl_running || !com_cl_running->integer ) {
return;
}
if (cls.uiStarted)
UI_SetActiveMenu( NULL,NULL );
SCR_StopCinematic ();
S_ClearSoundBuffer();
// send a disconnect message to the server
// send it a few times in case one is dropped
if ( cls.state >= CA_CONNECTED ) {
CL_AddReliableCommand( "disconnect" );
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
CL_ClearState ();
CL_FreeReliableCommands();
extern void CL_FreeServerCommands(void);
CL_FreeServerCommands();
memset( &clc, 0, sizeof( clc ) );
cls.state = CA_DISCONNECTED;
// allow cheats locally
Cvar_Set( "timescale", "1" );//jic we were skipping
Cvar_Set( "skippingCinematic", "0" );//jic we were skipping
}
/*
===================
CL_ForwardCommandToServer
adds the current command line as a clientCommand
things like godmode, noclip, etc, are commands directed to the server,
so when they are typed in at the console, they will need to be forwarded.
===================
*/
void CL_ForwardCommandToServer( void ) {
const char *cmd;
char string[MAX_STRING_CHARS];
cmd = Cmd_Argv(0);
// ignore key up commands
if ( cmd[0] == '-' ) {
return;
}
if ( cls.state != CA_ACTIVE || cmd[0] == '+' ) {
Com_Printf ("Unknown command \"%s\"\n", cmd);
return;
}
if ( Cmd_Argc() > 1 ) {
Com_sprintf( string, sizeof(string), "%s %s", cmd, Cmd_Args() );
} else {
Q_strncpyz( string, cmd, sizeof(string) );
}
CL_AddReliableCommand( string );
}
/*
======================================================================
CONSOLE COMMANDS
======================================================================
*/
/*
==================
CL_ForwardToServer_f
==================
*/
void CL_ForwardToServer_f( void ) {
if ( cls.state != CA_ACTIVE ) {
Com_Printf ("Not connected to a server.\n");
return;
}
// don't forward the first argument
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand( Cmd_Args() );
}
}
/*
==================
CL_Disconnect_f
==================
*/
void CL_Disconnect_f( void ) {
SCR_StopCinematic();
//FIXME:
// TA codebase added additional CA_CINEMATIC check below, presumably so they could play cinematics
// in the menus when disconnected, although having the SCR_StopCinematic() call above is weird.
// Either there's a bug, or the new version of that function conditionally-doesn't stop cinematics...
//
if ( cls.state != CA_DISCONNECTED && cls.state != CA_CINEMATIC ) {
Com_Error (ERR_DISCONNECT, "Disconnected from server");
}
}
/*
=================
CL_Vid_Restart_f
Restart the video subsystem
=================
*/
void CL_Vid_Restart_f( void ) {
S_StopAllSounds(); // don't let them loop during the restart
S_BeginRegistration(); // all sound handles are now invalid
CL_ShutdownRef(qtrue);
CL_ShutdownUI();
CL_ShutdownCGame();
//rww - sof2mp does this here, but it seems to cause problems in this codebase.
// CM_ClearMap();
CL_InitRef();
cls.rendererStarted = qfalse;
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.soundRegistered = qfalse;
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
}
/*
=================
CL_Snd_Restart_f
Restart the sound subsystem
The cgame and game must also be forced to restart because
handles will be invalid
=================
*/
void CL_Snd_Restart_f( void ) {
S_Shutdown();
S_Init();
// CL_Vid_Restart_f();
extern qboolean s_soundMuted;
s_soundMuted = qfalse; // we can play again
S_RestartMusic();
extern void S_ReloadAllUsedSounds(void);
S_ReloadAllUsedSounds();
extern void AS_ParseSets(void);
AS_ParseSets();
}
/*
==================
CL_Configstrings_f
==================
*/
void CL_Configstrings_f( void ) {
int i;
int ofs;
if ( cls.state != CA_ACTIVE ) {
Com_Printf( "Not connected to a server.\n");
return;
}
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
ofs = cl.gameState.stringOffsets[ i ];
if ( !ofs ) {
continue;
}
Com_Printf( "%4i: %s\n", i, cl.gameState.stringData + ofs );
}
}
/*
==============
CL_Clientinfo_f
==============
*/
void CL_Clientinfo_f( void ) {
Com_Printf( "--------- Client Information ---------\n" );
Com_Printf( "state: %i\n", cls.state );
Com_Printf( "Server: %s\n", cls.servername );
Com_Printf ("User info settings:\n");
Info_Print( Cvar_InfoString( CVAR_USERINFO ) );
Com_Printf( "--------------------------------------\n" );
}
//====================================================================
void UI_UpdateConnectionString( const char *string );
/*
=================
CL_CheckForResend
Resend a connect message if the last one has timed out
=================
*/
void CL_CheckForResend( void ) {
int port;
char info[MAX_INFO_STRING];
// if ( cls.state == CA_CINEMATIC )
if ( cls.state == CA_CINEMATIC || CL_IsRunningInGameCinematic())
{
return;
}
// resend if we haven't gotten a reply yet
if ( cls.state < CA_CONNECTING || cls.state > CA_CHALLENGING ) {
return;
}
if ( cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT ) {
return;
}
clc.connectTime = cls.realtime; // for retransmit requests
clc.connectPacketCount++;
// requesting a challenge
switch ( cls.state ) {
case CA_CONNECTING:
UI_UpdateConnectionString( va("(%i)", clc.connectPacketCount ) );
NET_OutOfBandPrint(NS_CLIENT, clc.serverAddress, "getchallenge");
break;
case CA_CHALLENGING:
// sending back the challenge
port = Cvar_VariableIntegerValue("net_qport");
UI_UpdateConnectionString( va("(%i)", clc.connectPacketCount ) );
Q_strncpyz( info, Cvar_InfoString( CVAR_USERINFO ), sizeof( info ) );
Info_SetValueForKey( info, "protocol", va("%i", PROTOCOL_VERSION ) );
Info_SetValueForKey( info, "qport", va("%i", port ) );
Info_SetValueForKey( info, "challenge", va("%i", clc.challenge ) );
NET_OutOfBandPrint( NS_CLIENT, clc.serverAddress, "connect \"%s\"", info );
// the most current userinfo has been sent, so watch for any
// newer changes to userinfo variables
cvar_modifiedFlags &= ~CVAR_USERINFO;
break;
default:
Com_Error( ERR_FATAL, "CL_CheckForResend: bad cls.state" );
}
}
/*
===================
CL_DisconnectPacket
Sometimes the server can drop the client and the netchan based
disconnect can be lost. If the client continues to send packets
to the server, the server will send out of band disconnect packets
to the client so it doesn't have to wait for the full timeout period.
===================
*/
void CL_DisconnectPacket( netadr_t from ) {
if ( cls.state != CA_ACTIVE ) {
return;
}
// if not from our server, ignore it
if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
return;
}
// if we have received packets within three seconds, ignore it
// (it might be a malicious spoof)
if ( cls.realtime - clc.lastPacketTime < 3000 ) {
return;
}
// drop the connection (FIXME: connection dropped dialog)
Com_Printf( "Server disconnected for unknown reason\n" );
CL_Disconnect();
}
/*
=================
CL_ConnectionlessPacket
Responses to broadcasts, etc
=================
*/
void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) {
char *s;
const char *c;
MSG_BeginReading( msg );
MSG_ReadLong( msg ); // skip the -1
s = MSG_ReadStringLine( msg );
Cmd_TokenizeString( s );
c = Cmd_Argv(0);
Com_DPrintf ("CL packet %s: %s\n", NET_AdrToString(from), c);
// challenge from the server we are connecting to
if ( !strcmp(c, "challengeResponse") ) {
if ( cls.state != CA_CONNECTING ) {
Com_Printf( "Unwanted challenge response received. Ignored.\n" );
} else {
// start sending challenge repsonse instead of challenge request packets
clc.challenge = atoi(Cmd_Argv(1));
cls.state = CA_CHALLENGING;
clc.connectPacketCount = 0;
clc.connectTime = -99999;
// take this address as the new server address. This allows
// a server proxy to hand off connections to multiple servers
clc.serverAddress = from;
}
return;
}
// server connection
if ( !strcmp(c, "connectResponse") ) {
if ( cls.state >= CA_CONNECTED ) {
Com_Printf ("Dup connect received. Ignored.\n");
return;
}
if ( cls.state != CA_CHALLENGING ) {
Com_Printf ("connectResponse packet while not connecting. Ignored.\n");
return;
}
if ( !NET_CompareBaseAdr( from, clc.serverAddress ) ) {
Com_Printf( "connectResponse from a different address. Ignored.\n" );
Com_Printf( "%s should have been %s\n", NET_AdrToString( from ),
NET_AdrToString( clc.serverAddress ) );
return;
}
Netchan_Setup (NS_CLIENT, &clc.netchan, from, Cvar_VariableIntegerValue( "net_qport" ) );
cls.state = CA_CONNECTED;
clc.lastPacketSentTime = -9999; // send first packet immediately
return;
}
// a disconnect message from the server, which will happen if the server
// dropped the connection but it is still getting packets from us
if (!strcmp(c, "disconnect")) {
CL_DisconnectPacket( from );
return;
}
// echo request from server
if ( !strcmp(c, "echo") ) {
NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv(1) );
return;
}
// print request from server
if ( !strcmp(c, "print") ) {
s = MSG_ReadString( msg );
UI_UpdateConnectionMessageString( s );
Com_Printf( "%s", s );
return;
}
Com_DPrintf ("Unknown connectionless packet command.\n");
}
/*
=================
CL_PacketEvent
A packet has arrived from the main event loop
=================
*/
void CL_PacketEvent( netadr_t from, msg_t *msg ) {
clc.lastPacketTime = cls.realtime;
if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) {
CL_ConnectionlessPacket( from, msg );
return;
}
if ( cls.state < CA_CONNECTED ) {
return; // can't be a valid sequenced packet
}
if ( msg->cursize < 8 ) {
Com_Printf ("%s: Runt packet\n",NET_AdrToString( from ));
return;
}
//
// packet from server
//
if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
Com_DPrintf ("%s:sequenced packet without connection\n"
,NET_AdrToString( from ) );
// FIXME: send a client disconnect?
return;
}
if (!Netchan_Process( &clc.netchan, msg) ) {
return; // out of order, duplicated, etc
}
clc.lastPacketTime = cls.realtime;
CL_ParseServerMessage( msg );
}
/*
==================
CL_CheckTimeout
==================
*/
void CL_CheckTimeout( void ) {
//
// check timeout
//
if ( ( !CL_CheckPaused() || !sv_paused->integer )
// && cls.state >= CA_CONNECTED && cls.state != CA_CINEMATIC
&& cls.state >= CA_CONNECTED && (cls.state != CA_CINEMATIC && !CL_IsRunningInGameCinematic())
&& cls.realtime - clc.lastPacketTime > cl_timeout->value*1000) {
if (++cl.timeoutcount > 5) { // timeoutcount saves debugger
Com_Printf ("\nServer connection timed out.\n");
CL_Disconnect ();
return;
}
} else {
cl.timeoutcount = 0;
}
}
/*
==================
CL_CheckPaused
Check whether client has been paused.
==================
*/
qboolean CL_CheckPaused(void)
{
// if cl_paused->modified is set, the cvar has only been changed in
// this frame. Keep paused in this frame to ensure the server doesn't
// lag behind.
if(cl_paused->integer || cl_paused->modified)
return qtrue;
return qfalse;
}
//============================================================================
/*
==================
CL_CheckUserinfo
==================
*/
void CL_CheckUserinfo( void ) {
if ( cls.state < CA_CHALLENGING ) {
return;
}
// don't overflow the reliable command buffer when paused
if ( CL_CheckPaused() ) {
return;
}
// send a reliable userinfo update if needed
if ( cvar_modifiedFlags & CVAR_USERINFO ) {
cvar_modifiedFlags &= ~CVAR_USERINFO;
CL_AddReliableCommand( va("userinfo \"%s\"", Cvar_InfoString( CVAR_USERINFO ) ) );
}
}
/*
==================
CL_Frame
==================
*/
extern cvar_t *cl_newClock;
static unsigned int frameCount;
float avgFrametime=0.0;
void CL_Frame ( int msec,float fractionMsec ) {
if ( !com_cl_running->integer ) {
return;
}
// load the ref / cgame if needed
CL_StartHunkUsers();
if ( cls.state == CA_DISCONNECTED && !( Key_GetCatcher( ) & KEYCATCH_UI )
&& !com_sv_running->integer ) {
// if disconnected, bring up the menu
if (!CL_CheckPendingCinematic()) // this avoid having the menu flash for one frame before pending cinematics
{
UI_SetActiveMenu( "mainMenu",NULL );
}
}
// if recording an avi, lock to a fixed fps
if ( cl_avidemo->integer ) {
// save the current screen
if ( cls.state == CA_ACTIVE ) {
if (cl_avidemo->integer > 0) {
Cbuf_ExecuteText( EXEC_NOW, "screenshot silent\n" );
} else {
Cbuf_ExecuteText( EXEC_NOW, "screenshot_tga silent\n" );
}
}
// fixed time for next frame
if (cl_avidemo->integer > 0) {
msec = 1000 / cl_avidemo->integer;
} else {
msec = 1000 / -cl_avidemo->integer;
}
}
// save the msec before checking pause
cls.realFrametime = msec;
// decide the simulation time
cls.frametime = msec;
if(cl_framerate->integer)
{
avgFrametime+=msec;
char mess[256];
if(!(frameCount&0x1f))
{
sprintf(mess,"Frame rate=%f\n\n",1000.0f*(1.0/(avgFrametime/32.0f)));
// OutputDebugString(mess);
Com_Printf(mess);
avgFrametime=0.0f;
}
frameCount++;
}
cls.frametimeFraction=fractionMsec;
cls.realtime += msec;
cls.realtimeFraction+=fractionMsec;
if (cls.realtimeFraction>=1.0f)
{
if (cl_newClock&&cl_newClock->integer)
{
cls.realtime++;
}
cls.realtimeFraction-=1.0f;
}
if ( cl_timegraph->integer ) {
SCR_DebugGraph ( cls.realFrametime * 0.25, 0 );
}
// see if we need to update any userinfo
CL_CheckUserinfo();
// if we haven't gotten a packet in a long time,
// drop the connection
CL_CheckTimeout();
// send intentions now
CL_SendCmd();
// resend a connection request if necessary
CL_CheckForResend();
// decide on the serverTime to render
CL_SetCGameTime();
if (cl_pano->integer && cls.state == CA_ACTIVE) { //grab some panoramic shots
int i = 1;
int pref = cl_pano->integer;
int oldnoprint = cl_noprint->integer;
Con_Close();
cl_noprint->integer = 1; //hide the screen shot msgs
for (; i <= cl_panoNumShots->integer; i++) {
Cvar_SetValue( "pano", i );
SCR_UpdateScreen();// update the screen
Cbuf_ExecuteText( EXEC_NOW, va("screenshot %dpano%02d\n", pref, i) ); //grab this screen
}
Cvar_SetValue( "pano", 0 ); //done
cl_noprint->integer = oldnoprint;
}
if (cl_skippingcin->integer && !cl_endcredits->integer && !com_developer->integer ) {
if (cl_skippingcin->modified){
S_StopSounds(); //kill em all but music
cl_skippingcin->modified=qfalse;
Com_Printf (S_COLOR_YELLOW "%s", SE_GetString("CON_TEXT_SKIPPING"));
SCR_UpdateScreen();
}
} else {
// update the screen
SCR_UpdateScreen();
}
// update audio
S_Update();
// advance local effects for next frame
SCR_RunCinematic();
Con_RunConsole();
cls.framecount++;
}
//============================================================================
/*
============
CL_ShutdownRef
============
*/
static void CL_ShutdownRef( qboolean restarting ) {
if ( re.Shutdown ) {
re.Shutdown( qtrue, restarting );
}
memset( &re, 0, sizeof( re ) );
if ( rendererLib != NULL ) {
Sys_UnloadDll (rendererLib);
rendererLib = NULL;
}
}
/*
============================
CL_StartSound
Convenience function for the sound system to be started
REALLY early on Xbox, helps with memory fragmentation.
============================
*/
void CL_StartSound( void ) {
if ( !cls.soundStarted ) {
cls.soundStarted = qtrue;
S_Init();
}
if ( !cls.soundRegistered ) {
cls.soundRegistered = qtrue;
S_BeginRegistration();
}
}
/*
============
CL_InitRenderer
============
*/
void CL_InitRenderer( void ) {
// this sets up the renderer and calls R_Init
re.BeginRegistration( &cls.glconfig );
// load character sets
cls.charSetShader = re.RegisterShaderNoMip("gfx/2d/charsgrid_med");
cls.whiteShader = re.RegisterShader( "white" );
cls.consoleShader = re.RegisterShader( "console" );
g_console_field_width = cls.glconfig.vidWidth / SMALLCHAR_WIDTH - 2;
g_consoleField.widthInChars = g_console_field_width;
}
/*
============================
CL_StartHunkUsers
After the server has cleared the hunk, these will need to be restarted
This is the only place that any of these functions are called from
============================
*/
void CL_StartHunkUsers( void ) {
if ( !com_cl_running->integer ) {
return;
}
if ( !cls.rendererStarted ) {
cls.rendererStarted = qtrue;
CL_InitRenderer();
}
if ( !cls.soundStarted ) {
cls.soundStarted = qtrue;
S_Init();
}
if ( !cls.soundRegistered ) {
cls.soundRegistered = qtrue;
S_BeginRegistration();
}
//we require the ui to be loaded here or else it crashes trying to access the ui on command line map loads
if ( !cls.uiStarted ) {
cls.uiStarted = qtrue;
CL_InitUI();
}
// if ( !cls.cgameStarted && cls.state > CA_CONNECTED && cls.state != CA_CINEMATIC ) {
if ( !cls.cgameStarted && cls.state > CA_CONNECTED && (cls.state != CA_CINEMATIC && !CL_IsRunningInGameCinematic()) )
{
cls.cgameStarted = qtrue;
CL_InitCGame();
}
}
/*
================
CL_RefPrintf
DLL glue
================
*/
void QDECL CL_RefPrintf( int print_level, const char *fmt, ...) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start (argptr,fmt);
Q_vsnprintf(msg, sizeof(msg), fmt, argptr);
va_end (argptr);
if ( print_level == PRINT_ALL ) {
Com_Printf ("%s", msg);
} else if ( print_level == PRINT_WARNING ) {
Com_Printf (S_COLOR_YELLOW "%s", msg); // yellow
} else if ( print_level == PRINT_DEVELOPER ) {
Com_DPrintf (S_COLOR_RED "%s", msg); // red
}
}
/*
============
String_GetStringValue
DLL glue, but highly reusuable DLL glue at that
============
*/
const char *String_GetStringValue( const char *reference )
{
#ifndef JK2_MODE
return SE_GetString(reference);
#else
return JK2SP_GetStringTextString(reference);
#endif
}
extern qboolean gbAlreadyDoingLoad;
extern void *gpvCachedMapDiskImage;
extern char gsCachedMapDiskImage[MAX_QPATH];
extern qboolean gbUsingCachedMapDataRightNow;
char *get_gsCachedMapDiskImage( void )
{
return gsCachedMapDiskImage;
}
void *get_gpvCachedMapDiskImage( void )
{
return gpvCachedMapDiskImage;
}
qboolean *get_gbUsingCachedMapDataRightNow( void )
{
return &gbUsingCachedMapDataRightNow;
}
qboolean *get_gbAlreadyDoingLoad( void )
{
return &gbAlreadyDoingLoad;
}
int get_com_frameTime( void )
{
return com_frameTime;
}
void *CL_Malloc(int iSize, memtag_t eTag, qboolean bZeroit, int iAlign)
{
return Z_Malloc(iSize, eTag, bZeroit);
}
/*
============
CL_InitRef
============
*/
extern qboolean S_FileExists( const char *psFilename );
extern bool CM_CullWorldBox (const cplane_t *frustum, const vec3pair_t bounds);
extern qboolean SND_RegisterAudio_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel /* 99% qfalse */);
extern cvar_t *Cvar_Set2( const char *var_name, const char *value, qboolean force);
extern CMiniHeap *G2VertSpaceServer;
static CMiniHeap *GetG2VertSpaceServer( void ) {
return G2VertSpaceServer;
}
// NOTENOTE: If you change the output name of rd-vanilla, change this define too!
#ifdef JK2_MODE
#define DEFAULT_RENDER_LIBRARY "rdjosp-vanilla"
#else
#define DEFAULT_RENDER_LIBRARY "rdsp-vanilla"
#endif
void CL_InitRef( void ) {
refexport_t *ret;
static refimport_t rit;
char dllName[MAX_OSPATH];
GetRefAPI_t GetRefAPI;
Com_Printf( "----- Initializing Renderer ----\n" );
cl_renderer = Cvar_Get( "cl_renderer", DEFAULT_RENDER_LIBRARY, CVAR_ARCHIVE|CVAR_LATCH );
Com_sprintf( dllName, sizeof( dllName ), "%s_" ARCH_STRING DLL_EXT, cl_renderer->string );
if( !(rendererLib = Sys_LoadDll( dllName, qfalse )) && strcmp( cl_renderer->string, cl_renderer->resetString ) )
{
Com_Printf( "failed: trying to load fallback renderer\n" );
Cvar_ForceReset( "cl_renderer" );
Com_sprintf( dllName, sizeof( dllName ), DEFAULT_RENDER_LIBRARY "_" ARCH_STRING DLL_EXT );
rendererLib = Sys_LoadDll( dllName, qfalse );
}
if ( !rendererLib ) {
Com_Error( ERR_FATAL, "Failed to load renderer\n" );
}
memset( &rit, 0, sizeof( rit ) );
GetRefAPI = (GetRefAPI_t)Sys_LoadFunction( rendererLib, "GetRefAPI" );
if ( !GetRefAPI )
Com_Error( ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError() );
#define RIT(y) rit.y = y
RIT(CIN_PlayCinematic);
RIT(CIN_RunCinematic);
RIT(CIN_UploadCinematic);
RIT(CL_IsRunningInGameCinematic);
RIT(Cmd_AddCommand);
RIT(Cmd_Argc);
RIT(Cmd_ArgsBuffer);
RIT(Cmd_Argv);
RIT(Cmd_ExecuteString);
RIT(Cmd_RemoveCommand);
RIT(CM_ClusterPVS);
RIT(CM_CullWorldBox);
RIT(CM_DeleteCachedMap);
RIT(CM_DrawDebugSurface);
RIT(CM_PointContents);
RIT(Cvar_Get);
RIT(Cvar_Set);
RIT(Cvar_SetValue);
RIT(Cvar_CheckRange);
RIT(Cvar_VariableIntegerValue);
RIT(Cvar_VariableString);
RIT(Cvar_VariableStringBuffer);
RIT(Cvar_VariableValue);
RIT(FS_FCloseFile);
RIT(FS_FileIsInPAK);
RIT(FS_FOpenFileByMode);
RIT(FS_FOpenFileRead);
RIT(FS_FOpenFileWrite);
RIT(FS_FreeFile);
RIT(FS_FreeFileList);
RIT(FS_ListFiles);
RIT(FS_Read);
RIT(FS_ReadFile);
RIT(FS_Write);
RIT(FS_WriteFile);
RIT(Hunk_ClearToMark);
RIT(SND_RegisterAudio_LevelLoadEnd);
//RIT(SV_PointContents);
RIT(SV_Trace);
RIT(S_RestartMusic);
RIT(Z_Free);
rit.Malloc=CL_Malloc;
RIT(Z_MemSize);
RIT(Z_MorphMallocTag);
RIT(Hunk_ClearToMark);
rit.WIN_Init = WIN_Init;
rit.WIN_SetGamma = WIN_SetGamma;
rit.WIN_Shutdown = WIN_Shutdown;
rit.WIN_Present = WIN_Present;
rit.GL_GetProcAddress = WIN_GL_GetProcAddress;
rit.GL_ExtensionSupported = WIN_GL_ExtensionSupported;
rit.PD_Load = PD_Load;
rit.PD_Store = PD_Store;
rit.Error = Com_Error;
rit.FS_FileExists = S_FileExists;
rit.GetG2VertSpaceServer = GetG2VertSpaceServer;
rit.LowPhysicalMemory = Sys_LowPhysicalMemory;
rit.Milliseconds = Sys_Milliseconds2;
rit.Printf = CL_RefPrintf;
rit.SE_GetString = String_GetStringValue;
rit.SV_Trace = SV_Trace;
rit.gpvCachedMapDiskImage = get_gpvCachedMapDiskImage;
rit.gsCachedMapDiskImage = get_gsCachedMapDiskImage;
rit.gbUsingCachedMapDataRightNow = get_gbUsingCachedMapDataRightNow;
rit.gbAlreadyDoingLoad = get_gbAlreadyDoingLoad;
rit.com_frameTime = get_com_frameTime;
rit.SV_PointContents = SV_PointContents;
rit.saved_game = &ojk::SavedGame::get_instance();
ret = GetRefAPI( REF_API_VERSION, &rit );
if ( !ret ) {
Com_Error (ERR_FATAL, "Couldn't initialize refresh" );
}
re = *ret;
Com_Printf( "-------------------------------\n");
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
}
//===========================================================================================
void CL_CompleteCinematic( char *args, int argNum );
/*
====================
CL_Init
====================
*/
void CL_Init( void ) {
Com_Printf( "----- Client Initialization -----\n" );
#ifdef JK2_MODE
JK2SP_Register("con_text", SP_REGISTER_REQUIRED); //reference is CON_TEXT
JK2SP_Register("keynames", SP_REGISTER_REQUIRED); // reference is KEYNAMES
#endif
Con_Init ();
CL_ClearState ();
cls.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
//cls.keyCatchers = KEYCATCH_CONSOLE;
cls.realtime = 0;
cls.realtimeFraction=0.0f; // fraction of a msec accumulated
CL_InitInput ();
//
// register our variables
//
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
cl_timeout = Cvar_Get ("cl_timeout", "125", 0);
cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP );
cl_newClock = Cvar_Get ("cl_newClock", "1", 0);
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_avidemo = Cvar_Get ("cl_avidemo", "0", 0);
cl_pano = Cvar_Get ("pano", "0", 0);
cl_panoNumShots= Cvar_Get ("panoNumShots", "10", CVAR_ARCHIVE);
cl_skippingcin = Cvar_Get ("skippingCinematic", "0", CVAR_ROM);
cl_endcredits = Cvar_Get ("cg_endcredits", "0", 0);
cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE);
cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE);
cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", CVAR_ARCHIVE);
cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE );
cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE);
cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE);
cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE);
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE );
cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0);
cl_allowAltEnter = Cvar_Get ("cl_allowAltEnter", "1", CVAR_ARCHIVE);
cl_inGameVideo = Cvar_Get ("cl_inGameVideo", "1", CVAR_ARCHIVE);
cl_framerate = Cvar_Get ("cl_framerate", "0", CVAR_TEMP);
// init autoswitch so the ui will have it correctly even
// if the cgame hasn't been started
Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE);
m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE);
m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE);
m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE);
m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE);
m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE);
// ~ and `, as keys and characters
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60 0xb2", CVAR_ARCHIVE);
cl_consoleUseScanCode = Cvar_Get( "cl_consoleUseScanCode", "1", CVAR_ARCHIVE );
// userinfo
#ifdef JK2_MODE
Cvar_Get ("name", "Kyle", CVAR_USERINFO | CVAR_ARCHIVE );
#else
Cvar_Get ("name", "Jaden", CVAR_USERINFO | CVAR_ARCHIVE );
#endif
#ifdef JK2_MODE
// this is required for savegame compatibility - not ever actually used
Cvar_Get ("snaps", "20", CVAR_USERINFO );
Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_SAVEGAME );
#else
Cvar_Get ("sex", "f", CVAR_USERINFO | CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART );
Cvar_Get ("snd", "jaden_fmle", CVAR_USERINFO | CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART );//UI_SetSexandSoundForModel changes to match sounds.cfg for model
Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_SAVEGAME | CVAR_NORESTART);
#endif
//
// register our commands
//
Cmd_AddCommand ("cmd", CL_ForwardToServer_f);
Cmd_AddCommand ("configstrings", CL_Configstrings_f);
Cmd_AddCommand ("clientinfo", CL_Clientinfo_f);
Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f);
Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f);
Cmd_AddCommand ("disconnect", CL_Disconnect_f);
Cmd_AddCommand ("cinematic", CL_PlayCinematic_f);
Cmd_SetCommandCompletionFunc( "cinematic", CL_CompleteCinematic );
Cmd_AddCommand ("ingamecinematic", CL_PlayInGameCinematic_f);
Cmd_AddCommand ("uimenu", CL_GenericMenu_f);
Cmd_AddCommand ("datapad", CL_DataPad_f);
Cmd_AddCommand ("endscreendissolve", CL_EndScreenDissolve_f);
CL_InitRef();
CL_StartHunkUsers();
SCR_Init ();
Cbuf_Execute ();
Cvar_Set( "cl_running", "1" );
Com_Printf( "----- Client Initialization Complete -----\n" );
}
/*
===============
CL_Shutdown
===============
*/
void CL_Shutdown( void ) {
static qboolean recursive = qfalse;
if ( !com_cl_running || !com_cl_running->integer ) {
return;
}
Com_Printf( "----- CL_Shutdown -----\n" );
if ( recursive ) {
Com_Printf( "WARNING: Recursive shutdown\n" );
return;
}
recursive = qtrue;
CL_ShutdownUI();
CL_Disconnect();
S_Shutdown();
CL_ShutdownRef(qfalse);
Cmd_RemoveCommand ("cmd");
Cmd_RemoveCommand ("configstrings");
Cmd_RemoveCommand ("clientinfo");
Cmd_RemoveCommand ("snd_restart");
Cmd_RemoveCommand ("vid_restart");
Cmd_RemoveCommand ("disconnect");
Cmd_RemoveCommand ("cinematic");
Cmd_RemoveCommand ("ingamecinematic");
Cmd_RemoveCommand ("uimenu");
Cmd_RemoveCommand ("datapad");
Cmd_RemoveCommand ("endscreendissolve");
Cvar_Set( "cl_running", "0" );
recursive = qfalse;
memset( &cls, 0, sizeof( cls ) );
Com_Printf( "-----------------------\n" );
}
| ./CrossVul/dataset_final_sorted/CWE-269/cpp/bad_3234_0 |
crossvul-cpp_data_good_3234_2 | /*
===========================================================================
Copyright (C) 1999 - 2005, Id Software, Inc.
Copyright (C) 2000 - 2013, Raven Software, Inc.
Copyright (C) 2001 - 2013, Activision, Inc.
Copyright (C) 2005 - 2015, ioquake3 contributors
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
// cl_main.c -- client main loop
#include "client.h"
#include <limits.h>
#include "ghoul2/G2.h"
#include "qcommon/cm_public.h"
#include "qcommon/MiniHeap.h"
#include "qcommon/stringed_ingame.h"
#include "cl_cgameapi.h"
#include "cl_uiapi.h"
#include "cl_lan.h"
#include "snd_local.h"
#include "sys/sys_loadlib.h"
cvar_t *cl_renderer;
cvar_t *cl_nodelta;
cvar_t *cl_debugMove;
cvar_t *cl_noprint;
cvar_t *cl_motd;
cvar_t *cl_motdServer[MAX_MASTER_SERVERS];
cvar_t *rcon_client_password;
cvar_t *rconAddress;
cvar_t *cl_timeout;
cvar_t *cl_maxpackets;
cvar_t *cl_packetdup;
cvar_t *cl_timeNudge;
cvar_t *cl_showTimeDelta;
cvar_t *cl_freezeDemo;
cvar_t *cl_shownet;
cvar_t *cl_showSend;
cvar_t *cl_timedemo;
cvar_t *cl_aviFrameRate;
cvar_t *cl_aviMotionJpeg;
cvar_t *cl_avi2GBLimit;
cvar_t *cl_forceavidemo;
cvar_t *cl_freelook;
cvar_t *cl_sensitivity;
cvar_t *cl_mouseAccel;
cvar_t *cl_mouseAccelOffset;
cvar_t *cl_mouseAccelStyle;
cvar_t *cl_showMouseRate;
cvar_t *m_pitchVeh;
cvar_t *m_pitch;
cvar_t *m_yaw;
cvar_t *m_forward;
cvar_t *m_side;
cvar_t *m_filter;
cvar_t *cl_activeAction;
cvar_t *cl_motdString;
cvar_t *cl_allowDownload;
cvar_t *cl_allowAltEnter;
cvar_t *cl_conXOffset;
cvar_t *cl_inGameVideo;
cvar_t *cl_serverStatusResendTime;
cvar_t *cl_framerate;
// cvar to enable sending a "ja_guid" player identifier in userinfo to servers
// ja_guid is a persistent "cookie" that allows servers to track players across game sessions
cvar_t *cl_enableGuid;
cvar_t *cl_guidServerUniq;
cvar_t *cl_autolodscale;
cvar_t *cl_consoleKeys;
cvar_t *cl_consoleUseScanCode;
cvar_t *cl_lanForcePackets;
vec3_t cl_windVec;
clientActive_t cl;
clientConnection_t clc;
clientStatic_t cls;
netadr_t rcon_address;
char cl_reconnectArgs[MAX_OSPATH] = {0};
// Structure containing functions exported from refresh DLL
refexport_t *re = NULL;
static void *rendererLib = NULL;
ping_t cl_pinglist[MAX_PINGREQUESTS];
typedef struct serverStatus_s
{
char string[BIG_INFO_STRING];
netadr_t address;
int time, startTime;
qboolean pending;
qboolean print;
qboolean retrieved;
} serverStatus_t;
serverStatus_t cl_serverStatusList[MAX_SERVERSTATUSREQUESTS];
int serverStatusCount;
IHeapAllocator *G2VertSpaceClient = 0;
extern void SV_BotFrame( int time );
void CL_CheckForResend( void );
void CL_ShowIP_f(void);
void CL_ServerStatus_f(void);
void CL_ServerStatusResponse( netadr_t from, msg_t *msg );
static void CL_ShutdownRef( qboolean restarting );
/*
=======================================================================
CLIENT RELIABLE COMMAND COMMUNICATION
=======================================================================
*/
/*
======================
CL_AddReliableCommand
The given command will be transmitted to the server, and is gauranteed to
not have future usercmd_t executed before it is executed
======================
*/
void CL_AddReliableCommand( const char *cmd, qboolean isDisconnectCmd ) {
int unacknowledged = clc.reliableSequence - clc.reliableAcknowledge;
// if we would be losing an old command that hasn't been acknowledged,
// we must drop the connection
// also leave one slot open for the disconnect command in this case.
if ((isDisconnectCmd && unacknowledged > MAX_RELIABLE_COMMANDS) ||
(!isDisconnectCmd && unacknowledged >= MAX_RELIABLE_COMMANDS))
{
if(com_errorEntered)
return;
else
Com_Error(ERR_DROP, "Client command overflow");
}
Q_strncpyz(clc.reliableCommands[++clc.reliableSequence & (MAX_RELIABLE_COMMANDS - 1)],
cmd, sizeof(*clc.reliableCommands));
}
/*
=======================================================================
CLIENT SIDE DEMO RECORDING
=======================================================================
*/
/*
====================
CL_WriteDemoMessage
Dumps the current net message, prefixed by the length
====================
*/
void CL_WriteDemoMessage ( msg_t *msg, int headerBytes ) {
int len, swlen;
// write the packet sequence
len = clc.serverMessageSequence;
swlen = LittleLong( len );
FS_Write (&swlen, 4, clc.demofile);
// skip the packet sequencing information
len = msg->cursize - headerBytes;
swlen = LittleLong(len);
FS_Write (&swlen, 4, clc.demofile);
FS_Write ( msg->data + headerBytes, len, clc.demofile );
}
/*
====================
CL_StopRecording_f
stop recording a demo
====================
*/
void CL_StopRecord_f( void ) {
int len;
if ( !clc.demorecording ) {
Com_Printf ("Not recording a demo.\n");
return;
}
// finish up
len = -1;
FS_Write (&len, 4, clc.demofile);
FS_Write (&len, 4, clc.demofile);
FS_FCloseFile (clc.demofile);
clc.demofile = 0;
clc.demorecording = qfalse;
clc.spDemoRecording = qfalse;
Com_Printf ("Stopped demo.\n");
}
/*
==================
CL_DemoFilename
==================
*/
void CL_DemoFilename( char *buf, int bufSize ) {
time_t rawtime;
char timeStr[32] = {0}; // should really only reach ~19 chars
time( &rawtime );
strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime
Com_sprintf( buf, bufSize, "demo%s", timeStr );
}
/*
====================
CL_Record_f
record <demoname>
Begins recording a demo from the current position
====================
*/
static char demoName[MAX_QPATH]; // compiler bug workaround
void CL_Record_f( void ) {
char name[MAX_OSPATH];
byte bufData[MAX_MSGLEN];
msg_t buf;
int i;
int len;
entityState_t *ent;
entityState_t nullstate;
char *s;
if ( Cmd_Argc() > 2 ) {
Com_Printf ("record <demoname>\n");
return;
}
if ( clc.demorecording ) {
if (!clc.spDemoRecording) {
Com_Printf ("Already recording.\n");
}
return;
}
if ( cls.state != CA_ACTIVE ) {
Com_Printf ("You must be in a level to record.\n");
return;
}
// sync 0 doesn't prevent recording, so not forcing it off .. everyone does g_sync 1 ; record ; g_sync 0 ..
if ( NET_IsLocalAddress( clc.serverAddress ) && !Cvar_VariableValue( "g_synchronousClients" ) ) {
Com_Printf (S_COLOR_YELLOW "WARNING: You should set 'g_synchronousClients 1' for smoother demo recording\n");
}
if ( Cmd_Argc() == 2 ) {
s = Cmd_Argv(1);
Q_strncpyz( demoName, s, sizeof( demoName ) );
Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION );
} else {
// timestamp the file
CL_DemoFilename( demoName, sizeof( demoName ) );
Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION );
if ( FS_FileExists( name ) ) {
Com_Printf( "Record: Couldn't create a file\n");
return;
}
}
// open the demo file
Com_Printf ("recording to %s.\n", name);
clc.demofile = FS_FOpenFileWrite( name );
if ( !clc.demofile ) {
Com_Printf ("ERROR: couldn't open.\n");
return;
}
clc.demorecording = qtrue;
if (Cvar_VariableValue("ui_recordSPDemo")) {
clc.spDemoRecording = qtrue;
} else {
clc.spDemoRecording = qfalse;
}
Q_strncpyz( clc.demoName, demoName, sizeof( clc.demoName ) );
// don't start saving messages until a non-delta compressed message is received
clc.demowaiting = qtrue;
// write out the gamestate message
MSG_Init (&buf, bufData, sizeof(bufData));
MSG_Bitstream(&buf);
// NOTE, MRE: all server->client messages now acknowledge
MSG_WriteLong( &buf, clc.reliableSequence );
MSG_WriteByte (&buf, svc_gamestate);
MSG_WriteLong (&buf, clc.serverCommandSequence );
// configstrings
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
if ( !cl.gameState.stringOffsets[i] ) {
continue;
}
s = cl.gameState.stringData + cl.gameState.stringOffsets[i];
MSG_WriteByte (&buf, svc_configstring);
MSG_WriteShort (&buf, i);
MSG_WriteBigString (&buf, s);
}
// baselines
Com_Memset (&nullstate, 0, sizeof(nullstate));
for ( i = 0; i < MAX_GENTITIES ; i++ ) {
ent = &cl.entityBaselines[i];
if ( !ent->number ) {
continue;
}
MSG_WriteByte (&buf, svc_baseline);
MSG_WriteDeltaEntity (&buf, &nullstate, ent, qtrue );
}
MSG_WriteByte( &buf, svc_EOF );
// finished writing the gamestate stuff
// write the client num
MSG_WriteLong(&buf, clc.clientNum);
// write the checksum feed
MSG_WriteLong(&buf, clc.checksumFeed);
// Filler for old RMG system.
MSG_WriteShort ( &buf, 0 );
// finished writing the client packet
MSG_WriteByte( &buf, svc_EOF );
// write it to the demo file
len = LittleLong( clc.serverMessageSequence - 1 );
FS_Write (&len, 4, clc.demofile);
len = LittleLong (buf.cursize);
FS_Write (&len, 4, clc.demofile);
FS_Write (buf.data, buf.cursize, clc.demofile);
// the rest of the demo file will be copied from net messages
}
/*
=======================================================================
CLIENT SIDE DEMO PLAYBACK
=======================================================================
*/
/*
=================
CL_DemoCompleted
=================
*/
void CL_DemoCompleted( void ) {
if (cl_timedemo && cl_timedemo->integer) {
int time;
time = Sys_Milliseconds() - clc.timeDemoStart;
if ( time > 0 ) {
Com_Printf ("%i frames, %3.1f seconds: %3.1f fps\n", clc.timeDemoFrames,
time/1000.0, clc.timeDemoFrames*1000.0 / time);
}
}
/* CL_Disconnect( qtrue );
CL_NextDemo();
*/
//rww - The above code seems to just stick you in a no-menu state and you can't do anything there.
//I'm not sure why it ever worked in TA, but whatever. This code will bring us back to the main menu
//after a demo is finished playing instead.
CL_Disconnect_f();
S_StopAllSounds();
UIVM_SetActiveMenu( UIMENU_MAIN );
CL_NextDemo();
}
/*
=================
CL_ReadDemoMessage
=================
*/
void CL_ReadDemoMessage( void ) {
int r;
msg_t buf;
byte bufData[ MAX_MSGLEN ];
int s;
if ( !clc.demofile ) {
CL_DemoCompleted ();
return;
}
// get the sequence number
r = FS_Read( &s, 4, clc.demofile);
if ( r != 4 ) {
CL_DemoCompleted ();
return;
}
clc.serverMessageSequence = LittleLong( s );
// init the message
MSG_Init( &buf, bufData, sizeof( bufData ) );
// get the length
r = FS_Read (&buf.cursize, 4, clc.demofile);
if ( r != 4 ) {
CL_DemoCompleted ();
return;
}
buf.cursize = LittleLong( buf.cursize );
if ( buf.cursize == -1 ) {
CL_DemoCompleted ();
return;
}
if ( buf.cursize > buf.maxsize ) {
Com_Error (ERR_DROP, "CL_ReadDemoMessage: demoMsglen > MAX_MSGLEN");
}
r = FS_Read( buf.data, buf.cursize, clc.demofile );
if ( r != buf.cursize ) {
Com_Printf( "Demo file was truncated.\n");
CL_DemoCompleted ();
return;
}
clc.lastPacketTime = cls.realtime;
buf.readcount = 0;
CL_ParseServerMessage( &buf );
}
/*
====================
CL_CompleteDemoName
====================
*/
static void CL_CompleteDemoName( char *args, int argNum )
{
if( argNum == 2 )
{
char demoExt[16];
Com_sprintf(demoExt, sizeof(demoExt), ".dm_%d", PROTOCOL_VERSION);
Field_CompleteFilename( "demos", demoExt, qtrue, qtrue );
}
}
/*
====================
CL_PlayDemo_f
demo <demoname>
====================
*/
void CL_PlayDemo_f( void ) {
char name[MAX_OSPATH], extension[32];
char *arg;
if (Cmd_Argc() != 2) {
Com_Printf ("demo <demoname>\n");
return;
}
// make sure a local server is killed
// 2 means don't force disconnect of local client
Cvar_Set( "sv_killserver", "2" );
// open the demo file
arg = Cmd_Argv(1);
CL_Disconnect( qtrue );
Com_sprintf(extension, sizeof(extension), ".dm_%d", PROTOCOL_VERSION);
if ( !Q_stricmp( arg + strlen(arg) - strlen(extension), extension ) ) {
Com_sprintf (name, sizeof(name), "demos/%s", arg);
} else {
Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", arg, PROTOCOL_VERSION);
}
FS_FOpenFileRead( name, &clc.demofile, qtrue );
if (!clc.demofile) {
if (!Q_stricmp(arg, "(null)"))
{
Com_Error( ERR_DROP, SE_GetString("CON_TEXT_NO_DEMO_SELECTED") );
}
else
{
Com_Error( ERR_DROP, "couldn't open %s", name);
}
return;
}
Q_strncpyz( clc.demoName, Cmd_Argv(1), sizeof( clc.demoName ) );
Con_Close();
cls.state = CA_CONNECTED;
clc.demoplaying = qtrue;
Q_strncpyz( cls.servername, Cmd_Argv(1), sizeof( cls.servername ) );
// read demo messages until connected
while ( cls.state >= CA_CONNECTED && cls.state < CA_PRIMED ) {
CL_ReadDemoMessage();
}
// don't get the first snapshot this frame, to prevent the long
// time from the gamestate load from messing causing a time skip
clc.firstDemoFrameSkipped = qfalse;
}
/*
====================
CL_StartDemoLoop
Closing the main menu will restart the demo loop
====================
*/
void CL_StartDemoLoop( void ) {
// start the demo loop again
Cbuf_AddText ("d1\n");
Key_SetCatcher( 0 );
}
/*
==================
CL_NextDemo
Called when a demo or cinematic finishes
If the "nextdemo" cvar is set, that command will be issued
==================
*/
void CL_NextDemo( void ) {
char v[MAX_STRING_CHARS];
Q_strncpyz( v, Cvar_VariableString ("nextdemo"), sizeof(v) );
v[MAX_STRING_CHARS-1] = 0;
Com_DPrintf("CL_NextDemo: %s\n", v );
if (!v[0]) {
return;
}
Cvar_Set ("nextdemo","");
Cbuf_AddText (v);
Cbuf_AddText ("\n");
Cbuf_Execute();
}
//======================================================================
/*
=====================
CL_ShutdownAll
=====================
*/
void CL_ShutdownAll( qboolean shutdownRef ) {
if(CL_VideoRecording())
CL_CloseAVI();
if(clc.demorecording)
CL_StopRecord_f();
#if 0 //rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug.
//so it doesn't barf on shutdown saying refentities belong to each other
tr.refdef.num_entities = 0;
#endif
// clear sounds
S_DisableSounds();
// shutdown CGame
CL_ShutdownCGame();
// shutdown UI
CL_ShutdownUI();
// shutdown the renderer
if(shutdownRef)
CL_ShutdownRef( qfalse );
if ( re && re->Shutdown ) {
re->Shutdown( qfalse, qfalse ); // don't destroy window or context
}
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.rendererStarted = qfalse;
cls.soundRegistered = qfalse;
}
/*
=================
CL_FlushMemory
Called by CL_MapLoading, CL_Connect_f, CL_PlayDemo_f, and CL_ParseGamestate the only
ways a client gets into a game
Also called by Com_Error
=================
*/
void CL_FlushMemory( void ) {
// shutdown all the client stuff
CL_ShutdownAll( qfalse );
// if not running a server clear the whole hunk
if ( !com_sv_running->integer ) {
// clear collision map data
CM_ClearMap();
// clear the whole hunk
Hunk_Clear();
}
else {
// clear all the client data on the hunk
Hunk_ClearToMark();
}
CL_StartHunkUsers();
}
/*
=====================
CL_MapLoading
A local server is starting to load a map, so update the
screen to let the user know about it, then dump all client
memory on the hunk from cgame, ui, and renderer
=====================
*/
void CL_MapLoading( void ) {
if ( !com_cl_running->integer ) {
return;
}
// Set this to localhost.
Cvar_Set( "cl_currentServerAddress", "Localhost");
Cvar_Set( "cl_currentServerIP", "loopback");
Con_Close();
Key_SetCatcher( 0 );
// if we are already connected to the local host, stay connected
if ( cls.state >= CA_CONNECTED && !Q_stricmp( cls.servername, "localhost" ) ) {
cls.state = CA_CONNECTED; // so the connect screen is drawn
Com_Memset( cls.updateInfoString, 0, sizeof( cls.updateInfoString ) );
Com_Memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) );
Com_Memset( &cl.gameState, 0, sizeof( cl.gameState ) );
clc.lastPacketSentTime = -9999;
SCR_UpdateScreen();
} else {
// clear nextmap so the cinematic shutdown doesn't execute it
Cvar_Set( "nextmap", "" );
CL_Disconnect( qtrue );
Q_strncpyz( cls.servername, "localhost", sizeof(cls.servername) );
cls.state = CA_CHALLENGING; // so the connect screen is drawn
Key_SetCatcher( 0 );
SCR_UpdateScreen();
clc.connectTime = -RETRANSMIT_TIMEOUT;
NET_StringToAdr( cls.servername, &clc.serverAddress);
// we don't need a challenge on the localhost
CL_CheckForResend();
}
}
/*
=====================
CL_ClearState
Called before parsing a gamestate
=====================
*/
void CL_ClearState (void) {
// S_StopAllSounds();
Com_Memset( &cl, 0, sizeof( cl ) );
}
/*
====================
CL_UpdateGUID
update cl_guid using QKEY_FILE and optional prefix
====================
*/
static void CL_UpdateGUID( const char *prefix, int prefix_len )
{
if (cl_enableGuid->integer) {
fileHandle_t f;
int len;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
// initialize the cvar here in case it's unset or was user-created
// while tracking was disabled (removes CVAR_USER_CREATED)
Cvar_Get( "ja_guid", "", CVAR_USERINFO | CVAR_ROM, "Client GUID" );
if( len != QKEY_SIZE ) {
Cvar_Set( "ja_guid", "" );
} else {
Cvar_Set( "ja_guid", Com_MD5File( QKEY_FILE, QKEY_SIZE,
prefix, prefix_len ) );
}
} else {
// Remove the cvar entirely if tracking is disabled
uint32_t flags = Cvar_Flags("ja_guid");
// keep the cvar if it's user-created, but destroy it otherwise
if (flags != CVAR_NONEXISTENT && !(flags & CVAR_USER_CREATED)) {
cvar_t *ja_guid = Cvar_Get("ja_guid", "", 0, "Client GUID" );
Cvar_Unset(ja_guid);
}
}
}
/*
=====================
CL_Disconnect
Called when a connection, demo, or cinematic is being terminated.
Goes from a connected state to either a menu state or a console state
Sends a disconnect message to the server
This is also called on Com_Error and Com_Quit, so it shouldn't cause any errors
=====================
*/
void CL_Disconnect( qboolean showMainMenu ) {
if ( !com_cl_running || !com_cl_running->integer ) {
return;
}
// shutting down the client so enter full screen ui mode
Cvar_Set("r_uiFullScreen", "1");
if ( clc.demorecording ) {
CL_StopRecord_f ();
}
if (clc.download) {
FS_FCloseFile( clc.download );
clc.download = 0;
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
if ( clc.demofile ) {
FS_FCloseFile( clc.demofile );
clc.demofile = 0;
}
if ( cls.uiStarted && showMainMenu ) {
UIVM_SetActiveMenu( UIMENU_NONE );
}
SCR_StopCinematic ();
S_ClearSoundBuffer();
// send a disconnect message to the server
// send it a few times in case one is dropped
if ( cls.state >= CA_CONNECTED ) {
CL_AddReliableCommand( "disconnect", qtrue );
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
// Remove pure paks
FS_PureServerSetLoadedPaks("", "");
FS_PureServerSetReferencedPaks("", "");
CL_ClearState ();
// wipe the client connection
Com_Memset( &clc, 0, sizeof( clc ) );
cls.state = CA_DISCONNECTED;
// allow cheats locally
Cvar_Set( "sv_cheats", "1" );
// not connected to a pure server anymore
cl_connectedToPureServer = qfalse;
// Stop recording any video
if( CL_VideoRecording( ) ) {
// Finish rendering current frame
SCR_UpdateScreen( );
CL_CloseAVI( );
}
CL_UpdateGUID( NULL, 0 );
}
/*
===================
CL_ForwardCommandToServer
adds the current command line as a clientCommand
things like godmode, noclip, etc, are commands directed to the server,
so when they are typed in at the console, they will need to be forwarded.
===================
*/
void CL_ForwardCommandToServer( const char *string ) {
char *cmd;
cmd = Cmd_Argv(0);
// ignore key up commands
if ( cmd[0] == '-' ) {
return;
}
if (clc.demoplaying || cls.state < CA_CONNECTED || cmd[0] == '+' ) {
Com_Printf ("Unknown command \"%s" S_COLOR_WHITE "\"\n", cmd);
return;
}
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand( string, qfalse );
} else {
CL_AddReliableCommand( cmd, qfalse );
}
}
/*
===================
CL_RequestMotd
===================
*/
void CL_RequestMotd( void ) {
netadr_t to;
int i;
char command[MAX_STRING_CHARS], info[MAX_INFO_STRING];
char *motdaddress;
if ( !cl_motd->integer ) {
return;
}
if ( cl_motd->integer < 1 || cl_motd->integer > MAX_MASTER_SERVERS ) {
Com_Printf( "CL_RequestMotd: Invalid motd server num. Valid values are 1-%d or 0 to disable\n", MAX_MASTER_SERVERS );
return;
}
Com_sprintf( command, sizeof(command), "cl_motdServer%d", cl_motd->integer );
motdaddress = Cvar_VariableString( command );
if ( !*motdaddress )
{
Com_Printf( "CL_RequestMotd: Error: No motd server address given.\n" );
return;
}
i = NET_StringToAdr( motdaddress, &to );
if ( !i )
{
Com_Printf( "CL_RequestMotd: Error: could not resolve address of motd server %s\n", motdaddress );
return;
}
to.type = NA_IP;
to.port = BigShort( PORT_UPDATE );
Com_Printf( "Requesting motd from update %s (%s)...\n", motdaddress, NET_AdrToString( to ) );
cls.updateServer = to;
info[0] = 0;
// NOTE TTimo xoring against Com_Milliseconds, otherwise we may not have a true randomization
// only srand I could catch before here is tr_noise.c l:26 srand(1001)
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=382
// NOTE: the Com_Milliseconds xoring only affects the lower 16-bit word,
// but I decided it was enough randomization
Com_sprintf( cls.updateChallenge, sizeof( cls.updateChallenge ), "%i", ((rand() << 16) ^ rand()) ^ Com_Milliseconds());
Info_SetValueForKey( info, "challenge", cls.updateChallenge );
Info_SetValueForKey( info, "renderer", cls.glconfig.renderer_string );
Info_SetValueForKey( info, "rvendor", cls.glconfig.vendor_string );
Info_SetValueForKey( info, "version", com_version->string );
//If raven starts filtering for this, add this code back in
#if 0
Info_SetValueForKey( info, "cputype", "Intel Pentium IV");
Info_SetValueForKey( info, "mhz", "3000" );
Info_SetValueForKey( info, "memory", "4096" );
#endif
Info_SetValueForKey( info, "joystick", Cvar_VariableString("in_joystick") );
Info_SetValueForKey( info, "colorbits", va("%d",cls.glconfig.colorBits) );
NET_OutOfBandPrint( NS_CLIENT, cls.updateServer, "getmotd \"%s\"\n", info );
}
/*
======================================================================
CONSOLE COMMANDS
======================================================================
*/
/*
==================
CL_ForwardToServer_f
==================
*/
void CL_ForwardToServer_f( void ) {
if ( cls.state != CA_ACTIVE || clc.demoplaying ) {
Com_Printf ("Not connected to a server.\n");
return;
}
// don't forward the first argument
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand( Cmd_Args(), qfalse );
}
}
/*
==================
CL_Disconnect_f
==================
*/
void CL_Disconnect_f( void ) {
SCR_StopCinematic();
Cvar_Set("ui_singlePlayerActive", "0");
if ( cls.state != CA_DISCONNECTED && cls.state != CA_CINEMATIC ) {
Com_Error (ERR_DISCONNECT, "Disconnected from server");
}
}
/*
================
CL_Reconnect_f
================
*/
void CL_Reconnect_f( void ) {
if ( !strlen( cl_reconnectArgs ) ) {
return;
}
Cvar_Set("ui_singlePlayerActive", "0");
Cbuf_AddText( va("connect %s\n", cl_reconnectArgs ) );
}
/*
================
CL_Connect_f
================
*/
void CL_Connect_f( void ) {
char *server;
const char *serverString;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: connect [server]\n");
return;
}
// save arguments for reconnect
Q_strncpyz( cl_reconnectArgs, Cmd_Args(), sizeof( cl_reconnectArgs ) );
Cvar_Set("ui_singlePlayerActive", "0");
// fire a message off to the motd server
CL_RequestMotd();
// clear any previous "server full" type messages
clc.serverMessage[0] = 0;
server = Cmd_Argv (1);
if ( com_sv_running->integer && !strcmp( server, "localhost" ) ) {
// if running a local server, kill it
SV_Shutdown( "Server quit\n" );
}
// make sure a local server is killed
Cvar_Set( "sv_killserver", "1" );
SV_Frame( 0 );
CL_Disconnect( qtrue );
Con_Close();
Q_strncpyz( cls.servername, server, sizeof(cls.servername) );
if (!NET_StringToAdr( cls.servername, &clc.serverAddress) ) {
Com_Printf ("Bad server address\n");
cls.state = CA_DISCONNECTED;
return;
}
if (clc.serverAddress.port == 0) {
clc.serverAddress.port = BigShort( PORT_SERVER );
}
serverString = NET_AdrToString(clc.serverAddress);
Com_Printf( "%s resolved to %s\n", cls.servername, serverString );
if( cl_guidServerUniq->integer )
CL_UpdateGUID( serverString, strlen( serverString ) );
else
CL_UpdateGUID( NULL, 0 );
// if we aren't playing on a lan, we need to authenticate
if ( NET_IsLocalAddress( clc.serverAddress ) ) {
cls.state = CA_CHALLENGING;
} else {
cls.state = CA_CONNECTING;
// Set a client challenge number that ideally is mirrored back by the server.
clc.challenge = ((rand() << 16) ^ rand()) ^ Com_Milliseconds();
}
Key_SetCatcher( 0 );
clc.connectTime = -99999; // CL_CheckForResend() will fire immediately
clc.connectPacketCount = 0;
// server connection string
Cvar_Set( "cl_currentServerAddress", server );
Cvar_Set( "cl_currentServerIP", serverString );
}
#define MAX_RCON_MESSAGE 1024
/*
==================
CL_CompleteRcon
==================
*/
static void CL_CompleteRcon( char *args, int argNum )
{
if( argNum == 2 )
{
// Skip "rcon "
char *p = Com_SkipTokens( args, 1, " " );
if( p > args )
Field_CompleteCommand( p, qtrue, qtrue );
}
}
/*
=====================
CL_Rcon_f
Send the rest of the command line over as
an unconnected command.
=====================
*/
void CL_Rcon_f( void ) {
char message[MAX_RCON_MESSAGE];
if ( !rcon_client_password->string[0] ) {
Com_Printf( "You must set 'rconpassword' before issuing an rcon command.\n" );
return;
}
message[0] = -1;
message[1] = -1;
message[2] = -1;
message[3] = -1;
message[4] = 0;
Q_strcat (message, MAX_RCON_MESSAGE, "rcon ");
Q_strcat (message, MAX_RCON_MESSAGE, rcon_client_password->string);
Q_strcat (message, MAX_RCON_MESSAGE, " ");
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543
Q_strcat (message, MAX_RCON_MESSAGE, Cmd_Cmd()+5);
if ( cls.state >= CA_CONNECTED ) {
rcon_address = clc.netchan.remoteAddress;
} else {
if (!strlen(rconAddress->string)) {
Com_Printf ("You must either be connected,\n"
"or set the 'rconAddress' cvar\n"
"to issue rcon commands\n");
return;
}
NET_StringToAdr (rconAddress->string, &rcon_address);
if (rcon_address.port == 0) {
rcon_address.port = BigShort (PORT_SERVER);
}
}
NET_SendPacket (NS_CLIENT, strlen(message)+1, message, rcon_address);
}
/*
=================
CL_SendPureChecksums
=================
*/
void CL_SendPureChecksums( void ) {
char cMsg[MAX_INFO_VALUE];
// if we are pure we need to send back a command with our referenced pk3 checksums
Com_sprintf(cMsg, sizeof(cMsg), "cp %s", FS_ReferencedPakPureChecksums());
CL_AddReliableCommand( cMsg, qfalse );
}
/*
=================
CL_ResetPureClientAtServer
=================
*/
void CL_ResetPureClientAtServer( void ) {
CL_AddReliableCommand( "vdr", qfalse );
}
/*
=================
CL_Vid_Restart_f
Restart the video subsystem
we also have to reload the UI and CGame because the renderer
doesn't know what graphics to reload
=================
*/
extern bool g_nOverrideChecked;
void CL_Vid_Restart_f( void ) {
// Settings may have changed so stop recording now
if( CL_VideoRecording( ) ) {
CL_CloseAVI( );
}
if(clc.demorecording)
CL_StopRecord_f();
//rww - sort of nasty, but when a user selects a mod
//from the menu all it does is a vid_restart, so we
//have to check for new net overrides for the mod then.
g_nOverrideChecked = false;
// don't let them loop during the restart
S_StopAllSounds();
// shutdown the UI
CL_ShutdownUI();
// shutdown the CGame
CL_ShutdownCGame();
// shutdown the renderer and clear the renderer interface
CL_ShutdownRef( qtrue );
// client is no longer pure untill new checksums are sent
CL_ResetPureClientAtServer();
// clear pak references
FS_ClearPakReferences( FS_UI_REF | FS_CGAME_REF );
// reinitialize the filesystem if the game directory or checksum has changed
FS_ConditionalRestart( clc.checksumFeed );
cls.rendererStarted = qfalse;
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.soundRegistered = qfalse;
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
// if not running a server clear the whole hunk
if ( !com_sv_running->integer ) {
CM_ClearMap();
// clear the whole hunk
Hunk_Clear();
}
else {
// clear all the client data on the hunk
Hunk_ClearToMark();
}
// initialize the renderer interface
CL_InitRef();
// startup all the client stuff
CL_StartHunkUsers();
// start the cgame if connected
if ( cls.state > CA_CONNECTED && cls.state != CA_CINEMATIC ) {
cls.cgameStarted = qtrue;
CL_InitCGame();
// send pure checksums
CL_SendPureChecksums();
}
}
/*
=================
CL_Snd_Restart_f
Restart the sound subsystem
The cgame and game must also be forced to restart because
handles will be invalid
=================
*/
// extern void S_UnCacheDynamicMusic( void );
void CL_Snd_Restart_f( void ) {
S_Shutdown();
S_Init();
// S_FreeAllSFXMem(); // These two removed by BTO (VV)
// S_UnCacheDynamicMusic(); // S_Shutdown() already does this!
// CL_Vid_Restart_f();
extern qboolean s_soundMuted;
s_soundMuted = qfalse; // we can play again
extern void S_RestartMusic( void );
S_RestartMusic();
}
/*
==================
CL_PK3List_f
==================
*/
void CL_OpenedPK3List_f( void ) {
Com_Printf("Opened PK3 Names: %s\n", FS_LoadedPakNames());
}
/*
==================
CL_PureList_f
==================
*/
void CL_ReferencedPK3List_f( void ) {
Com_Printf("Referenced PK3 Names: %s\n", FS_ReferencedPakNames());
}
/*
==================
CL_Configstrings_f
==================
*/
void CL_Configstrings_f( void ) {
int i;
int ofs;
if ( cls.state != CA_ACTIVE ) {
Com_Printf( "Not connected to a server.\n");
return;
}
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
ofs = cl.gameState.stringOffsets[ i ];
if ( !ofs ) {
continue;
}
Com_Printf( "%4i: %s\n", i, cl.gameState.stringData + ofs );
}
}
/*
==============
CL_Clientinfo_f
==============
*/
void CL_Clientinfo_f( void ) {
Com_Printf( "--------- Client Information ---------\n" );
Com_Printf( "state: %i\n", cls.state );
Com_Printf( "Server: %s\n", cls.servername );
Com_Printf ("User info settings:\n");
Info_Print( Cvar_InfoString( CVAR_USERINFO ) );
Com_Printf( "--------------------------------------\n" );
}
//====================================================================
/*
=================
CL_DownloadsComplete
Called when all downloading has been completed
=================
*/
void CL_DownloadsComplete( void ) {
// if we downloaded files we need to restart the file system
if (clc.downloadRestart) {
clc.downloadRestart = qfalse;
FS_Restart(clc.checksumFeed); // We possibly downloaded a pak, restart the file system to load it
// inform the server so we get new gamestate info
CL_AddReliableCommand( "donedl", qfalse );
// by sending the donedl command we request a new gamestate
// so we don't want to load stuff yet
return;
}
// let the client game init and load data
cls.state = CA_LOADING;
// Pump the loop, this may change gamestate!
Com_EventLoop();
// if the gamestate was changed by calling Com_EventLoop
// then we loaded everything already and we don't want to do it again.
if ( cls.state != CA_LOADING ) {
return;
}
// starting to load a map so we get out of full screen ui mode
Cvar_Set("r_uiFullScreen", "0");
// flush client memory and start loading stuff
// this will also (re)load the UI
// if this is a local client then only the client part of the hunk
// will be cleared, note that this is done after the hunk mark has been set
CL_FlushMemory();
// initialize the CGame
cls.cgameStarted = qtrue;
CL_InitCGame();
// set pure checksums
CL_SendPureChecksums();
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
/*
=================
CL_BeginDownload
Requests a file to download from the server. Stores it in the current
game directory.
=================
*/
void CL_BeginDownload( const char *localName, const char *remoteName ) {
Com_DPrintf("***** CL_BeginDownload *****\n"
"Localname: %s\n"
"Remotename: %s\n"
"****************************\n", localName, remoteName);
Q_strncpyz ( clc.downloadName, localName, sizeof(clc.downloadName) );
Com_sprintf( clc.downloadTempName, sizeof(clc.downloadTempName), "%s.tmp", localName );
// Set so UI gets access to it
Cvar_Set( "cl_downloadName", remoteName );
Cvar_Set( "cl_downloadSize", "0" );
Cvar_Set( "cl_downloadCount", "0" );
Cvar_SetValue( "cl_downloadTime", (float) cls.realtime );
clc.downloadBlock = 0; // Starting new file
clc.downloadCount = 0;
CL_AddReliableCommand( va("download %s", remoteName), qfalse );
}
/*
=================
CL_NextDownload
A download completed or failed
=================
*/
void CL_NextDownload(void) {
char *s;
char *remoteName, *localName;
// A download has finished, check whether this matches a referenced checksum
if(*clc.downloadName)
{
char *zippath = FS_BuildOSPath(Cvar_VariableString("fs_homepath"), clc.downloadName, "");
zippath[strlen(zippath)-1] = '\0';
if(!FS_CompareZipChecksum(zippath))
Com_Error(ERR_DROP, "Incorrect checksum for file: %s", clc.downloadName);
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set("cl_downloadName", "");
// We are looking to start a download here
if (*clc.downloadList) {
s = clc.downloadList;
// format is:
// @remotename@localname@remotename@localname, etc.
if (*s == '@')
s++;
remoteName = s;
if ( (s = strchr(s, '@')) == NULL ) {
CL_DownloadsComplete();
return;
}
*s++ = 0;
localName = s;
if ( (s = strchr(s, '@')) != NULL )
*s++ = 0;
else
s = localName + strlen(localName); // point at the nul byte
if (!cl_allowDownload->integer) {
Com_Error(ERR_DROP, "UDP Downloads are disabled on your client. (cl_allowDownload is %d)", cl_allowDownload->integer);
return;
}
else {
CL_BeginDownload( localName, remoteName );
}
clc.downloadRestart = qtrue;
// move over the rest
memmove( clc.downloadList, s, strlen(s) + 1);
return;
}
CL_DownloadsComplete();
}
/*
=================
CL_InitDownloads
After receiving a valid game state, we valid the cgame and local zip files here
and determine if we need to download them
=================
*/
void CL_InitDownloads(void) {
char missingfiles[1024];
if ( !cl_allowDownload->integer )
{
// autodownload is disabled on the client
// but it's possible that some referenced files on the server are missing
if (FS_ComparePaks( missingfiles, sizeof( missingfiles ), qfalse ) )
{
// NOTE TTimo I would rather have that printed as a modal message box
// but at this point while joining the game we don't know wether we will successfully join or not
Com_Printf( "\nWARNING: You are missing some files referenced by the server:\n%s"
"You might not be able to join the game\n"
"Go to the setting menu to turn on autodownload, or get the file elsewhere\n\n", missingfiles );
}
}
else if ( FS_ComparePaks( clc.downloadList, sizeof( clc.downloadList ) , qtrue ) ) {
Com_Printf("Need paks: %s\n", clc.downloadList );
if ( *clc.downloadList ) {
// if autodownloading is not enabled on the server
cls.state = CA_CONNECTED;
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
CL_NextDownload();
return;
}
}
CL_DownloadsComplete();
}
/*
=================
CL_CheckForResend
Resend a connect message if the last one has timed out
=================
*/
void CL_CheckForResend( void ) {
int port;
char info[MAX_INFO_STRING];
char data[MAX_INFO_STRING+10];
// don't send anything if playing back a demo
if ( clc.demoplaying ) {
return;
}
// resend if we haven't gotten a reply yet
if ( cls.state != CA_CONNECTING && cls.state != CA_CHALLENGING ) {
return;
}
if ( cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT ) {
return;
}
clc.connectTime = cls.realtime; // for retransmit requests
clc.connectPacketCount++;
switch ( cls.state ) {
case CA_CONNECTING:
// requesting a challenge
// The challenge request shall be followed by a client challenge so no malicious server can hijack this connection.
Com_sprintf(data, sizeof(data), "getchallenge %d", clc.challenge);
NET_OutOfBandPrint(NS_CLIENT, clc.serverAddress, data);
break;
case CA_CHALLENGING:
// sending back the challenge
port = (int) Cvar_VariableValue ("net_qport");
Q_strncpyz( info, Cvar_InfoString( CVAR_USERINFO ), sizeof( info ) );
Info_SetValueForKey( info, "protocol", va("%i", PROTOCOL_VERSION ) );
Info_SetValueForKey( info, "qport", va("%i", port ) );
Info_SetValueForKey( info, "challenge", va("%i", clc.challenge ) );
Com_sprintf(data, sizeof(data), "connect \"%s\"", info );
NET_OutOfBandData( NS_CLIENT, clc.serverAddress, (byte *)data, strlen(data) );
// the most current userinfo has been sent, so watch for any
// newer changes to userinfo variables
cvar_modifiedFlags &= ~CVAR_USERINFO;
break;
default:
Com_Error( ERR_FATAL, "CL_CheckForResend: bad cls.state" );
}
}
/*
===================
CL_DisconnectPacket
Sometimes the server can drop the client and the netchan based
disconnect can be lost. If the client continues to send packets
to the server, the server will send out of band disconnect packets
to the client so it doesn't have to wait for the full timeout period.
===================
*/
void CL_DisconnectPacket( netadr_t from ) {
if ( cls.state < CA_AUTHORIZING ) {
return;
}
// if not from our server, ignore it
if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
return;
}
// if we have received packets within three seconds, ignore it
// (it might be a malicious spoof)
if ( cls.realtime - clc.lastPacketTime < 3000 ) {
return;
}
// drop the connection (FIXME: connection dropped dialog)
Com_Printf( "Server disconnected for unknown reason\n" );
CL_Disconnect( qtrue );
}
/*
===================
CL_MotdPacket
===================
*/
void CL_MotdPacket( netadr_t from ) {
char *challenge;
char *info;
// if not from our server, ignore it
if ( !NET_CompareAdr( from, cls.updateServer ) ) {
return;
}
info = Cmd_Argv(1);
// check challenge
challenge = Info_ValueForKey( info, "challenge" );
if ( strcmp( challenge, cls.updateChallenge ) ) {
return;
}
challenge = Info_ValueForKey( info, "motd" );
Q_strncpyz( cls.updateInfoString, info, sizeof( cls.updateInfoString ) );
Cvar_Set( "cl_motdString", challenge );
}
/*
===================
CL_InitServerInfo
===================
*/
void CL_InitServerInfo( serverInfo_t *server, netadr_t *address ) {
server->adr = *address;
server->clients = 0;
server->hostName[0] = '\0';
server->mapName[0] = '\0';
server->maxClients = 0;
server->maxPing = 0;
server->minPing = 0;
server->netType = 0;
server->needPassword = qfalse;
server->trueJedi = 0;
server->weaponDisable = 0;
server->forceDisable = 0;
server->ping = -1;
server->game[0] = '\0';
server->gameType = 0;
server->humans = server->bots = 0;
}
#define MAX_SERVERSPERPACKET 256
/*
===================
CL_ServersResponsePacket
===================
*/
void CL_ServersResponsePacket( const netadr_t *from, msg_t *msg ) {
int i, j, count, total;
netadr_t addresses[MAX_SERVERSPERPACKET];
int numservers;
byte* buffptr;
byte* buffend;
Com_Printf("CL_ServersResponsePacket\n");
if (cls.numglobalservers == -1) {
// state to detect lack of servers or lack of response
cls.numglobalservers = 0;
cls.numGlobalServerAddresses = 0;
}
// parse through server response string
numservers = 0;
buffptr = msg->data;
buffend = buffptr + msg->cursize;
// advance to initial token
do
{
if(*buffptr == '\\')
break;
buffptr++;
} while (buffptr < buffend);
while (buffptr + 1 < buffend)
{
// IPv4 address
if (*buffptr == '\\')
{
buffptr++;
if (buffend - buffptr < (int)(sizeof(addresses[numservers].ip) + sizeof(addresses[numservers].port) + 1))
break;
for(size_t i = 0; i < sizeof(addresses[numservers].ip); i++)
addresses[numservers].ip[i] = *buffptr++;
addresses[numservers].type = NA_IP;
}
else
// syntax error!
break;
// parse out port
addresses[numservers].port = (*buffptr++) << 8;
addresses[numservers].port += *buffptr++;
addresses[numservers].port = BigShort( addresses[numservers].port );
// syntax check
if (*buffptr != '\\')
break;
numservers++;
if (numservers >= MAX_SERVERSPERPACKET)
break;
}
count = cls.numglobalservers;
for (i = 0; i < numservers && count < MAX_GLOBAL_SERVERS; i++) {
// build net address
serverInfo_t *server = &cls.globalServers[count];
// Tequila: It's possible to have sent many master server requests. Then
// we may receive many times the same addresses from the master server.
// We just avoid to add a server if it is still in the global servers list.
for (j = 0; j < count; j++)
{
if (NET_CompareAdr(cls.globalServers[j].adr, addresses[i]))
break;
}
if (j < count)
continue;
CL_InitServerInfo( server, &addresses[i] );
// advance to next slot
count++;
}
// if getting the global list
if ( count >= MAX_GLOBAL_SERVERS && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS )
{
// if we couldn't store the servers in the main list anymore
for (; i < numservers && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS; i++)
{
// just store the addresses in an additional list
cls.globalServerAddresses[cls.numGlobalServerAddresses++] = addresses[i];
}
}
cls.numglobalservers = count;
total = count + cls.numGlobalServerAddresses;
Com_Printf("%d servers parsed (total %d)\n", numservers, total);
}
#ifndef MAX_STRINGED_SV_STRING
#define MAX_STRINGED_SV_STRING 1024
#endif
static void CL_CheckSVStringEdRef(char *buf, const char *str)
{ //I don't really like doing this. But it utilizes the system that was already in place.
int i = 0;
int b = 0;
int strLen = 0;
qboolean gotStrip = qfalse;
if (!str || !str[0])
{
if (str)
{
strcpy(buf, str);
}
return;
}
strcpy(buf, str);
strLen = strlen(str);
if (strLen >= MAX_STRINGED_SV_STRING)
{
return;
}
while (i < strLen && str[i])
{
gotStrip = qfalse;
if (str[i] == '@' && (i+1) < strLen)
{
if (str[i+1] == '@' && (i+2) < strLen)
{
if (str[i+2] == '@' && (i+3) < strLen)
{ //@@@ should mean to insert a stringed reference here, so insert it into buf at the current place
char stripRef[MAX_STRINGED_SV_STRING];
int r = 0;
while (i < strLen && str[i] == '@')
{
i++;
}
while (i < strLen && str[i] && str[i] != ' ' && str[i] != ':' && str[i] != '.' && str[i] != '\n')
{
stripRef[r] = str[i];
r++;
i++;
}
stripRef[r] = 0;
buf[b] = 0;
Q_strcat(buf, MAX_STRINGED_SV_STRING, SE_GetString(va("MP_SVGAME_%s", stripRef)));
b = strlen(buf);
}
}
}
if (!gotStrip)
{
buf[b] = str[i];
b++;
}
i++;
}
buf[b] = 0;
}
/*
=================
CL_ConnectionlessPacket
Responses to broadcasts, etc
=================
*/
void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) {
char *s;
char *c;
int challenge = 0;
MSG_BeginReadingOOB( msg );
MSG_ReadLong( msg ); // skip the -1
s = MSG_ReadStringLine( msg );
Cmd_TokenizeString( s );
c = Cmd_Argv(0);
Com_DPrintf ("CL packet %s: %s\n", NET_AdrToString(from), c);
// challenge from the server we are connecting to
if ( !Q_stricmp(c, "challengeResponse") )
{
if ( cls.state != CA_CONNECTING )
{
Com_Printf( "Unwanted challenge response received. Ignored.\n" );
return;
}
c = Cmd_Argv(2);
if(*c)
challenge = atoi(c);
if(!NET_CompareAdr(from, clc.serverAddress))
{
// This challenge response is not coming from the expected address.
// Check whether we have a matching client challenge to prevent
// connection hi-jacking.
if(!*c || challenge != clc.challenge)
{
Com_DPrintf("Challenge response received from unexpected source. Ignored.\n");
return;
}
}
// start sending challenge response instead of challenge request packets
clc.challenge = atoi(Cmd_Argv(1));
cls.state = CA_CHALLENGING;
clc.connectPacketCount = 0;
clc.connectTime = -99999;
// take this address as the new server address. This allows
// a server proxy to hand off connections to multiple servers
clc.serverAddress = from;
Com_DPrintf ("challengeResponse: %d\n", clc.challenge);
return;
}
// server connection
if ( !Q_stricmp(c, "connectResponse") ) {
if ( cls.state >= CA_CONNECTED ) {
Com_Printf ("Dup connect received. Ignored.\n");
return;
}
if ( cls.state != CA_CHALLENGING ) {
Com_Printf ("connectResponse packet while not connecting. Ignored.\n");
return;
}
if ( !NET_CompareAdr( from, clc.serverAddress ) ) {
Com_Printf( "connectResponse from wrong address. Ignored.\n" );
return;
}
Netchan_Setup (NS_CLIENT, &clc.netchan, from, Cvar_VariableValue( "net_qport" ) );
cls.state = CA_CONNECTED;
clc.lastPacketSentTime = -9999; // send first packet immediately
return;
}
// server responding to an info broadcast
if ( !Q_stricmp(c, "infoResponse") ) {
CL_ServerInfoPacket( from, msg );
return;
}
// server responding to a get playerlist
if ( !Q_stricmp(c, "statusResponse") ) {
CL_ServerStatusResponse( from, msg );
return;
}
// a disconnect message from the server, which will happen if the server
// dropped the connection but it is still getting packets from us
if (!Q_stricmp(c, "disconnect")) {
CL_DisconnectPacket( from );
return;
}
// echo request from server
if ( !Q_stricmp(c, "echo") ) {
NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv(1) );
return;
}
// cd check
if ( !Q_stricmp(c, "keyAuthorize") ) {
// we don't use these now, so dump them on the floor
return;
}
// global MOTD from id
if ( !Q_stricmp(c, "motd") ) {
CL_MotdPacket( from );
return;
}
// echo request from server
if ( !Q_stricmp(c, "print") )
{
// NOTE: we may have to add exceptions for auth and update servers
if (NET_CompareAdr(from, clc.serverAddress) || NET_CompareAdr(from, rcon_address))
{
char sTemp[MAX_STRINGED_SV_STRING];
s = MSG_ReadString( msg );
CL_CheckSVStringEdRef(sTemp, s);
Q_strncpyz( clc.serverMessage, sTemp, sizeof( clc.serverMessage ) );
Com_Printf( "%s", sTemp );
}
return;
}
// list of servers sent back by a master server (classic)
if ( !Q_strncmp(c, "getserversResponse", 18) ) {
CL_ServersResponsePacket( &from, msg );
return;
}
Com_DPrintf ("Unknown connectionless packet command.\n");
}
/*
=================
CL_PacketEvent
A packet has arrived from the main event loop
=================
*/
void CL_PacketEvent( netadr_t from, msg_t *msg ) {
int headerBytes;
clc.lastPacketTime = cls.realtime;
if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) {
CL_ConnectionlessPacket( from, msg );
return;
}
if ( cls.state < CA_CONNECTED ) {
return; // can't be a valid sequenced packet
}
if ( msg->cursize < 4 ) {
Com_Printf ("%s: Runt packet\n",NET_AdrToString( from ));
return;
}
//
// packet from server
//
if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
Com_DPrintf ("%s:sequenced packet without connection\n"
,NET_AdrToString( from ) );
// FIXME: send a client disconnect?
return;
}
if (!CL_Netchan_Process( &clc.netchan, msg) ) {
return; // out of order, duplicated, etc
}
// the header is different lengths for reliable and unreliable messages
headerBytes = msg->readcount;
// track the last message received so it can be returned in
// client messages, allowing the server to detect a dropped
// gamestate
clc.serverMessageSequence = LittleLong( *(int *)msg->data );
clc.lastPacketTime = cls.realtime;
CL_ParseServerMessage( msg );
//
// we don't know if it is ok to save a demo message until
// after we have parsed the frame
//
if ( clc.demorecording && !clc.demowaiting ) {
CL_WriteDemoMessage( msg, headerBytes );
}
}
/*
==================
CL_CheckTimeout
==================
*/
void CL_CheckTimeout( void ) {
//
// check timeout
//
if ( ( !CL_CheckPaused() || !sv_paused->integer )
&& cls.state >= CA_CONNECTED && cls.state != CA_CINEMATIC
&& cls.realtime - clc.lastPacketTime > cl_timeout->value*1000) {
if (++cl.timeoutcount > 5) { // timeoutcount saves debugger
const char *psTimedOut = SE_GetString("MP_SVGAME_SERVER_CONNECTION_TIMED_OUT");
Com_Printf ("\n%s\n",psTimedOut);
Com_Error(ERR_DROP, psTimedOut);
//CL_Disconnect( qtrue );
return;
}
} else {
cl.timeoutcount = 0;
}
}
/*
==================
CL_CheckPaused
Check whether client has been paused.
==================
*/
qboolean CL_CheckPaused(void)
{
// if cl_paused->modified is set, the cvar has only been changed in
// this frame. Keep paused in this frame to ensure the server doesn't
// lag behind.
if(cl_paused->integer || cl_paused->modified)
return qtrue;
return qfalse;
}
//============================================================================
/*
==================
CL_CheckUserinfo
==================
*/
void CL_CheckUserinfo( void ) {
// don't add reliable commands when not yet connected
if ( cls.state < CA_CONNECTED ) {
return;
}
// don't overflow the reliable command buffer when paused
if ( CL_CheckPaused() ) {
return;
}
// send a reliable userinfo update if needed
if ( cvar_modifiedFlags & CVAR_USERINFO ) {
cvar_modifiedFlags &= ~CVAR_USERINFO;
CL_AddReliableCommand( va("userinfo \"%s\"", Cvar_InfoString( CVAR_USERINFO ) ), qfalse );
}
}
/*
==================
CL_Frame
==================
*/
static unsigned int frameCount;
static float avgFrametime=0.0;
extern void SE_CheckForLanguageUpdates(void);
void CL_Frame ( int msec ) {
qboolean takeVideoFrame = qfalse;
if ( !com_cl_running->integer ) {
return;
}
SE_CheckForLanguageUpdates(); // will take zero time to execute unless language changes, then will reload strings.
// of course this still doesn't work for menus...
if ( cls.state == CA_DISCONNECTED && !( Key_GetCatcher( ) & KEYCATCH_UI )
&& !com_sv_running->integer && cls.uiStarted ) {
// if disconnected, bring up the menu
S_StopAllSounds();
UIVM_SetActiveMenu( UIMENU_MAIN );
}
// if recording an avi, lock to a fixed fps
if ( CL_VideoRecording( ) && cl_aviFrameRate->integer && msec) {
if ( cls.state == CA_ACTIVE || cl_forceavidemo->integer) {
float fps = Q_min(cl_aviFrameRate->value * com_timescale->value, 1000.0f);
float frameDuration = Q_max(1000.0f / fps, 1.0f) + clc.aviVideoFrameRemainder;
takeVideoFrame = qtrue;
msec = (int)frameDuration;
clc.aviVideoFrameRemainder = frameDuration - msec;
}
}
// save the msec before checking pause
cls.realFrametime = msec;
// decide the simulation time
cls.frametime = msec;
if(cl_framerate->integer)
{
avgFrametime+=msec;
char mess[256];
if(!(frameCount&0x1f))
{
Com_sprintf(mess,sizeof(mess),"Frame rate=%f\n\n",1000.0f*(1.0/(avgFrametime/32.0f)));
// Com_OPrintf("%s", mess);
Com_Printf("%s", mess);
avgFrametime=0.0f;
}
frameCount++;
}
cls.realtime += cls.frametime;
if ( cl_timegraph->integer ) {
SCR_DebugGraph ( cls.realFrametime * 0.25, 0 );
}
// see if we need to update any userinfo
CL_CheckUserinfo();
// if we haven't gotten a packet in a long time,
// drop the connection
CL_CheckTimeout();
// send intentions now
CL_SendCmd();
// resend a connection request if necessary
CL_CheckForResend();
// decide on the serverTime to render
CL_SetCGameTime();
// update the screen
SCR_UpdateScreen();
// update audio
S_Update();
// advance local effects for next frame
SCR_RunCinematic();
Con_RunConsole();
// reset the heap for Ghoul2 vert transform space gameside
if (G2VertSpaceServer)
{
G2VertSpaceServer->ResetHeap();
}
cls.framecount++;
if ( takeVideoFrame ) {
// save the current screen
CL_TakeVideoFrame( );
}
}
//============================================================================
/*
================
CL_RefPrintf
DLL glue
================
*/
void QDECL CL_RefPrintf( int print_level, const char *fmt, ...) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start (argptr,fmt);
Q_vsnprintf(msg, sizeof(msg), fmt, argptr);
va_end (argptr);
if ( print_level == PRINT_ALL ) {
Com_Printf ("%s", msg);
} else if ( print_level == PRINT_WARNING ) {
Com_Printf (S_COLOR_YELLOW "%s", msg); // yellow
} else if ( print_level == PRINT_DEVELOPER ) {
Com_DPrintf (S_COLOR_RED "%s", msg); // red
}
}
/*
============
CL_ShutdownRef
============
*/
static void CL_ShutdownRef( qboolean restarting ) {
if ( re )
{
if ( re->Shutdown )
{
re->Shutdown( qtrue, restarting );
}
}
re = NULL;
if ( rendererLib != NULL ) {
Sys_UnloadDll (rendererLib);
rendererLib = NULL;
}
}
/*
============
CL_InitRenderer
============
*/
void CL_InitRenderer( void ) {
// this sets up the renderer and calls R_Init
re->BeginRegistration( &cls.glconfig );
// load character sets
cls.charSetShader = re->RegisterShaderNoMip("gfx/2d/charsgrid_med");
cls.whiteShader = re->RegisterShader( "white" );
cls.consoleShader = re->RegisterShader( "console" );
g_console_field_width = cls.glconfig.vidWidth / SMALLCHAR_WIDTH - 2;
g_consoleField.widthInChars = g_console_field_width;
}
/*
============================
CL_StartHunkUsers
After the server has cleared the hunk, these will need to be restarted
This is the only place that any of these functions are called from
============================
*/
void CL_StartHunkUsers( void ) {
if (!com_cl_running) {
return;
}
if ( !com_cl_running->integer ) {
return;
}
if ( !cls.rendererStarted ) {
cls.rendererStarted = qtrue;
CL_InitRenderer();
}
if ( !cls.soundStarted ) {
cls.soundStarted = qtrue;
S_Init();
}
if ( !cls.soundRegistered ) {
cls.soundRegistered = qtrue;
S_BeginRegistration();
}
if ( !cls.uiStarted ) {
cls.uiStarted = qtrue;
CL_InitUI();
}
}
/*
============
CL_InitRef
============
*/
qboolean Com_TheHunkMarkHasBeenMade(void);
//qcommon/cm_load.cpp
extern void *gpvCachedMapDiskImage;
extern qboolean gbUsingCachedMapDataRightNow;
static char *GetSharedMemory( void ) { return cl.mSharedMemory; }
static vm_t *GetCurrentVM( void ) { return currentVM; }
static qboolean CGVMLoaded( void ) { return (qboolean)cls.cgameStarted; }
static void *CM_GetCachedMapDiskImage( void ) { return gpvCachedMapDiskImage; }
static void CM_SetCachedMapDiskImage( void *ptr ) { gpvCachedMapDiskImage = ptr; }
static void CM_SetUsingCache( qboolean usingCache ) { gbUsingCachedMapDataRightNow = usingCache; }
#define G2_VERT_SPACE_SERVER_SIZE 256
IHeapAllocator *G2VertSpaceServer = NULL;
CMiniHeap IHeapAllocator_singleton(G2_VERT_SPACE_SERVER_SIZE * 1024);
static IHeapAllocator *GetG2VertSpaceServer( void ) {
return G2VertSpaceServer;
}
#define DEFAULT_RENDER_LIBRARY "rd-vanilla"
void CL_InitRef( void ) {
static refimport_t ri;
refexport_t *ret;
GetRefAPI_t GetRefAPI;
char dllName[MAX_OSPATH];
Com_Printf( "----- Initializing Renderer ----\n" );
cl_renderer = Cvar_Get( "cl_renderer", DEFAULT_RENDER_LIBRARY, CVAR_ARCHIVE|CVAR_LATCH|CVAR_PROTECTED, "Which renderer library to use" );
Com_sprintf( dllName, sizeof( dllName ), "%s_" ARCH_STRING DLL_EXT, cl_renderer->string );
if( !(rendererLib = Sys_LoadDll( dllName, qfalse )) && strcmp( cl_renderer->string, cl_renderer->resetString ) )
{
Com_Printf( "failed: trying to load fallback renderer\n" );
Cvar_ForceReset( "cl_renderer" );
Com_sprintf( dllName, sizeof( dllName ), DEFAULT_RENDER_LIBRARY "_" ARCH_STRING DLL_EXT );
rendererLib = Sys_LoadDll( dllName, qfalse );
}
if ( !rendererLib ) {
Com_Error( ERR_FATAL, "Failed to load renderer\n" );
}
memset( &ri, 0, sizeof( ri ) );
GetRefAPI = (GetRefAPI_t)Sys_LoadFunction( rendererLib, "GetRefAPI" );
if ( !GetRefAPI )
Com_Error( ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError() );
//set up the import table
ri.Printf = CL_RefPrintf;
ri.Error = Com_Error;
ri.OPrintf = Com_OPrintf;
ri.Milliseconds = Sys_Milliseconds2; //FIXME: unix+mac need this
ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
ri.Hunk_Alloc = Hunk_Alloc;
ri.Hunk_MemoryRemaining = Hunk_MemoryRemaining;
ri.Z_Malloc = Z_Malloc;
ri.Z_Free = Z_Free;
ri.Z_MemSize = Z_MemSize;
ri.Z_MorphMallocTag = Z_MorphMallocTag;
ri.Cmd_ExecuteString = Cmd_ExecuteString;
ri.Cmd_Argc = Cmd_Argc;
ri.Cmd_Argv = Cmd_Argv;
ri.Cmd_ArgsBuffer = Cmd_ArgsBuffer;
ri.Cmd_AddCommand = Cmd_AddCommand;
ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
ri.Cvar_Set = Cvar_Set;
ri.Cvar_Get = Cvar_Get;
ri.Cvar_SetValue = Cvar_SetValue;
ri.Cvar_CheckRange = Cvar_CheckRange;
ri.Cvar_VariableStringBuffer = Cvar_VariableStringBuffer;
ri.Cvar_VariableString = Cvar_VariableString;
ri.Cvar_VariableValue = Cvar_VariableValue;
ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;
ri.SE_GetString = SE_GetString;
ri.FS_FreeFile = FS_FreeFile;
ri.FS_FreeFileList = FS_FreeFileList;
ri.FS_Read = FS_Read;
ri.FS_ReadFile = FS_ReadFile;
ri.FS_FCloseFile = FS_FCloseFile;
ri.FS_FOpenFileRead = FS_FOpenFileRead;
ri.FS_FOpenFileWrite = FS_FOpenFileWrite;
ri.FS_FOpenFileByMode = FS_FOpenFileByMode;
ri.FS_FileExists = FS_FileExists;
ri.FS_FileIsInPAK = FS_FileIsInPAK;
ri.FS_ListFiles = FS_ListFiles;
ri.FS_Write = FS_Write;
ri.FS_WriteFile = FS_WriteFile;
ri.CM_BoxTrace = CM_BoxTrace;
ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
ri.CM_CullWorldBox = CM_CullWorldBox;
ri.CM_ClusterPVS = CM_ClusterPVS;
ri.CM_LeafArea = CM_LeafArea;
ri.CM_LeafCluster = CM_LeafCluster;
ri.CM_PointLeafnum = CM_PointLeafnum;
ri.CM_PointContents = CM_PointContents;
ri.Com_TheHunkMarkHasBeenMade = Com_TheHunkMarkHasBeenMade;
ri.S_RestartMusic = S_RestartMusic;
ri.SND_RegisterAudio_LevelLoadEnd = SND_RegisterAudio_LevelLoadEnd;
ri.CIN_RunCinematic = CIN_RunCinematic;
ri.CIN_PlayCinematic = CIN_PlayCinematic;
ri.CIN_UploadCinematic = CIN_UploadCinematic;
ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;
// g2 data access
ri.GetSharedMemory = GetSharedMemory;
// (c)g vm callbacks
ri.GetCurrentVM = GetCurrentVM;
ri.CGVMLoaded = CGVMLoaded;
ri.CGVM_RagCallback = CGVM_RagCallback;
ri.WIN_Init = WIN_Init;
ri.WIN_SetGamma = WIN_SetGamma;
ri.WIN_Shutdown = WIN_Shutdown;
ri.WIN_Present = WIN_Present;
ri.GL_GetProcAddress = WIN_GL_GetProcAddress;
ri.GL_ExtensionSupported = WIN_GL_ExtensionSupported;
ri.CM_GetCachedMapDiskImage = CM_GetCachedMapDiskImage;
ri.CM_SetCachedMapDiskImage = CM_SetCachedMapDiskImage;
ri.CM_SetUsingCache = CM_SetUsingCache;
//FIXME: Might have to do something about this...
ri.GetG2VertSpaceServer = GetG2VertSpaceServer;
G2VertSpaceServer = &IHeapAllocator_singleton;
ri.PD_Store = PD_Store;
ri.PD_Load = PD_Load;
ret = GetRefAPI( REF_API_VERSION, &ri );
// Com_Printf( "-------------------------------\n");
if ( !ret ) {
Com_Error (ERR_FATAL, "Couldn't initialize refresh" );
}
re = ret;
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
}
//===========================================================================================
#define MODEL_CHANGE_DELAY 5000
int gCLModelDelay = 0;
void CL_SetModel_f( void ) {
char *arg;
char name[256];
arg = Cmd_Argv( 1 );
if (arg[0])
{
/*
//If you wanted to be foolproof you would put this on the server I guess. But that
//tends to put things out of sync regarding cvar status. And I sort of doubt someone
//is going to write a client and figure out the protocol so that they can annoy people
//by changing models real fast.
int curTime = Com_Milliseconds();
if (gCLModelDelay > curTime)
{
Com_Printf("You can only change your model every %i seconds.\n", (MODEL_CHANGE_DELAY/1000));
return;
}
gCLModelDelay = curTime + MODEL_CHANGE_DELAY;
*/
//rwwFIXMEFIXME: This is currently broken and doesn't seem to work for connecting clients
Cvar_Set( "model", arg );
}
else
{
Cvar_VariableStringBuffer( "model", name, sizeof(name) );
Com_Printf("model is set to %s\n", name);
}
}
void CL_SetForcePowers_f( void ) {
return;
}
/*
==================
CL_VideoFilename
==================
*/
void CL_VideoFilename( char *buf, int bufSize ) {
time_t rawtime;
char timeStr[32] = {0}; // should really only reach ~19 chars
time( &rawtime );
strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime
Com_sprintf( buf, bufSize, "videos/video%s.avi", timeStr );
}
/*
===============
CL_Video_f
video
video [filename]
===============
*/
void CL_Video_f( void )
{
char filename[ MAX_OSPATH ];
if( !clc.demoplaying )
{
Com_Printf( "The video command can only be used when playing back demos\n" );
return;
}
if( Cmd_Argc( ) == 2 )
{
// explicit filename
Com_sprintf( filename, MAX_OSPATH, "videos/%s.avi", Cmd_Argv( 1 ) );
}
else
{
CL_VideoFilename( filename, MAX_OSPATH );
if ( FS_FileExists( filename ) ) {
Com_Printf( "Video: Couldn't create a file\n");
return;
}
}
CL_OpenAVIForWriting( filename );
}
/*
===============
CL_StopVideo_f
===============
*/
void CL_StopVideo_f( void )
{
CL_CloseAVI( );
}
static void CL_AddFavorite_f( void ) {
const bool connected = (cls.state == CA_ACTIVE) && !clc.demoplaying;
const int argc = Cmd_Argc();
if ( !connected && argc != 2 ) {
Com_Printf( "syntax: addFavorite <ip or hostname>\n" );
return;
}
const char *server = (argc == 2) ? Cmd_Argv( 1 ) : NET_AdrToString( clc.serverAddress );
const int status = LAN_AddFavAddr( server );
switch ( status ) {
case -1:
Com_Printf( "error adding favorite server: too many favorite servers\n" );
break;
case 0:
Com_Printf( "error adding favorite server: server already exists\n" );
break;
case 1:
Com_Printf( "successfully added favorite server \"%s\"\n", server );
break;
default:
Com_Printf( "unknown error (%i) adding favorite server\n", status );
break;
}
}
#define G2_VERT_SPACE_CLIENT_SIZE 256
/*
===============
CL_GenerateQKey
test to see if a valid QKEY_FILE exists. If one does not, try to generate
it by filling it with 2048 bytes of random data.
===============
*/
static void CL_GenerateQKey(void)
{
if (cl_enableGuid->integer) {
int len = 0;
unsigned char buff[ QKEY_SIZE ];
fileHandle_t f;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
if( len == QKEY_SIZE ) {
Com_Printf( "QKEY found.\n" );
return;
}
else {
if( len > 0 ) {
Com_Printf( "QKEY file size != %d, regenerating\n",
QKEY_SIZE );
}
Com_Printf( "QKEY building random string\n" );
Com_RandomBytes( buff, sizeof(buff) );
f = FS_SV_FOpenFileWrite( QKEY_FILE );
if( !f ) {
Com_Printf( "QKEY could not open %s for write\n",
QKEY_FILE );
return;
}
FS_Write( buff, sizeof(buff), f );
FS_FCloseFile( f );
Com_Printf( "QKEY generated\n" );
}
}
}
/*
====================
CL_Init
====================
*/
void CL_Init( void ) {
// Com_Printf( "----- Client Initialization -----\n" );
Con_Init ();
CL_ClearState ();
cls.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
cls.realtime = 0;
CL_InitInput ();
//
// register our variables
//
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
cl_motd = Cvar_Get ("cl_motd", "1", CVAR_ARCHIVE, "Display welcome message from master server on the bottom of connection screen" );
cl_motdServer[0] = Cvar_Get( "cl_motdServer1", UPDATE_SERVER_NAME, 0 );
cl_motdServer[1] = Cvar_Get( "cl_motdServer2", JKHUB_UPDATE_SERVER_NAME, 0 );
for ( int index = 2; index < MAX_MASTER_SERVERS; index++ )
cl_motdServer[index] = Cvar_Get( va( "cl_motdServer%d", index + 1 ), "", CVAR_ARCHIVE );
cl_timeout = Cvar_Get ("cl_timeout", "200", 0);
cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP );
cl_showSend = Cvar_Get ("cl_showSend", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP );
cl_freezeDemo = Cvar_Get ("cl_freezeDemo", "0", CVAR_TEMP );
rcon_client_password = Cvar_Get ("rconPassword", "", CVAR_TEMP, "Password for remote console access" );
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_timedemo = Cvar_Get ("timedemo", "0", 0);
cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE);
cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE);
cl_avi2GBLimit = Cvar_Get ("cl_avi2GBLimit", "1", CVAR_ARCHIVE );
cl_forceavidemo = Cvar_Get ("cl_forceavidemo", "0", 0);
rconAddress = Cvar_Get ("rconAddress", "", 0, "Alternate server address to remotely access via rcon protocol");
cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE);
cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE);
cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", CVAR_ARCHIVE);
cl_maxpackets = Cvar_Get ("cl_maxpackets", "63", CVAR_ARCHIVE );
cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE );
cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE, "Always run");
cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE, "Mouse sensitivity value");
cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE, "Mouse acceleration value");
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE, "Mouse look" );
// 0: legacy mouse acceleration
// 1: new implementation
cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE, "Mouse accelration style (0:legacy, 1:QuakeLive)" );
// offset for the power function (for style 1, ignored otherwise)
// this should be set to the max rate value
cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE, "Mouse acceleration offset for style 1" );
cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0);
cl_framerate = Cvar_Get ("cl_framerate", "0", CVAR_TEMP);
cl_allowDownload = Cvar_Get ("cl_allowDownload", "0", CVAR_ARCHIVE, "Allow downloading custom paks from server");
cl_allowAltEnter = Cvar_Get ("cl_allowAltEnter", "1", CVAR_ARCHIVE, "Enables use of ALT+ENTER keyboard combo to toggle fullscreen" );
cl_autolodscale = Cvar_Get( "cl_autolodscale", "1", CVAR_ARCHIVE );
cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0);
cl_inGameVideo = Cvar_Get ("r_inGameVideo", "1", CVAR_ARCHIVE);
cl_serverStatusResendTime = Cvar_Get ("cl_serverStatusResendTime", "750", 0);
// init autoswitch so the ui will have it correctly even
// if the cgame hasn't been started
Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE);
m_pitchVeh = Cvar_Get ("m_pitchVeh", "0.022", CVAR_ARCHIVE);
m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE);
m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE);
m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE);
m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE);
#ifdef MACOS_X
// Input is jittery on OS X w/o this
m_filter = Cvar_Get ("m_filter", "1", CVAR_ARCHIVE);
#else
m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE);
#endif
cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM );
Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE, "Max. ping for servers when searching the serverlist" );
cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE);
// enable the ja_guid player identifier in userinfo by default in OpenJK
cl_enableGuid = Cvar_Get("cl_enableGuid", "1", CVAR_ARCHIVE, "Enable GUID userinfo identifier" );
cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE, "Use a unique guid value per server" );
// ~ and `, as keys and characters
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60 0xb2", CVAR_ARCHIVE, "Which keys are used to toggle the console");
cl_consoleUseScanCode = Cvar_Get( "cl_consoleUseScanCode", "1", CVAR_ARCHIVE, "Use native console key detection" );
// userinfo
Cvar_Get ("name", "Padawan", CVAR_USERINFO | CVAR_ARCHIVE, "Player name" );
Cvar_Get ("rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE, "Data rate" );
Cvar_Get ("snaps", "40", CVAR_USERINFO | CVAR_ARCHIVE, "Client snapshots per second" );
Cvar_Get ("model", DEFAULT_MODEL"/default", CVAR_USERINFO | CVAR_ARCHIVE, "Player model" );
Cvar_Get ("forcepowers", "7-1-032330000000001333", CVAR_USERINFO | CVAR_ARCHIVE, "Player forcepowers" );
// Cvar_Get ("g_redTeam", DEFAULT_REDTEAM_NAME, CVAR_SERVERINFO | CVAR_ARCHIVE);
// Cvar_Get ("g_blueTeam", DEFAULT_BLUETEAM_NAME, CVAR_SERVERINFO | CVAR_ARCHIVE);
Cvar_Get ("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE, "Player saber1 color" );
Cvar_Get ("color2", "4", CVAR_USERINFO | CVAR_ARCHIVE, "Player saber2 color" );
Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE, "Player handicap" );
Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE, "Player sex" );
Cvar_Get ("password", "", CVAR_USERINFO, "Password to join server" );
Cvar_Get ("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE );
//default sabers
Cvar_Get ("saber1", DEFAULT_SABER, CVAR_USERINFO | CVAR_ARCHIVE, "Player default right hand saber" );
Cvar_Get ("saber2", "none", CVAR_USERINFO | CVAR_ARCHIVE, "Player left hand saber" );
//skin color
Cvar_Get ("char_color_red", "255", CVAR_USERINFO | CVAR_ARCHIVE, "Player tint (Red)" );
Cvar_Get ("char_color_green", "255", CVAR_USERINFO | CVAR_ARCHIVE, "Player tint (Green)" );
Cvar_Get ("char_color_blue", "255", CVAR_USERINFO | CVAR_ARCHIVE, "Player tint (Blue)" );
// cgame might not be initialized before menu is used
Cvar_Get ("cg_viewsize", "100", CVAR_ARCHIVE );
//
// register our commands
//
Cmd_AddCommand ("cmd", CL_ForwardToServer_f, "Forward command to server" );
Cmd_AddCommand ("globalservers", CL_GlobalServers_f, "Query the masterserver for serverlist" );
Cmd_AddCommand( "addFavorite", CL_AddFavorite_f, "Add server to favorites" );
Cmd_AddCommand ("record", CL_Record_f, "Record a demo" );
Cmd_AddCommand ("demo", CL_PlayDemo_f, "Playback a demo" );
Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName );
Cmd_AddCommand ("stoprecord", CL_StopRecord_f, "Stop recording a demo" );
Cmd_AddCommand ("configstrings", CL_Configstrings_f, "Prints the configstrings list" );
Cmd_AddCommand ("clientinfo", CL_Clientinfo_f, "Prints the userinfo variables" );
Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f, "Restart sound" );
Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f, "Restart the renderer - or change the resolution" );
Cmd_AddCommand ("disconnect", CL_Disconnect_f, "Disconnect from current server" );
Cmd_AddCommand ("cinematic", CL_PlayCinematic_f, "Play a cinematic video" );
Cmd_AddCommand ("connect", CL_Connect_f, "Connect to a server" );
Cmd_AddCommand ("reconnect", CL_Reconnect_f, "Reconnect to current server" );
Cmd_AddCommand ("localservers", CL_LocalServers_f, "Query LAN for local servers" );
Cmd_AddCommand ("rcon", CL_Rcon_f, "Execute commands remotely to a server" );
Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon );
Cmd_AddCommand ("ping", CL_Ping_f, "Ping a server for info response" );
Cmd_AddCommand ("serverstatus", CL_ServerStatus_f, "Retrieve current or specified server's status" );
Cmd_AddCommand ("showip", CL_ShowIP_f, "Shows local IP" );
Cmd_AddCommand ("fs_openedList", CL_OpenedPK3List_f, "Lists open pak files" );
Cmd_AddCommand ("fs_referencedList", CL_ReferencedPK3List_f, "Lists referenced pak files" );
Cmd_AddCommand ("model", CL_SetModel_f, "Set the player model" );
Cmd_AddCommand ("forcepowers", CL_SetForcePowers_f );
Cmd_AddCommand ("video", CL_Video_f, "Record demo to avi" );
Cmd_AddCommand ("stopvideo", CL_StopVideo_f, "Stop avi recording" );
CL_InitRef();
SCR_Init ();
Cbuf_Execute ();
Cvar_Set( "cl_running", "1" );
G2VertSpaceClient = new CMiniHeap (G2_VERT_SPACE_CLIENT_SIZE * 1024);
CL_GenerateQKey();
CL_UpdateGUID( NULL, 0 );
// Com_Printf( "----- Client Initialization Complete -----\n" );
}
/*
===============
CL_Shutdown
===============
*/
void CL_Shutdown( void ) {
static qboolean recursive = qfalse;
//Com_Printf( "----- CL_Shutdown -----\n" );
if ( recursive ) {
printf ("recursive CL_Shutdown shutdown\n");
return;
}
recursive = qtrue;
if (G2VertSpaceClient)
{
delete G2VertSpaceClient;
G2VertSpaceClient = 0;
}
CL_Disconnect( qtrue );
// RJ: added the shutdown all to close down the cgame (to free up some memory, such as in the fx system)
CL_ShutdownAll( qtrue );
S_Shutdown();
//CL_ShutdownUI();
Cmd_RemoveCommand ("cmd");
Cmd_RemoveCommand ("configstrings");
Cmd_RemoveCommand ("clientinfo");
Cmd_RemoveCommand ("snd_restart");
Cmd_RemoveCommand ("vid_restart");
Cmd_RemoveCommand ("disconnect");
Cmd_RemoveCommand ("record");
Cmd_RemoveCommand ("demo");
Cmd_RemoveCommand ("cinematic");
Cmd_RemoveCommand ("stoprecord");
Cmd_RemoveCommand ("connect");
Cmd_RemoveCommand ("reconnect");
Cmd_RemoveCommand ("localservers");
Cmd_RemoveCommand ("globalservers");
Cmd_RemoveCommand( "addFavorite" );
Cmd_RemoveCommand ("rcon");
Cmd_RemoveCommand ("ping");
Cmd_RemoveCommand ("serverstatus");
Cmd_RemoveCommand ("showip");
Cmd_RemoveCommand ("fs_openedList");
Cmd_RemoveCommand ("fs_referencedList");
Cmd_RemoveCommand ("model");
Cmd_RemoveCommand ("forcepowers");
Cmd_RemoveCommand ("video");
Cmd_RemoveCommand ("stopvideo");
CL_ShutdownInput();
Con_Shutdown();
Cvar_Set( "cl_running", "0" );
recursive = qfalse;
Com_Memset( &cls, 0, sizeof( cls ) );
Key_SetCatcher( 0 );
//Com_Printf( "-----------------------\n" );
}
qboolean CL_ConnectedToRemoteServer( void ) {
return (qboolean)( com_sv_running && !com_sv_running->integer && cls.state >= CA_CONNECTED && !clc.demoplaying );
}
static void CL_SetServerInfo(serverInfo_t *server, const char *info, int ping) {
if (server) {
if (info) {
server->clients = atoi(Info_ValueForKey(info, "clients"));
Q_strncpyz(server->hostName,Info_ValueForKey(info, "hostname"), MAX_NAME_LENGTH);
Q_strncpyz(server->mapName, Info_ValueForKey(info, "mapname"), MAX_NAME_LENGTH);
server->maxClients = atoi(Info_ValueForKey(info, "sv_maxclients"));
Q_strncpyz(server->game,Info_ValueForKey(info, "game"), MAX_NAME_LENGTH);
server->gameType = atoi(Info_ValueForKey(info, "gametype"));
server->netType = atoi(Info_ValueForKey(info, "nettype"));
server->minPing = atoi(Info_ValueForKey(info, "minping"));
server->maxPing = atoi(Info_ValueForKey(info, "maxping"));
// server->allowAnonymous = atoi(Info_ValueForKey(info, "sv_allowAnonymous"));
server->needPassword = (qboolean)atoi(Info_ValueForKey(info, "needpass" ));
server->trueJedi = atoi(Info_ValueForKey(info, "truejedi" ));
server->weaponDisable = atoi(Info_ValueForKey(info, "wdisable" ));
server->forceDisable = atoi(Info_ValueForKey(info, "fdisable" ));
server->humans = atoi( Info_ValueForKey( info, "g_humanplayers" ) );
server->bots = atoi( Info_ValueForKey( info, "bots" ) );
// server->pure = (qboolean)atoi(Info_ValueForKey(info, "pure" ));
}
server->ping = ping;
}
}
static void CL_SetServerInfoByAddress(netadr_t from, const char *info, int ping) {
int i;
for (i = 0; i < MAX_OTHER_SERVERS; i++) {
if (NET_CompareAdr(from, cls.localServers[i].adr)) {
CL_SetServerInfo(&cls.localServers[i], info, ping);
}
}
for (i = 0; i < MAX_GLOBAL_SERVERS; i++) {
if (NET_CompareAdr(from, cls.globalServers[i].adr)) {
CL_SetServerInfo(&cls.globalServers[i], info, ping);
}
}
for (i = 0; i < MAX_OTHER_SERVERS; i++) {
if (NET_CompareAdr(from, cls.favoriteServers[i].adr)) {
CL_SetServerInfo(&cls.favoriteServers[i], info, ping);
}
}
}
/*
===================
CL_ServerInfoPacket
===================
*/
void CL_ServerInfoPacket( netadr_t from, msg_t *msg ) {
int i, type;
char info[MAX_INFO_STRING];
char *infoString;
int prot;
infoString = MSG_ReadString( msg );
// if this isn't the correct protocol version, ignore it
prot = atoi( Info_ValueForKey( infoString, "protocol" ) );
if ( prot != PROTOCOL_VERSION ) {
Com_DPrintf( "Different protocol info packet: %s\n", infoString );
return;
}
// iterate servers waiting for ping response
for (i=0; i<MAX_PINGREQUESTS; i++)
{
if ( cl_pinglist[i].adr.port && !cl_pinglist[i].time && NET_CompareAdr( from, cl_pinglist[i].adr ) )
{
// calc ping time
cl_pinglist[i].time = Sys_Milliseconds() - cl_pinglist[i].start;
Com_DPrintf( "ping time %dms from %s\n", cl_pinglist[i].time, NET_AdrToString( from ) );
// save of info
Q_strncpyz( cl_pinglist[i].info, infoString, sizeof( cl_pinglist[i].info ) );
// tack on the net type
// NOTE: make sure these types are in sync with the netnames strings in the UI
switch (from.type)
{
case NA_BROADCAST:
case NA_IP:
type = 1;
break;
default:
type = 0;
break;
}
Info_SetValueForKey( cl_pinglist[i].info, "nettype", va("%d", type) );
CL_SetServerInfoByAddress(from, infoString, cl_pinglist[i].time);
return;
}
}
// if not just sent a local broadcast or pinging local servers
if (cls.pingUpdateSource != AS_LOCAL) {
return;
}
for ( i = 0 ; i < MAX_OTHER_SERVERS ; i++ ) {
// empty slot
if ( cls.localServers[i].adr.port == 0 ) {
break;
}
// avoid duplicate
if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) {
return;
}
}
if ( i == MAX_OTHER_SERVERS ) {
Com_DPrintf( "MAX_OTHER_SERVERS hit, dropping infoResponse\n" );
return;
}
// add this to the list
cls.numlocalservers = i+1;
CL_InitServerInfo( &cls.localServers[i], &from );
Q_strncpyz( info, MSG_ReadString( msg ), MAX_INFO_STRING );
if (strlen(info)) {
if (info[strlen(info)-1] != '\n') {
strncat(info, "\n", sizeof(info) -1);
}
Com_Printf( "%s: %s", NET_AdrToString( from ), info );
}
}
/*
===================
CL_GetServerStatus
===================
*/
serverStatus_t *CL_GetServerStatus( netadr_t from ) {
int i, oldest, oldestTime;
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
return &cl_serverStatusList[i];
}
}
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
if ( cl_serverStatusList[i].retrieved ) {
return &cl_serverStatusList[i];
}
}
oldest = -1;
oldestTime = 0;
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
if (oldest == -1 || cl_serverStatusList[i].startTime < oldestTime) {
oldest = i;
oldestTime = cl_serverStatusList[i].startTime;
}
}
if (oldest != -1) {
return &cl_serverStatusList[oldest];
}
serverStatusCount++;
return &cl_serverStatusList[serverStatusCount & (MAX_SERVERSTATUSREQUESTS-1)];
}
/*
===================
CL_ServerStatus
===================
*/
int CL_ServerStatus( const char *serverAddress, char *serverStatusString, int maxLen ) {
int i;
netadr_t to;
serverStatus_t *serverStatus;
// if no server address then reset all server status requests
if ( !serverAddress ) {
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
cl_serverStatusList[i].address.port = 0;
cl_serverStatusList[i].retrieved = qtrue;
}
return qfalse;
}
// get the address
if ( !NET_StringToAdr( serverAddress, &to ) ) {
return qfalse;
}
serverStatus = CL_GetServerStatus( to );
// if no server status string then reset the server status request for this address
if ( !serverStatusString ) {
serverStatus->retrieved = qtrue;
return qfalse;
}
// if this server status request has the same address
if ( NET_CompareAdr( to, serverStatus->address) ) {
// if we received a response for this server status request
if (!serverStatus->pending) {
Q_strncpyz(serverStatusString, serverStatus->string, maxLen);
serverStatus->retrieved = qtrue;
serverStatus->startTime = 0;
return qtrue;
}
// resend the request regularly
else if ( serverStatus->startTime < Com_Milliseconds() - cl_serverStatusResendTime->integer ) {
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->time = 0;
serverStatus->startTime = Com_Milliseconds();
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
}
// if retrieved
else if ( serverStatus->retrieved ) {
serverStatus->address = to;
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->startTime = Com_Milliseconds();
serverStatus->time = 0;
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
return qfalse;
}
/*
===================
CL_ServerStatusResponse
===================
*/
void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) {
char *s;
char info[MAX_INFO_STRING];
int i, l, score, ping;
int len;
serverStatus_t *serverStatus;
serverStatus = NULL;
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
serverStatus = &cl_serverStatusList[i];
break;
}
}
// if we didn't request this server status
if (!serverStatus) {
return;
}
s = MSG_ReadStringLine( msg );
len = 0;
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "%s", s);
if (serverStatus->print) {
Com_Printf( "Server (%s)\n",
NET_AdrToString( serverStatus->address ) );
Com_Printf("Server settings:\n");
// print cvars
while (*s) {
for (i = 0; i < 2 && *s; i++) {
if (*s == '\\')
s++;
l = 0;
while (*s) {
info[l++] = *s;
if (l >= MAX_INFO_STRING-1)
break;
s++;
if (*s == '\\') {
break;
}
}
info[l] = '\0';
if (i) {
Com_Printf("%s\n", info);
}
else {
Com_Printf("%-24s", info);
}
}
}
}
len = strlen(serverStatus->string);
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\");
if (serverStatus->print) {
Com_Printf("\nPlayers:\n");
Com_Printf("num: score: ping: name:\n");
}
for (i = 0, s = MSG_ReadStringLine( msg ); *s; s = MSG_ReadStringLine( msg ), i++) {
len = strlen(serverStatus->string);
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\%s", s);
if (serverStatus->print) {
score = ping = 0;
sscanf(s, "%d %d", &score, &ping);
s = strchr(s, ' ');
if (s)
s = strchr(s+1, ' ');
if (s)
s++;
else
s = "unknown";
Com_Printf("%-2d %-3d %-3d %s\n", i, score, ping, s );
}
}
len = strlen(serverStatus->string);
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\");
serverStatus->time = Com_Milliseconds();
serverStatus->address = from;
serverStatus->pending = qfalse;
if (serverStatus->print) {
serverStatus->retrieved = qtrue;
}
}
/*
==================
CL_LocalServers_f
==================
*/
void CL_LocalServers_f( void ) {
char *message;
int i, j;
netadr_t to;
Com_Printf( "Scanning for servers on the local network...\n");
// reset the list, waiting for response
cls.numlocalservers = 0;
cls.pingUpdateSource = AS_LOCAL;
for (i = 0; i < MAX_OTHER_SERVERS; i++) {
qboolean b = cls.localServers[i].visible;
Com_Memset(&cls.localServers[i], 0, sizeof(cls.localServers[i]));
cls.localServers[i].visible = b;
}
Com_Memset( &to, 0, sizeof( to ) );
// The 'xxx' in the message is a challenge that will be echoed back
// by the server. We don't care about that here, but master servers
// can use that to prevent spoofed server responses from invalid ip
message = "\377\377\377\377getinfo xxx";
// send each message twice in case one is dropped
for ( i = 0 ; i < 2 ; i++ ) {
// send a broadcast packet on each server port
// we support multiple server ports so a single machine
// can nicely run multiple servers
for ( j = 0 ; j < NUM_SERVER_PORTS ; j++ ) {
to.port = BigShort( (short)(PORT_SERVER + j) );
to.type = NA_BROADCAST;
NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
}
}
}
/*
==================
CL_GlobalServers_f
==================
*/
void CL_GlobalServers_f( void ) {
netadr_t to;
int count, i, masterNum;
char command[1024], *masteraddress;
if ((count = Cmd_Argc()) < 3 || (masterNum = atoi(Cmd_Argv(1))) < 0 || masterNum > MAX_MASTER_SERVERS - 1)
{
Com_Printf("usage: globalservers <master# 0-%d> <protocol> [keywords]\n", MAX_MASTER_SERVERS - 1);
return;
}
Com_sprintf( command, sizeof(command), "sv_master%d", masterNum + 1 );
masteraddress = Cvar_VariableString( command );
if ( !*masteraddress )
{
Com_Printf( "CL_GlobalServers_f: Error: No master server address given.\n" );
return;
}
// reset the list, waiting for response
// -1 is used to distinguish a "no response"
i = NET_StringToAdr( masteraddress, &to );
if (!i)
{
Com_Printf( "CL_GlobalServers_f: Error: could not resolve address of master %s\n", masteraddress );
return;
}
to.type = NA_IP;
to.port = BigShort(PORT_MASTER);
Com_Printf( "Requesting servers from the master %s (%s)...\n", masteraddress, NET_AdrToString( to ) );
cls.numglobalservers = -1;
cls.pingUpdateSource = AS_GLOBAL;
Com_sprintf(command, sizeof(command), "getservers %s", Cmd_Argv(2));
// tack on keywords
for (i = 3; i < count; i++)
{
Q_strcat(command, sizeof(command), " ");
Q_strcat(command, sizeof(command), Cmd_Argv(i));
}
NET_OutOfBandPrint( NS_SERVER, to, "%s", command );
}
/*
==================
CL_GetPing
==================
*/
void CL_GetPing( int n, char *buf, int buflen, int *pingtime )
{
const char *str;
int time;
int maxPing;
if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port)
{
// empty or invalid slot
buf[0] = '\0';
*pingtime = 0;
return;
}
str = NET_AdrToString( cl_pinglist[n].adr );
Q_strncpyz( buf, str, buflen );
time = cl_pinglist[n].time;
if (!time)
{
// check for timeout
time = Sys_Milliseconds() - cl_pinglist[n].start;
maxPing = Cvar_VariableIntegerValue( "cl_maxPing" );
if( maxPing < 100 ) {
maxPing = 100;
}
if (time < maxPing)
{
// not timed out yet
time = 0;
}
}
CL_SetServerInfoByAddress(cl_pinglist[n].adr, cl_pinglist[n].info, cl_pinglist[n].time);
*pingtime = time;
}
/*
==================
CL_GetPingInfo
==================
*/
void CL_GetPingInfo( int n, char *buf, int buflen )
{
if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port)
{
// empty or invalid slot
if (buflen)
buf[0] = '\0';
return;
}
Q_strncpyz( buf, cl_pinglist[n].info, buflen );
}
/*
==================
CL_ClearPing
==================
*/
void CL_ClearPing( int n )
{
if (n < 0 || n >= MAX_PINGREQUESTS)
return;
cl_pinglist[n].adr.port = 0;
}
/*
==================
CL_GetPingQueueCount
==================
*/
int CL_GetPingQueueCount( void )
{
int i;
int count;
ping_t* pingptr;
count = 0;
pingptr = cl_pinglist;
for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ ) {
if (pingptr->adr.port) {
count++;
}
}
return (count);
}
/*
==================
CL_GetFreePing
==================
*/
ping_t* CL_GetFreePing( void )
{
ping_t* pingptr;
ping_t* best;
int oldest;
int i;
int time;
pingptr = cl_pinglist;
for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ )
{
// find free ping slot
if (pingptr->adr.port)
{
if (!pingptr->time)
{
if (Sys_Milliseconds() - pingptr->start < 500)
{
// still waiting for response
continue;
}
}
else if (pingptr->time < 500)
{
// results have not been queried
continue;
}
}
// clear it
pingptr->adr.port = 0;
return (pingptr);
}
// use oldest entry
pingptr = cl_pinglist;
best = cl_pinglist;
oldest = INT_MIN;
for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ )
{
// scan for oldest
time = Sys_Milliseconds() - pingptr->start;
if (time > oldest)
{
oldest = time;
best = pingptr;
}
}
return (best);
}
/*
==================
CL_Ping_f
==================
*/
void CL_Ping_f( void ) {
netadr_t to;
ping_t* pingptr;
char* server;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: ping [server]\n");
return;
}
Com_Memset( &to, 0, sizeof(netadr_t) );
server = Cmd_Argv(1);
if ( !NET_StringToAdr( server, &to ) ) {
return;
}
pingptr = CL_GetFreePing();
memcpy( &pingptr->adr, &to, sizeof (netadr_t) );
pingptr->start = Sys_Milliseconds();
pingptr->time = 0;
CL_SetServerInfoByAddress(pingptr->adr, NULL, 0);
NET_OutOfBandPrint( NS_CLIENT, to, "getinfo xxx" );
}
/*
==================
CL_UpdateVisiblePings_f
==================
*/
qboolean CL_UpdateVisiblePings_f(int source) {
int slots, i;
char buff[MAX_STRING_CHARS];
int pingTime;
int max;
qboolean status = qfalse;
if (source < 0 || source > AS_FAVORITES) {
return qfalse;
}
cls.pingUpdateSource = source;
slots = CL_GetPingQueueCount();
if (slots < MAX_PINGREQUESTS) {
serverInfo_t *server = NULL;
switch (source) {
case AS_LOCAL :
server = &cls.localServers[0];
max = cls.numlocalservers;
break;
case AS_GLOBAL :
server = &cls.globalServers[0];
max = cls.numglobalservers;
break;
case AS_FAVORITES :
server = &cls.favoriteServers[0];
max = cls.numfavoriteservers;
break;
default:
return qfalse;
}
for (i = 0; i < max; i++) {
if (server[i].visible) {
if (server[i].ping == -1) {
int j;
if (slots >= MAX_PINGREQUESTS) {
break;
}
for (j = 0; j < MAX_PINGREQUESTS; j++) {
if (!cl_pinglist[j].adr.port) {
continue;
}
if (NET_CompareAdr( cl_pinglist[j].adr, server[i].adr)) {
// already on the list
break;
}
}
if (j >= MAX_PINGREQUESTS) {
status = qtrue;
for (j = 0; j < MAX_PINGREQUESTS; j++) {
if (!cl_pinglist[j].adr.port) {
break;
}
}
memcpy(&cl_pinglist[j].adr, &server[i].adr, sizeof(netadr_t));
cl_pinglist[j].start = Sys_Milliseconds();
cl_pinglist[j].time = 0;
NET_OutOfBandPrint( NS_CLIENT, cl_pinglist[j].adr, "getinfo xxx" );
slots++;
}
}
// if the server has a ping higher than cl_maxPing or
// the ping packet got lost
else if (server[i].ping == 0) {
// if we are updating global servers
if (source == AS_GLOBAL) {
//
if ( cls.numGlobalServerAddresses > 0 ) {
// overwrite this server with one from the additional global servers
cls.numGlobalServerAddresses--;
CL_InitServerInfo(&server[i], &cls.globalServerAddresses[cls.numGlobalServerAddresses]);
// NOTE: the server[i].visible flag stays untouched
}
}
}
}
}
}
if (slots) {
status = qtrue;
}
for (i = 0; i < MAX_PINGREQUESTS; i++) {
if (!cl_pinglist[i].adr.port) {
continue;
}
CL_GetPing( i, buff, MAX_STRING_CHARS, &pingTime );
if (pingTime != 0) {
CL_ClearPing(i);
status = qtrue;
}
}
return status;
}
/*
==================
CL_ServerStatus_f
==================
*/
void CL_ServerStatus_f(void) {
netadr_t to, *toptr = NULL;
char *server;
serverStatus_t *serverStatus;
if ( Cmd_Argc() != 2 ) {
if ( cls.state != CA_ACTIVE || clc.demoplaying ) {
Com_Printf ("Not connected to a server.\n");
Com_Printf( "Usage: serverstatus [server]\n");
return;
}
toptr = &clc.serverAddress;
}
if(!toptr)
{
Com_Memset( &to, 0, sizeof(netadr_t) );
server = Cmd_Argv(1);
toptr = &to;
if ( !NET_StringToAdr( server, toptr ) )
return;
}
NET_OutOfBandPrint( NS_CLIENT, *toptr, "getstatus" );
serverStatus = CL_GetServerStatus( *toptr );
serverStatus->address = *toptr;
serverStatus->print = qtrue;
serverStatus->pending = qtrue;
}
/*
==================
CL_ShowIP_f
==================
*/
void CL_ShowIP_f(void) {
Sys_ShowIP();
}
| ./CrossVul/dataset_final_sorted/CWE-269/cpp/good_3234_2 |
crossvul-cpp_data_good_3234_1 | /*
===========================================================================
Copyright (C) 1999 - 2005, Id Software, Inc.
Copyright (C) 2000 - 2013, Raven Software, Inc.
Copyright (C) 2001 - 2013, Activision, Inc.
Copyright (C) 2005 - 2015, ioquake3 contributors
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
/*****************************************************************************
* name: files.cpp
*
* desc: file code
*
*****************************************************************************/
#include "q_shared.h"
#include "qcommon.h"
#ifndef FINAL_BUILD
#include "../client/client.h"
#endif
#include <minizip/unzip.h>
// for rmdir
#if defined (_MSC_VER)
#include <direct.h>
#else
#include <unistd.h>
#endif
#if defined(_WIN32)
#include <windows.h>
#endif
/*
=============================================================================
QUAKE3 FILESYSTEM
All of Quake's data access is through a hierarchical file system, but the contents of
the file system can be transparently merged from several sources.
A "qpath" is a reference to game file data. MAX_ZPATH is 256 characters, which must include
a terminating zero. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any
references outside the quake directory system.
The "base path" is the path to the directory holding all the game directories and usually
the executable. It defaults to ".", but can be overridden with a "+set fs_basepath c:\quake3"
command line to allow code debugging in a different directory. Basepath cannot
be modified at all after startup. Any files that are created (demos, screenshots,
etc) will be created relative to the base path, so base path should usually be writable.
The "home path" is the path used for all write access. On win32 systems we have "base path"
== "home path", but on *nix systems the base installation is usually readonly, and
"home path" points to ~/.q3a or similar
The user can also install custom mods and content in "home path", so it should be searched
along with "home path" and "cd path" for game content.
The "base game" is the directory under the paths where data comes from by default, and
can be either "baseq3" or "demoq3".
The "current game" may be the same as the base game, or it may be the name of another
directory under the paths that should be searched for files before looking in the base game.
This is the basis for addons.
Clients automatically set the game directory after receiving a gamestate from a server,
so only servers need to worry about +set fs_game.
No other directories outside of the base game and current game will ever be referenced by
filesystem functions.
To save disk space and speed loading, directory trees can be collapsed into zip files.
The files use a ".pk3" extension to prevent users from unzipping them accidentally, but
otherwise the are simply normal uncompressed zip files. A game directory can have multiple
zip files of the form "pak0.pk3", "pak1.pk3", etc. Zip files are searched in decending order
from the highest number to the lowest, and will always take precedence over the filesystem.
This allows a pk3 distributed as a patch to override all existing data.
Because we will have updated executables freely available online, there is no point to
trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
should be exactly the same executables as release versions, but with different data that
automatically restricts where game media can come from to prevent add-ons from working.
File search order: when FS_FOpenFileRead gets called it will go through the fs_searchpaths
structure and stop on the first successful hit. fs_searchpaths is built with successive
calls to FS_AddGameDirectory
Additionaly, we search in several subdirectories:
current game is the current mode
base game is a variable to allow mods based on other mods
(such as baseq3 + missionpack content combination in a mod for instance)
BASEGAME is the hardcoded base game ("baseq3")
e.g. the qpath "sound/newstuff/test.wav" would be searched for in the following places:
home path + current game's zip files
home path + current game's directory
base path + current game's zip files
base path + current game's directory
cd path + current game's zip files
cd path + current game's directory
home path + base game's zip file
home path + base game's directory
base path + base game's zip file
base path + base game's directory
cd path + base game's zip file
cd path + base game's directory
home path + BASEGAME's zip file
home path + BASEGAME's directory
base path + BASEGAME's zip file
base path + BASEGAME's directory
cd path + BASEGAME's zip file
cd path + BASEGAME's directory
server download, to be written to home path + current game's directory
The filesystem can be safely shutdown and reinitialized with different
basedir / cddir / game combinations, but all other subsystems that rely on it
(sound, video) must also be forced to restart.
Because the same files are loaded by both the clip model (CM_) and renderer (TR_)
subsystems, a simple single-file caching scheme is used. The CM_ subsystems will
load the file with a request to cache. Only one file will be kept cached at a time,
so any models that are going to be referenced by both subsystems should alternate
between the CM_ load function and the ref load function.
TODO: A qpath that starts with a leading slash will always refer to the base game, even if another
game is currently active. This allows character models, skins, and sounds to be downloaded
to a common directory no matter which game is active.
How to prevent downloading zip files?
Pass pk3 file names in systeminfo, and download before FS_Restart()?
Aborting a download disconnects the client from the server.
How to mark files as downloadable? Commercial add-ons won't be downloadable.
Non-commercial downloads will want to download the entire zip file.
the game would have to be reset to actually read the zip in
Auto-update information
Path separators
Casing
separate server gamedir and client gamedir, so if the user starts
a local game after having connected to a network game, it won't stick
with the network game.
allow menu options for game selection?
Read / write config to floppy option.
Different version coexistance?
When building a pak file, make sure a q3config.cfg isn't present in it,
or configs will never get loaded from disk!
todo:
downloading (outside fs?)
game directory passing and restarting
=============================================================================
*/
/*static const uint32_t pak_checksums[] = {
0u,
};
static const uint32_t bonuspak_checksum = 0u;*/
#define MAX_ZPATH 256
#define MAX_SEARCH_PATHS 4096
#define MAX_FILEHASH_SIZE 1024
typedef struct fileInPack_s {
char *name; // name of the file
unsigned long pos; // file info position in zip
unsigned long len; // uncompress file size
struct fileInPack_s* next; // next file in the hash
} fileInPack_t;
typedef struct pack_s {
char pakPathname[MAX_OSPATH]; // c:\jediacademy\gamedata\base
char pakFilename[MAX_OSPATH]; // c:\jediacademy\gamedata\base\assets0.pk3
char pakBasename[MAX_OSPATH]; // assets0
char pakGamename[MAX_OSPATH]; // base
unzFile handle; // handle to zip file
int checksum; // regular checksum
int numfiles; // number of files in pk3
int hashSize; // hash table size (power of 2)
fileInPack_t* *hashTable; // hash table
fileInPack_t* buildBuffer; // buffer with the filenames etc.
} pack_t;
typedef struct directory_s {
char path[MAX_OSPATH]; // c:\jediacademy\gamedata
char fullpath[MAX_OSPATH]; // c:\jediacademy\gamedata\base
char gamedir[MAX_OSPATH]; // base
} directory_t;
typedef struct searchpath_s {
struct searchpath_s *next;
pack_t *pack; // only one of pack / dir will be non NULL
directory_t *dir;
} searchpath_t;
static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators
static cvar_t *fs_debug;
static cvar_t *fs_homepath;
#ifdef MACOS_X
// Also search the .app bundle for .pk3 files
static cvar_t *fs_apppath;
#endif
static cvar_t *fs_basepath;
static cvar_t *fs_basegame;
static cvar_t *fs_cdpath;
static cvar_t *fs_copyfiles;
static cvar_t *fs_gamedirvar;
static cvar_t *fs_dirbeforepak; //rww - when building search path, keep directories at top and insert pk3's under them
static searchpath_t *fs_searchpaths;
static int fs_readCount; // total bytes read
static int fs_loadCount; // total files read
static int fs_packFiles = 0; // total number of files in packs
typedef union qfile_gus {
FILE* o;
unzFile z;
} qfile_gut;
typedef struct qfile_us {
qfile_gut file;
qboolean unique;
} qfile_ut;
typedef struct fileHandleData_s {
qfile_ut handleFiles;
qboolean handleSync;
int fileSize;
int zipFilePos;
int zipFileLen;
qboolean zipFile;
char name[MAX_ZPATH];
} fileHandleData_t;
static fileHandleData_t fsh[MAX_FILE_HANDLES];
// last valid game folder used
char lastValidBase[MAX_OSPATH];
char lastValidGame[MAX_OSPATH];
/* C99 defines __func__ */
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2 || _MSC_VER >= 1300
# define __func__ __FUNCTION__
# else
# define __func__ "(unknown)"
# endif
#endif
/*
==============
FS_Initialized
==============
*/
qboolean FS_Initialized( void ) {
return (qboolean)(fs_searchpaths != NULL);
}
static void FS_AssertInitialised( void ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
}
}
/*
================
return a hash value for the filename
================
*/
static long FS_HashFileName( const char *fname, int hashSize ) {
int i;
long hash;
char letter;
hash = 0;
i = 0;
while (fname[i] != '\0') {
letter = tolower(fname[i]);
if (letter =='.') break; // don't include extension
if (letter =='\\') letter = '/'; // damn path names
if (letter == PATH_SEP) letter = '/'; // damn path names
hash+=(long)(letter)*(i+119);
i++;
}
hash = (hash ^ (hash >> 10) ^ (hash >> 20));
hash &= (hashSize-1);
return hash;
}
static fileHandle_t FS_HandleForFile(void) {
int i;
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o == NULL ) {
return i;
}
}
Com_Printf( "FS_HandleForFile: all handles taken:\n" );
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
Com_Printf( "%d. %s\n", i, fsh[i].name);
}
Com_Error( ERR_DROP, "FS_HandleForFile: none free" );
return 0;
}
static FILE *FS_FileForHandle( fileHandle_t f ) {
if ( f < 1 || f >= MAX_FILE_HANDLES ) {
Com_Error( ERR_DROP, "FS_FileForHandle: out of range" );
}
if (fsh[f].zipFile == qtrue) {
Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" );
}
if ( ! fsh[f].handleFiles.file.o ) {
Com_Error( ERR_DROP, "FS_FileForHandle: NULL" );
}
return fsh[f].handleFiles.file.o;
}
void FS_ForceFlush( fileHandle_t f ) {
FILE *file;
file = FS_FileForHandle(f);
setvbuf( file, NULL, _IONBF, 0 );
}
/*
================
FS_fplength
================
*/
long FS_fplength(FILE *h)
{
long pos;
long end;
pos = ftell(h);
if ( pos == EOF )
return EOF;
fseek(h, 0, SEEK_END);
end = ftell(h);
fseek(h, pos, SEEK_SET);
return end;
}
/*
================
FS_filelength
If this is called on a non-unique FILE (from a pak file),
it will return the size of the pak file, not the expected
size of the file.
================
*/
int FS_filelength( fileHandle_t f ) {
FILE *h;
h = FS_FileForHandle(f);
if(h == NULL)
return EOF;
else
return FS_fplength(h);
}
/*
====================
FS_ReplaceSeparators
Fix things up differently for win/unix/mac
====================
*/
void FS_ReplaceSeparators( char *path ) {
char *s;
qboolean lastCharWasSep = qfalse;
for ( s = path ; *s ; s++ ) {
if ( *s == '/' || *s == '\\' ) {
if ( !lastCharWasSep ) {
*s = PATH_SEP;
lastCharWasSep = qtrue;
} else {
memmove (s, s + 1, strlen (s));
}
} else {
lastCharWasSep = qfalse;
}
}
}
/*
===================
FS_BuildOSPath
Qpath may have either forward or backwards slashes
===================
*/
char *FS_BuildOSPath( const char *qpath ) {
char temp[MAX_OSPATH];
static char ospath[4][MAX_OSPATH];
static int toggle;
int nextToggle = (toggle + 1)&3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement)
toggle = nextToggle;
// Fix for filenames that are given to FS with a leading "/" (/botfiles/Foo)
if (qpath[0] == '\\' || qpath[0] == '/')
qpath++;
Com_sprintf( temp, sizeof(temp), "/base/%s", qpath ); // FIXME SP used fs_gamedir here as well (not sure if this func is even used)
FS_ReplaceSeparators( temp );
Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", fs_basepath->string, temp );
return ospath[toggle];
}
char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) {
char temp[MAX_OSPATH];
static char ospath[4][MAX_OSPATH];
static int toggle;
int nextToggle = (toggle + 1)&3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement)
toggle = nextToggle;
if( !game || !game[0] ) {
game = fs_gamedir;
}
Com_sprintf( temp, sizeof(temp), "/%s/%s", game, qpath );
FS_ReplaceSeparators( temp );
Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp );
return ospath[toggle];
}
/*
============
FS_CreatePath
Creates any directories needed to store the given filename
============
*/
qboolean FS_CreatePath (char *OSPath) {
char *ofs;
char path[MAX_OSPATH];
// make absolutely sure that it can't back up the path
// FIXME: is c: allowed???
if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) {
Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath );
return qtrue;
}
Q_strncpyz( path, OSPath, sizeof( path ) );
FS_ReplaceSeparators( path );
// Skip creation of the root directory as it will always be there
ofs = strchr( path, PATH_SEP );
if ( ofs ) {
ofs++;
}
for (; ofs != NULL && *ofs ; ofs++) {
if (*ofs == PATH_SEP) {
// create the directory
*ofs = 0;
if (!Sys_Mkdir (path)) {
Com_Error( ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"",
path );
}
*ofs = PATH_SEP;
}
}
return qfalse;
}
/*
=================
FS_CheckFilenameIsMutable
ERR_FATAL if trying to maniuplate a file with the platform library, or pk3 extension
=================
*/
static void FS_CheckFilenameIsMutable( const char *filename, const char *function )
{
// Check if the filename ends with the library, or pk3 extension
if( COM_CompareExtension( filename, DLL_EXT )
|| COM_CompareExtension( filename, ".pk3" ) )
{
Com_Error( ERR_FATAL, "%s: Not allowed to manipulate '%s' due "
"to %s extension", function, filename, COM_GetExtension( filename ) );
}
}
/*
=================
FS_CopyFile
Copy a fully specified file from one place to another
=================
*/
// added extra param so behind-the-scenes copying in savegames doesn't clutter up the screen -slc
void FS_CopyFile( char *fromOSPath, char *toOSPath, qboolean qbSilent = qfalse );
void FS_CopyFile( char *fromOSPath, char *toOSPath, qboolean qbSilent ) {
FILE *f;
int len;
byte *buf;
FS_CheckFilenameIsMutable( fromOSPath, __func__ );
if ( !qbSilent )
Com_Printf( "copy %s to %s\n", fromOSPath, toOSPath );
f = fopen( fromOSPath, "rb" );
if ( !f ) {
return;
}
fseek (f, 0, SEEK_END);
len = ftell (f);
fseek (f, 0, SEEK_SET);
if ( len == EOF )
{
fclose( f );
if ( qbSilent )
return;
Com_Error( ERR_FATAL, "Bad file length in FS_CopyFile()" );
}
// we are using direct malloc instead of Z_Malloc here, so it
// probably won't work on a mac... Its only for developers anyway...
buf = (unsigned char *)malloc( len );
if (fread( buf, 1, len, f ) != (size_t)len)
{
fclose( f );
free ( buf );
if ( qbSilent )
return;
Com_Error( ERR_FATAL, "Short read in FS_Copyfiles()\n" );
}
fclose( f );
if( FS_CreatePath( toOSPath ) ) {
free ( buf );
return;
}
f = fopen( toOSPath, "wb" );
if ( !f ) {
free ( buf );
return;
}
if (fwrite( buf, 1, len, f ) != (size_t)len)
{
fclose( f );
free ( buf );
if ( qbSilent )
return;
Com_Error( ERR_FATAL, "Short write in FS_Copyfiles()\n" );
}
fclose( f );
free( buf );
}
/*
===========
FS_Remove
===========
*/
void FS_Remove( const char *osPath ) {
FS_CheckFilenameIsMutable( osPath, __func__ );
remove( osPath );
}
/*
===========
FS_HomeRemove
===========
*/
void FS_HomeRemove( const char *homePath ) {
FS_CheckFilenameIsMutable( homePath, __func__ );
remove( FS_BuildOSPath( fs_homepath->string,
fs_gamedir, homePath ) );
}
// The following functions with "UserGen" in them were added for savegame handling,
// since outside functions aren't supposed to know about full paths/dirs
// "filename" is local to the current gamedir (eg "saves/blah.sav")
//
void FS_DeleteUserGenFile( const char *filename ) {
FS_HomeRemove( filename );
}
// filenames are local (eg "saves/blah.sav")
//
// return: qtrue = OK
//
qboolean FS_MoveUserGenFile( const char *filename_src, const char *filename_dst ) {
char *from_ospath, *to_ospath;
FS_AssertInitialised();
// don't let sound stutter
S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename_src );
to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename_dst );
if ( fs_debug->integer ) {
Com_Printf( "FS_MoveUserGenFile: %s --> %s\n", from_ospath, to_ospath );
}
FS_CheckFilenameIsMutable( to_ospath, __func__ );
remove( to_ospath );
return (qboolean)!rename( from_ospath, to_ospath );
}
/*
===========
FS_Rmdir
Removes a directory, optionally deleting all files under it
===========
*/
void FS_Rmdir( const char *osPath, qboolean recursive ) {
FS_CheckFilenameIsMutable( osPath, __func__ );
if ( recursive ) {
int numfiles;
int i;
char **filesToRemove = Sys_ListFiles( osPath, "", NULL, &numfiles, qfalse );
for ( i = 0; i < numfiles; i++ ) {
char fileOsPath[MAX_OSPATH];
Com_sprintf( fileOsPath, sizeof( fileOsPath ), "%s/%s", osPath, filesToRemove[i] );
FS_Remove( fileOsPath );
}
FS_FreeFileList( filesToRemove );
char **directoriesToRemove = Sys_ListFiles( osPath, "/", NULL, &numfiles, qfalse );
for ( i = 0; i < numfiles; i++ ) {
if ( !Q_stricmp( directoriesToRemove[i], "." ) || !Q_stricmp( directoriesToRemove[i], ".." ) ) {
continue;
}
char directoryOsPath[MAX_OSPATH];
Com_sprintf( directoryOsPath, sizeof( directoryOsPath ), "%s/%s", osPath, directoriesToRemove[i] );
FS_Rmdir( directoryOsPath, qtrue );
}
FS_FreeFileList( directoriesToRemove );
}
rmdir( osPath );
}
/*
===========
FS_HomeRmdir
Removes a directory, optionally deleting all files under it
===========
*/
void FS_HomeRmdir( const char *homePath, qboolean recursive ) {
FS_CheckFilenameIsMutable( homePath, __func__ );
FS_Rmdir( FS_BuildOSPath( fs_homepath->string,
fs_gamedir, homePath ), recursive );
}
/*
================
FS_FileInPathExists
Tests if path and file exists
================
*/
qboolean FS_FileInPathExists(const char *testpath)
{
FILE *filep;
filep = fopen(testpath, "rb");
if(filep)
{
fclose(filep);
return qtrue;
}
return qfalse;
}
/*
================
FS_FileExists
Tests if the file exists in the current gamedir, this DOES NOT
search the paths. This is to determine if opening a file to write
(which always goes into the current gamedir) will cause any overwrites.
NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards
================
*/
qboolean FS_FileExists( const char *file )
{
return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file));
}
/*
================
FS_SV_FileExists
Tests if the file exists
================
*/
qboolean FS_SV_FileExists( const char *file )
{
char *testpath;
testpath = FS_BuildOSPath( fs_homepath->string, file, "");
testpath[strlen(testpath)-1] = '\0';
return FS_FileInPathExists(testpath);
}
/*
===========
FS_SV_FOpenFileWrite
===========
*/
fileHandle_t FS_SV_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
FS_AssertInitialised();
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileWrite: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = fopen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_SV_FOpenFileRead
search for a file somewhere below the home path, base path or cd path
we search in that order, matching FS_SV_FOpenFileRead order
===========
*/
int FS_SV_FOpenFileRead( const char *filename, fileHandle_t *fp ) {
char *ospath;
fileHandle_t f = 0;
FS_AssertInitialised();
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
S_ClearSoundBuffer();
// search homepath
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
// remove trailing slash
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o)
{
// NOTE TTimo on non *nix systems, fs_homepath == fs_basepath, might want to avoid
if (Q_stricmp(fs_homepath->string,fs_basepath->string))
{
// search basepath
ospath = FS_BuildOSPath( fs_basepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
if ( !fsh[f].handleFiles.file.o )
{
f = 0;
}
}
if (!fsh[f].handleFiles.file.o)
{
// search cd path
ospath = FS_BuildOSPath( fs_cdpath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if (fs_debug->integer)
{
Com_Printf( "FS_SV_FOpenFileRead (fs_cdpath) : %s\n", ospath );
}
fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
fsh[f].handleSync = qfalse;
if ( !fsh[f].handleFiles.file.o )
{
f = 0;
}
}
*fp = f;
if (f) {
return FS_filelength(f);
}
return 0;
}
/*
===========
FS_SV_Rename
===========
*/
void FS_SV_Rename( const char *from, const char *to, qboolean safe ) {
char *from_ospath, *to_ospath;
FS_AssertInitialised();
// don't let sound stutter
S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, from, "" );
to_ospath = FS_BuildOSPath( fs_homepath->string, to, "" );
from_ospath[strlen(from_ospath)-1] = '\0';
to_ospath[strlen(to_ospath)-1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath );
}
if ( safe ) {
FS_CheckFilenameIsMutable( to_ospath, __func__ );
}
if (rename( from_ospath, to_ospath )) {
// Failed, try copying it and deleting the original
FS_CopyFile ( from_ospath, to_ospath );
FS_Remove ( from_ospath );
}
}
/*
===========
FS_Rename
===========
*/
void FS_Rename( const char *from, const char *to ) {
char *from_ospath, *to_ospath;
FS_AssertInitialised();
// don't let sound stutter
S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from );
to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to );
if ( fs_debug->integer ) {
Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath );
}
FS_CheckFilenameIsMutable( to_ospath, __func__ );
if (rename( from_ospath, to_ospath )) {
// Failed, try copying it and deleting the original
FS_CopyFile ( from_ospath, to_ospath );
FS_Remove ( from_ospath );
}
}
/*
===========
FS_FCloseFile
Close a file.
There are three cases handled:
* normal file: closed with fclose.
* file in pak3 archive: subfile is closed with unzCloseCurrentFile, but the
minizip handle to the pak3 remains open.
* file in pak3 archive, opened with "unique" flag: This file did not use
the system minizip handle to the pak3 file, but its own dedicated one.
The dedicated handle is closed with unzClose.
===========
*/
void FS_FCloseFile( fileHandle_t f ) {
FS_AssertInitialised();
if (fsh[f].zipFile == qtrue) {
unzCloseCurrentFile( fsh[f].handleFiles.file.z );
if ( fsh[f].handleFiles.unique ) {
unzClose( fsh[f].handleFiles.file.z );
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
return;
}
// we didn't find it as a pak, so close it as a unique file
if (fsh[f].handleFiles.file.o) {
fclose (fsh[f].handleFiles.file.o);
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
}
/*
===========
FS_FOpenFileWrite
===========
*/
fileHandle_t FS_FOpenFileWrite( const char *filename, qboolean safe ) {
char *ospath;
fileHandle_t f;
FS_AssertInitialised();
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileWrite: %s\n", ospath );
}
if ( safe ) {
FS_CheckFilenameIsMutable( ospath, __func__ );
}
if( FS_CreatePath( ospath ) ) {
return 0;
}
// enabling the following line causes a recursive function call loop
// when running with +set logfile 1 +set developer 1
//Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = fopen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_FOpenFileAppend
===========
*/
fileHandle_t FS_FOpenFileAppend( const char *filename ) {
char *ospath;
fileHandle_t f;
FS_AssertInitialised();
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileAppend: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
fsh[f].handleFiles.file.o = fopen( ospath, "ab" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_FilenameCompare
Ignore case and separator char distinctions
===========
*/
qboolean FS_FilenameCompare( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if (c1 >= 'a' && c1 <= 'z') {
c1 -= ('a' - 'A');
}
if (c2 >= 'a' && c2 <= 'z') {
c2 -= ('a' - 'A');
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if (c1 != c2) {
return qtrue; // strings not equal
}
} while (c1);
return qfalse; // strings are equal
}
/*
===========
FS_IsExt
Return qtrue if ext matches file extension filename
===========
*/
qboolean FS_IsExt(const char *filename, const char *ext, int namelen)
{
int extlen;
extlen = strlen(ext);
if(extlen > namelen)
return qfalse;
filename += namelen - extlen;
return (qboolean)!Q_stricmp(filename, ext);
}
/*
===========
FS_IsDemoExt
Return qtrue if filename has a demo extension
===========
*/
#define DEMO_EXTENSION "dm_"
qboolean FS_IsDemoExt(const char *filename, int namelen)
{
const char *ext_test;
ext_test = strrchr(filename, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMO_EXTENSION, ARRAY_LEN(DEMO_EXTENSION) - 1))
{
int protocol = atoi(ext_test + ARRAY_LEN(DEMO_EXTENSION));
if(protocol == PROTOCOL_VERSION)
return qtrue;
}
return qfalse;
}
#ifdef _WIN32
bool Sys_GetFileTime(LPCSTR psFileName, FILETIME &ft)
{
bool bSuccess = false;
HANDLE hFile = INVALID_HANDLE_VALUE;
hFile = CreateFile( psFileName, // LPCTSTR lpFileName, // pointer to name of the file
GENERIC_READ, // DWORD dwDesiredAccess, // access (read-write) mode
FILE_SHARE_READ, // DWORD dwShareMode, // share mode
NULL, // LPSECURITY_ATTRIBUTES lpSecurityAttributes, // pointer to security attributes
OPEN_EXISTING, // DWORD dwCreationDisposition, // how to create
FILE_FLAG_NO_BUFFERING,// DWORD dwFlagsAndAttributes, // file attributes
NULL // HANDLE hTemplateFile // handle to file with attributes to
);
if (hFile != INVALID_HANDLE_VALUE)
{
if (GetFileTime(hFile, // handle to file
NULL, // LPFILETIME lpCreationTime
NULL, // LPFILETIME lpLastAccessTime
&ft // LPFILETIME lpLastWriteTime
)
)
{
bSuccess = true;
}
CloseHandle(hFile);
}
return bSuccess;
}
bool Sys_FileOutOfDate( LPCSTR psFinalFileName /* dest */, LPCSTR psDataFileName /* src */ )
{
FILETIME ftFinalFile, ftDataFile;
if (Sys_GetFileTime(psFinalFileName, ftFinalFile) && Sys_GetFileTime(psDataFileName, ftDataFile))
{
// timer res only accurate to within 2 seconds on FAT, so can't do exact compare...
//
//LONG l = CompareFileTime( &ftFinalFile, &ftDataFile );
if ( (abs((double)(ftFinalFile.dwLowDateTime - ftDataFile.dwLowDateTime)) <= 20000000 ) &&
ftFinalFile.dwHighDateTime == ftDataFile.dwHighDateTime
)
{
return false; // file not out of date, ie use it.
}
return true; // flag return code to copy over a replacement version of this file
}
// extra error check, report as suspicious if you find a file locally but not out on the net.,.
//
if (com_developer->integer)
{
if (!Sys_GetFileTime(psDataFileName, ftDataFile))
{
Com_Printf( "Sys_FileOutOfDate: reading %s but it's not on the net!\n", psFinalFileName);
}
}
return false;
}
#endif // _WIN32
bool FS_FileCacheable(const char* const filename)
{
extern cvar_t *com_buildScript;
if (com_buildScript && com_buildScript->integer)
{
return true;
}
return( strchr(filename, '/') != 0 );
}
/*
===========
FS_FOpenFileRead
Finds the file in the search path.
Returns filesize and an open FILE pointer.
Used for streaming data out of either a
separate file or a ZIP file.
===========
*/
extern qboolean com_fullyInitialized;
long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean uniqueFILE ) {
searchpath_t *search;
char *netpath;
pack_t *pak;
fileInPack_t *pakFile;
directory_t *dir;
long hash;
//unz_s *zfi;
//void *temp;
bool isUserConfig = false;
hash = 0;
FS_AssertInitialised();
if ( file == NULL ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'file' parameter passed\n" );
}
if ( !filename ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" );
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
*file = 0;
return -1;
}
// make sure the q3key file is only readable by the quake3.exe at initialization
// any other time the key should only be accessed in memory using the provided functions
if( com_fullyInitialized && strstr( filename, "q3key" ) ) {
*file = 0;
return -1;
}
isUserConfig = !Q_stricmp( filename, "autoexec_sp.cfg" ) || !Q_stricmp( filename, Q3CONFIG_NAME );
//
// search through the path, one element at a time
//
*file = FS_HandleForFile();
fsh[*file].handleFiles.unique = uniqueFILE;
// this new bool is in for an optimisation, if you (eg) opened a BSP file under fs_copyfiles==2,
// then it triggered a copy operation to update your local HD version, then this will re-open the
// file handle on your local version, not the net build. This uses a bit more CPU to re-do the loop
// logic, but should read faster than accessing the net version a second time.
//
qboolean bFasterToReOpenUsingNewLocalFile = qfalse;
do
{
bFasterToReOpenUsingNewLocalFile = qfalse;
for ( search = fs_searchpaths ; search ; search = search->next ) {
//
if ( search->pack ) {
hash = FS_HashFileName(filename, search->pack->hashSize);
}
// is the element a pak file?
if ( search->pack && search->pack->hashTable[hash] ) {
// autoexec_sp.cfg and openjk_sp.cfg can only be loaded outside of pk3 files.
if ( isUserConfig ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
// found it!
if ( uniqueFILE ) {
// open a new file on the pakfile
fsh[*file].handleFiles.file.z = unzOpen (pak->pakFilename);
if (fsh[*file].handleFiles.file.z == NULL) {
Com_Error (ERR_FATAL, "Couldn't open %s", pak->pakFilename);
}
} else {
fsh[*file].handleFiles.file.z = pak->handle;
}
Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) );
fsh[*file].zipFile = qtrue;
// set the file position in the zip file (also sets the current file info)
unzSetOffset(fsh[*file].handleFiles.file.z, pakFile->pos);
// open the file in the zip
unzOpenCurrentFile(fsh[*file].handleFiles.file.z);
#if 0
zfi = (unz_s *)fsh[*file].handleFiles.file.z;
// in case the file was new
temp = zfi->filestream;
// set the file position in the zip file (also sets the current file info)
unzSetOffset(pak->handle, pakFile->pos);
// copy the file info into the unzip structure
Com_Memcpy( zfi, pak->handle, sizeof(unz_s) );
// we copy this back into the structure
zfi->filestream = temp;
// open the file in the zip
unzOpenCurrentFile( fsh[*file].handleFiles.file.z );
#endif
fsh[*file].zipFilePos = pakFile->pos;
fsh[*file].zipFileLen = pakFile->len;
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileRead: %s (found in '%s')\n",
filename, pak->pakFilename );
}
return pakFile->len;
}
pakFile = pakFile->next;
} while(pakFile != NULL);
} else if ( search->dir ) {
// check a file in the directory tree
dir = search->dir;
netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename );
fsh[*file].handleFiles.file.o = fopen (netpath, "rb");
if ( !fsh[*file].handleFiles.file.o ) {
continue;
}
#ifdef _WIN32
// if running with fs_copyfiles 2, and search path == local, then we need to fail to open
// if the time/date stamp != the network version (so it'll loop round again and use the network path,
// which comes later in the search order)
//
if ( fs_copyfiles->integer == 2 && fs_cdpath->string[0] && !Q_stricmp( dir->path, fs_basepath->string )
&& FS_FileCacheable(filename) )
{
if ( Sys_FileOutOfDate( netpath, FS_BuildOSPath( fs_cdpath->string, dir->gamedir, filename ) ))
{
fclose(fsh[*file].handleFiles.file.o);
fsh[*file].handleFiles.file.o = 0;
continue; //carry on to find the cdpath version.
}
}
#endif
Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) );
fsh[*file].zipFile = qfalse;
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename,
dir->path, PATH_SEP, dir->gamedir );
}
#ifdef _WIN32
// if we are getting it from the cdpath, optionally copy it
// to the basepath
if ( fs_copyfiles->integer && !Q_stricmp( dir->path, fs_cdpath->string ) ) {
char *copypath;
copypath = FS_BuildOSPath( fs_basepath->string, dir->gamedir, filename );
switch ( fs_copyfiles->integer )
{
default:
case 1:
{
FS_CopyFile( netpath, copypath );
}
break;
case 2:
{
if (FS_FileCacheable(filename) )
{
// maybe change this to Com_DPrintf? On the other hand...
//
Com_Printf( "fs_copyfiles(2), Copying: %s to %s\n", netpath, copypath );
FS_CreatePath( copypath );
bool bOk = true;
if (!CopyFile( netpath, copypath, FALSE ))
{
DWORD dwAttrs = GetFileAttributes(copypath);
SetFileAttributes(copypath, dwAttrs & ~FILE_ATTRIBUTE_READONLY);
bOk = !!CopyFile( netpath, copypath, FALSE );
}
if (bOk)
{
// clear this handle and setup for re-opening of the new local copy...
//
bFasterToReOpenUsingNewLocalFile = qtrue;
fclose(fsh[*file].handleFiles.file.o);
fsh[*file].handleFiles.file.o = NULL;
}
}
}
break;
}
}
#endif
if (bFasterToReOpenUsingNewLocalFile)
{
break; // and re-read the local copy, not the net version
}
return FS_fplength(fsh[*file].handleFiles.file.o);
}
}
}
while ( bFasterToReOpenUsingNewLocalFile );
Com_DPrintf ("Can't find %s\n", filename);
*file = 0;
return -1;
}
/*
=================
FS_Read
Properly handles partial reads
=================
*/
int FS_Read( void *buffer, int len, fileHandle_t f ) {
int block, remaining;
int read;
byte *buf;
int tries;
FS_AssertInitialised();
if ( !f ) {
return 0;
}
buf = (byte *)buffer;
fs_readCount += len;
if (fsh[f].zipFile == qfalse) {
remaining = len;
tries = 0;
while (remaining) {
block = remaining;
read = fread (buf, 1, block, fsh[f].handleFiles.file.o);
if (read == 0) {
// we might have been trying to read from a CD, which
// sometimes returns a 0 read on windows
if (!tries) {
tries = 1;
} else {
return len-remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read");
}
}
if (read == -1) {
Com_Error (ERR_FATAL, "FS_Read: -1 bytes read");
}
remaining -= read;
buf += read;
}
return len;
} else {
return unzReadCurrentFile(fsh[f].handleFiles.file.z, buffer, len);
}
}
/*
=================
FS_Write
Properly handles partial writes
=================
*/
int FS_Write( const void *buffer, int len, fileHandle_t h ) {
int block, remaining;
int written;
byte *buf;
int tries;
FILE *f;
FS_AssertInitialised();
if ( !h ) {
return 0;
}
f = FS_FileForHandle(h);
buf = (byte *)buffer;
remaining = len;
tries = 0;
while (remaining) {
block = remaining;
written = fwrite (buf, 1, block, f);
if (written == 0) {
if (!tries) {
tries = 1;
} else {
Com_Printf( "FS_Write: 0 bytes written\n" );
return 0;
}
}
if (written == -1) {
Com_Printf( "FS_Write: -1 bytes written\n" );
return 0;
}
remaining -= written;
buf += written;
}
if ( fsh[h].handleSync ) {
fflush( f );
}
return len;
}
#define MAXPRINTMSG 4096
void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start (argptr,fmt);
Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
va_end (argptr);
FS_Write(msg, strlen(msg), h);
}
#define PK3_SEEK_BUFFER_SIZE 65536
/*
=================
FS_Seek
=================
*/
int FS_Seek( fileHandle_t f, long offset, int origin ) {
int _origin;
FS_AssertInitialised();
if (fsh[f].zipFile == qtrue) {
//FIXME: this is really, really crappy
//(but better than what was here before)
byte buffer[PK3_SEEK_BUFFER_SIZE];
int remainder;
int currentPosition = FS_FTell( f );
// change negative offsets into FS_SEEK_SET
if ( offset < 0 ) {
switch( origin ) {
case FS_SEEK_END:
remainder = fsh[f].zipFileLen + offset;
break;
case FS_SEEK_CUR:
remainder = currentPosition + offset;
break;
case FS_SEEK_SET:
default:
remainder = 0;
break;
}
if ( remainder < 0 ) {
remainder = 0;
}
origin = FS_SEEK_SET;
} else {
if ( origin == FS_SEEK_END ) {
remainder = fsh[f].zipFileLen - currentPosition + offset;
} else {
remainder = offset;
}
}
switch( origin ) {
case FS_SEEK_SET:
if ( remainder == currentPosition ) {
return offset;
}
unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
unzOpenCurrentFile(fsh[f].handleFiles.file.z);
//fallthrough
case FS_SEEK_END:
case FS_SEEK_CUR:
while( remainder > PK3_SEEK_BUFFER_SIZE ) {
FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f );
remainder -= PK3_SEEK_BUFFER_SIZE;
}
FS_Read( buffer, remainder, f );
return offset;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
return -1;
}
} else {
FILE *file;
file = FS_FileForHandle(f);
switch( origin ) {
case FS_SEEK_CUR:
_origin = SEEK_CUR;
break;
case FS_SEEK_END:
_origin = SEEK_END;
break;
case FS_SEEK_SET:
_origin = SEEK_SET;
break;
default:
_origin = SEEK_CUR;
Com_Error( ERR_FATAL, "Bad origin in FS_Seek\n" );
break;
}
return fseek( file, offset, _origin );
}
}
/*
======================================================================================
CONVENIENCE FUNCTIONS FOR ENTIRE FILES
======================================================================================
*/
int FS_FileIsInPAK(const char *filename ) {
searchpath_t *search;
pack_t *pak;
fileInPack_t *pakFile;
long hash = 0;
FS_AssertInitialised();
if ( !filename ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" );
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
return -1;
}
//
// search through the path, one element at a time
//
for ( search = fs_searchpaths ; search ; search = search->next ) {
//
if (search->pack) {
hash = FS_HashFileName(filename, search->pack->hashSize);
}
// is the element a pak file?
if ( search->pack && search->pack->hashTable[hash] ) {
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
return 1;
}
pakFile = pakFile->next;
} while(pakFile != NULL);
}
}
return -1;
}
/*
============
FS_ReadFile
Filename are relative to the quake search path
a null buffer will just return the file length without loading
============
*/
long FS_ReadFile( const char *qpath, void **buffer ) {
fileHandle_t h;
byte* buf;
long len;
FS_AssertInitialised();
if ( !qpath || !qpath[0] ) {
Com_Error( ERR_FATAL, "FS_ReadFile with empty name\n" );
}
// stop sounds from repeating
S_ClearSoundBuffer();
buf = NULL; // quiet compiler warning
// look for it in the filesystem or pack files
len = FS_FOpenFileRead( qpath, &h, qfalse );
if ( h == 0 ) {
if ( buffer ) {
*buffer = NULL;
}
return -1;
}
if ( !buffer ) {
FS_FCloseFile( h);
return len;
}
fs_loadCount++;
buf = (byte*)Z_Malloc( len+1, TAG_FILESYS, qfalse);
buf[len]='\0'; // because we're not calling Z_Malloc with optional trailing 'bZeroIt' bool
*buffer = buf;
Z_Label(buf, qpath);
// PRECACE CHECKER!
#ifndef FINAL_BUILD
if (com_sv_running && com_sv_running->integer && cls.state >= CA_ACTIVE) { //com_cl_running
if (strncmp(qpath,"menu/",5) ) {
Com_DPrintf( S_COLOR_MAGENTA"FS_ReadFile: %s NOT PRECACHED!\n", qpath );
}
}
#endif
FS_Read (buf, len, h);
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
FS_FCloseFile( h );
return len;
}
/*
=============
FS_FreeFile
=============
*/
void FS_FreeFile( void *buffer ) {
FS_AssertInitialised();
if ( !buffer ) {
Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" );
}
Z_Free( buffer );
}
/*
============
FS_WriteFile
Filename are reletive to the quake search path
============
*/
void FS_WriteFile( const char *qpath, const void *buffer, int size ) {
fileHandle_t f;
FS_AssertInitialised();
if ( !qpath || !buffer ) {
Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" );
}
f = FS_FOpenFileWrite( qpath );
if ( !f ) {
Com_Printf( "Failed to open %s\n", qpath );
return;
}
FS_Write( buffer, size, f );
FS_FCloseFile( f );
}
/*
==========================================================================
ZIP FILE LOADING
==========================================================================
*/
/*
=================
FS_LoadZipFile
Creates a new pak_t in the search chain for the contents
of a zip file.
=================
*/
static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename )
{
fileInPack_t *buildBuffer;
pack_t *pack;
unzFile uf;
int err;
unz_global_info gi;
char filename_inzip[MAX_ZPATH];
unz_file_info file_info;
int len;
size_t i;
long hash;
int fs_numHeaderLongs;
int *fs_headerLongs;
char *namePtr;
fs_numHeaderLongs = 0;
uf = unzOpen(zipfile);
err = unzGetGlobalInfo (uf,&gi);
if (err != UNZ_OK)
return NULL;
len = 0;
unzGoToFirstFile(uf);
for (i = 0; i < gi.number_entry; i++)
{
err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
if (err != UNZ_OK) {
break;
}
len += strlen(filename_inzip) + 1;
unzGoToNextFile(uf);
}
buildBuffer = (struct fileInPack_s *)Z_Malloc( (gi.number_entry * sizeof( fileInPack_t )) + len, TAG_FILESYS, qtrue );
namePtr = ((char *) buildBuffer) + gi.number_entry * sizeof( fileInPack_t );
fs_headerLongs = (int *)Z_Malloc( gi.number_entry * sizeof(int), TAG_FILESYS, qtrue );
// get the hash table size from the number of files in the zip
// because lots of custom pk3 files have less than 32 or 64 files
for (i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1) {
if (i > gi.number_entry) {
break;
}
}
pack = (pack_t *)Z_Malloc( sizeof( pack_t ) + i * sizeof(fileInPack_t *), TAG_FILESYS, qtrue );
pack->hashSize = i;
pack->hashTable = (fileInPack_t **) (((char *) pack) + sizeof( pack_t ));
for(int j = 0; j < pack->hashSize; j++) {
pack->hashTable[j] = NULL;
}
Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) );
Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) );
// strip .pk3 if needed
if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) {
pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0;
}
pack->handle = uf;
pack->numfiles = gi.number_entry;
unzGoToFirstFile(uf);
for (i = 0; i < gi.number_entry; i++)
{
err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
if (err != UNZ_OK) {
break;
}
if (file_info.uncompressed_size > 0) {
fs_headerLongs[fs_numHeaderLongs++] = LittleLong(file_info.crc);
}
Q_strlwr( filename_inzip );
hash = FS_HashFileName(filename_inzip, pack->hashSize);
buildBuffer[i].name = namePtr;
strcpy( buildBuffer[i].name, filename_inzip );
namePtr += strlen(filename_inzip) + 1;
// store the file position in the zip
buildBuffer[i].pos = unzGetOffset(uf);
buildBuffer[i].len = file_info.uncompressed_size;
buildBuffer[i].next = pack->hashTable[hash];
pack->hashTable[hash] = &buildBuffer[i];
unzGoToNextFile(uf);
}
pack->checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs );
pack->checksum = LittleLong( pack->checksum );
Z_Free(fs_headerLongs);
pack->buildBuffer = buildBuffer;
return pack;
}
/*
=================
FS_FreePak
Frees a pak structure and releases all associated resources
=================
*/
void FS_FreePak(pack_t *thepak)
{
unzClose(thepak->handle);
Z_Free(thepak->buildBuffer);
Z_Free(thepak);
}
/*
=================================================================================
DIRECTORY SCANNING FUNCTIONS
=================================================================================
*/
#define MAX_FOUND_FILES 0x1000
static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) {
int len, at, newdep;
newdep = 0;
zpath[0] = 0;
len = 0;
at = 0;
while(zname[at] != 0)
{
if (zname[at]=='/' || zname[at]=='\\') {
len = at;
newdep++;
}
at++;
}
strcpy(zpath, zname);
zpath[len] = 0;
*depth = newdep;
return len;
}
/*
==================
FS_AddFileToList
==================
*/
static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) {
int i;
if ( nfiles == MAX_FOUND_FILES - 1 ) {
return nfiles;
}
for ( i = 0 ; i < nfiles ; i++ ) {
if ( !Q_stricmp( name, list[i] ) ) {
return nfiles; // allready in list
}
}
list[nfiles] = CopyString( name );
nfiles++;
return nfiles;
}
/*
===============
FS_ListFilteredFiles
Returns a uniqued list of files that match the given criteria
from all search paths
===============
*/
char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles ) {
int nfiles;
char **listCopy;
char *list[MAX_FOUND_FILES];
searchpath_t *search;
int i;
int pathLength;
int extensionLength;
int length, pathDepth, temp;
pack_t *pak;
fileInPack_t *buildBuffer;
char zpath[MAX_ZPATH];
FS_AssertInitialised();
if ( !path ) {
*numfiles = 0;
return NULL;
}
if ( !extension ) {
extension = "";
}
pathLength = strlen( path );
if ( path[pathLength-1] == '\\' || path[pathLength-1] == '/' ) {
pathLength--;
}
extensionLength = strlen( extension );
nfiles = 0;
FS_ReturnPath(path, zpath, &pathDepth);
//
// search through the path, one element at a time, adding to list
//
for (search = fs_searchpaths ; search ; search = search->next) {
// is the element a pak file?
if (search->pack) {
// look through all the pak file elements
pak = search->pack;
buildBuffer = pak->buildBuffer;
for (i = 0; i < pak->numfiles; i++) {
char *name;
int zpathLen, depth;
// check for directory match
name = buildBuffer[i].name;
//
if (filter) {
// case insensitive
if (!Com_FilterPath( filter, name, qfalse ))
continue;
// unique the match
nfiles = FS_AddFileToList( name, list, nfiles );
}
else {
zpathLen = FS_ReturnPath(name, zpath, &depth);
if ( (depth-pathDepth)>2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) {
continue;
}
// check for extension match
length = strlen( name );
if ( length < extensionLength ) {
continue;
}
if ( Q_stricmp( name + length - extensionLength, extension ) ) {
continue;
}
// unique the match
temp = pathLength;
if (pathLength) {
temp++; // include the '/'
}
nfiles = FS_AddFileToList( name + temp, list, nfiles );
}
}
} else if (search->dir) { // scan for files in the filesystem
char *netpath;
int numSysFiles;
char **sysFiles;
char *name;
netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path );
sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse );
for ( i = 0 ; i < numSysFiles ; i++ ) {
// unique the match
name = sysFiles[i];
nfiles = FS_AddFileToList( name, list, nfiles );
}
Sys_FreeFileList( sysFiles );
}
}
// return a copy of the list
*numfiles = nfiles;
if ( !nfiles ) {
return NULL;
}
listCopy = (char **)Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ), TAG_FILESYS, qfalse );
for ( i = 0 ; i < nfiles ; i++ ) {
listCopy[i] = list[i];
}
listCopy[i] = NULL;
return listCopy;
}
/*
=================
FS_ListFiles
=================
*/
char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) {
return FS_ListFilteredFiles( path, extension, NULL, numfiles );
}
/*
=================
FS_FreeFileList
=================
*/
void FS_FreeFileList( char **fileList ) {
//rwwRMG - changed to fileList to not conflict with list type
int i;
FS_AssertInitialised();
if ( !fileList ) {
return;
}
for ( i = 0 ; fileList[i] ; i++ ) {
Z_Free( fileList[i] );
}
Z_Free( fileList );
}
/*
================
FS_GetFileList
================
*/
int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
int nFiles, i, nTotal, nLen;
char **pFiles = NULL;
*listbuf = 0;
nFiles = 0;
nTotal = 0;
if (Q_stricmp(path, "$modlist") == 0) {
return FS_GetModList(listbuf, bufsize);
}
pFiles = FS_ListFiles(path, extension, &nFiles);
for (i =0; i < nFiles; i++) {
nLen = strlen(pFiles[i]) + 1;
if (nTotal + nLen + 1 < bufsize) {
strcpy(listbuf, pFiles[i]);
listbuf += nLen;
nTotal += nLen;
}
else {
nFiles = i;
break;
}
}
FS_FreeFileList(pFiles);
return nFiles;
}
/*
=======================
Sys_ConcatenateFileLists
mkv: Naive implementation. Concatenates three lists into a
new list, and frees the old lists from the heap.
bk001129 - from cvs1.17 (mkv)
FIXME TTimo those two should move to common.c next to Sys_ListFiles
=======================
*/
static unsigned int Sys_CountFileList(char **fileList)
{
int i = 0;
if (fileList)
{
while (*fileList)
{
fileList++;
i++;
}
}
return i;
}
static char** Sys_ConcatenateFileLists( char **list0, char **list1, char **list2 )
{
int totalLength = 0;
char** cat = NULL, **dst, **src;
totalLength += Sys_CountFileList(list0);
totalLength += Sys_CountFileList(list1);
totalLength += Sys_CountFileList(list2);
/* Create new list. */
dst = cat = (char **)Z_Malloc( ( totalLength + 1 ) * sizeof( char* ), TAG_FILESYS, qtrue );
/* Copy over lists. */
if (list0) {
for (src = list0; *src; src++, dst++)
*dst = *src;
}
if (list1) {
for (src = list1; *src; src++, dst++)
*dst = *src;
}
if (list2) {
for (src = list2; *src; src++, dst++)
*dst = *src;
}
// Terminate the list
*dst = NULL;
// Free our old lists.
// NOTE: not freeing their content, it's been merged in dst and still being used
if (list0) Z_Free( list0 );
if (list1) Z_Free( list1 );
if (list2) Z_Free( list2 );
return cat;
}
//#endif
// For base game mod listing
const char *SE_GetString( const char *psPackageAndStringReference );
/*
================
FS_GetModList
Returns a list of mod directory names
A mod directory is a peer to base with a pk3 in it
The directories are searched in base path, cd path and home path
================
*/
int FS_GetModList( char *listbuf, int bufsize ) {
int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen;
char **pFiles = NULL;
char **pPaks = NULL;
char *name, *path;
char descPath[MAX_OSPATH];
fileHandle_t descHandle;
int dummy;
char **pFiles0 = NULL;
char **pFiles1 = NULL;
char **pFiles2 = NULL;
qboolean bDrop = qfalse;
*listbuf = 0;
nMods = nPotential = nTotal = 0;
pFiles0 = Sys_ListFiles( fs_homepath->string, NULL, NULL, &dummy, qtrue );
pFiles1 = Sys_ListFiles( fs_basepath->string, NULL, NULL, &dummy, qtrue );
pFiles2 = Sys_ListFiles( fs_cdpath->string, NULL, NULL, &dummy, qtrue );
// we searched for mods in the three paths
// it is likely that we have duplicate names now, which we will cleanup below
pFiles = Sys_ConcatenateFileLists( pFiles0, pFiles1, pFiles2 );
nPotential = Sys_CountFileList(pFiles);
for ( i = 0 ; i < nPotential ; i++ ) {
name = pFiles[i];
// NOTE: cleaner would involve more changes
// ignore duplicate mod directories
if (i!=0) {
bDrop = qfalse;
for(j=0; j<i; j++)
{
if (Q_stricmp(pFiles[j],name)==0) {
// this one can be dropped
bDrop = qtrue;
break;
}
}
}
if (bDrop) {
continue;
}
// we drop "." and ".."
if (Q_stricmpn(name, ".", 1)) {
// now we need to find some .pk3 files to validate the mod
// NOTE TTimo: (actually I'm not sure why .. what if it's a mod under developement with no .pk3?)
// we didn't keep the information when we merged the directory names, as to what OS Path it was found under
// so it could be in base path, cd path or home path
// we will try each three of them here (yes, it's a bit messy)
path = FS_BuildOSPath( fs_basepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse);
Sys_FreeFileList( pPaks ); // we only use Sys_ListFiles to check wether .pk3 files are present
/* Try on cd path */
if( nPaks <= 0 ) {
path = FS_BuildOSPath( fs_cdpath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
/* try on home path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_homepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
if (nPaks > 0) {
bool isBase = !Q_stricmp( name, BASEGAME );
nLen = isBase ? 1 : strlen(name) + 1;
// nLen is the length of the mod path
// we need to see if there is a description available
descPath[0] = '\0';
strcpy(descPath, name);
strcat(descPath, "/description.txt");
nDescLen = FS_SV_FOpenFileRead( descPath, &descHandle );
if ( nDescLen > 0 && descHandle) {
FILE *file;
file = FS_FileForHandle(descHandle);
Com_Memset( descPath, 0, sizeof( descPath ) );
nDescLen = fread(descPath, 1, 48, file);
if (nDescLen >= 0) {
descPath[nDescLen] = '\0';
}
FS_FCloseFile(descHandle);
} else if ( isBase ) {
strcpy(descPath, SE_GetString("MENUS_JEDI_ACADEMY"));
} else {
strcpy(descPath, name);
}
nDescLen = strlen(descPath) + 1;
if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) {
if ( isBase )
strcpy(listbuf, "");
else
strcpy(listbuf, name);
listbuf += nLen;
strcpy(listbuf, descPath);
listbuf += nDescLen;
nTotal += nLen + nDescLen;
nMods++;
}
else {
break;
}
}
}
}
Sys_FreeFileList( pFiles );
return nMods;
}
//============================================================================
/*
================
FS_Dir_f
================
*/
void FS_Dir_f( void ) {
char *path;
char *extension;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) {
Com_Printf( "usage: dir <directory> [extension]\n" );
return;
}
if ( Cmd_Argc() == 2 ) {
path = Cmd_Argv( 1 );
extension = "";
} else {
path = Cmd_Argv( 1 );
extension = Cmd_Argv( 2 );
}
Com_Printf( "Directory of %s %s\n", path, extension );
Com_Printf( "---------------\n" );
dirnames = FS_ListFiles( path, extension, &ndirs );
for ( i = 0; i < ndirs; i++ ) {
Com_Printf( "%s\n", dirnames[i] );
}
FS_FreeFileList( dirnames );
}
/*
===========
FS_ConvertPath
===========
*/
void FS_ConvertPath( char *s ) {
while (*s) {
if ( *s == '\\' || *s == ':' ) {
*s = '/';
}
s++;
}
}
/*
===========
FS_PathCmp
Ignore case and separator char distinctions
===========
*/
int FS_PathCmp( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if (c1 >= 'a' && c1 <= 'z') {
c1 -= ('a' - 'A');
}
if (c2 >= 'a' && c2 <= 'z') {
c2 -= ('a' - 'A');
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if (c1 < c2) {
return -1; // strings not equal
}
if (c1 > c2) {
return 1;
}
} while (c1);
return 0; // strings are equal
}
/*
================
FS_SortFileList
================
*/
void FS_SortFileList(char **filelist, int numfiles) {
int i, j, k, numsortedfiles;
char **sortedlist;
sortedlist = (char **)Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ), TAG_FILESYS, qtrue );
sortedlist[0] = NULL;
numsortedfiles = 0;
for (i = 0; i < numfiles; i++) {
for (j = 0; j < numsortedfiles; j++) {
if (FS_PathCmp(filelist[i], sortedlist[j]) < 0) {
break;
}
}
for (k = numsortedfiles; k > j; k--) {
sortedlist[k] = sortedlist[k-1];
}
sortedlist[j] = filelist[i];
numsortedfiles++;
}
Com_Memcpy(filelist, sortedlist, numfiles * sizeof( *filelist ) );
Z_Free(sortedlist);
}
/*
================
FS_NewDir_f
================
*/
void FS_NewDir_f( void ) {
char *filter;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 ) {
Com_Printf( "usage: fdir <filter>\n" );
Com_Printf( "example: fdir *t1*.bsp\n");
return;
}
filter = Cmd_Argv( 1 );
Com_Printf( "---------------\n" );
dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs );
FS_SortFileList(dirnames, ndirs);
for ( i = 0; i < ndirs; i++ ) {
FS_ConvertPath(dirnames[i]);
Com_Printf( "%s\n", dirnames[i] );
}
Com_Printf( "%d files listed\n", ndirs );
FS_FreeFileList( dirnames );
}
/*
============
FS_Path_f
============
*/
void FS_Path_f( void ) {
searchpath_t *s;
int i;
Com_Printf ("Current search path:\n");
for (s = fs_searchpaths; s; s = s->next) {
if (s->pack) {
Com_Printf ("%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles);
} else {
Com_Printf ("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir );
}
}
Com_Printf( "\n" );
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o ) {
Com_Printf( "handle %i: %s\n", i, fsh[i].name );
}
}
}
/*
============
FS_TouchFile_f
The only purpose of this function is to allow game script files to copy
arbitrary files furing an "fs_copyfiles 1" run.
============
*/
void FS_TouchFile_f( void ) {
fileHandle_t f;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: touchFile <file>\n" );
return;
}
FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse );
if ( f ) {
FS_FCloseFile( f );
}
}
/*
============
FS_Which_f
============
*/
void FS_Which_f( void ) {
searchpath_t *search;
char *filename;
filename = Cmd_Argv(1);
if ( !filename[0] ) {
Com_Printf( "Usage: which <file>\n" );
return;
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
return;
}
// just wants to see if file is there
for ( search=fs_searchpaths; search; search=search->next ) {
if ( search->pack ) {
long hash = FS_HashFileName( filename, search->pack->hashSize );
// is the element a pak file?
if ( search->pack->hashTable[hash]) {
// look through all the pak file elements
pack_t* pak = search->pack;
fileInPack_t* pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
// found it!
Com_Printf( "File \"%s\" found in \"%s\"\n", filename, pak->pakFilename );
return;
}
pakFile = pakFile->next;
} while ( pakFile != NULL );
}
} else if (search->dir) {
directory_t* dir = search->dir;
char* netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename );
FILE* filep = fopen(netpath, "rb");
if ( filep ) {
fclose( filep );
char buf[MAX_OSPATH];
Com_sprintf( buf, sizeof( buf ), "%s%c%s", dir->path, PATH_SEP, dir->gamedir );
FS_ReplaceSeparators( buf );
Com_Printf( "File \"%s\" found at \"%s\"\n", filename, buf );
return;
}
}
}
Com_Printf( "File not found: \"%s\"\n", filename );
}
//===========================================================================
static int QDECL paksort( const void *a, const void *b ) {
char *aa, *bb;
aa = *(char **)a;
bb = *(char **)b;
return FS_PathCmp( aa, bb );
}
/*
================
FS_AddGameDirectory
Sets fs_gamedir, adds the directory to the head of the path,
then loads the zip headers
================
*/
#define MAX_PAKFILES 1024
static void FS_AddGameDirectory( const char *path, const char *dir ) {
searchpath_t *sp;
int i;
searchpath_t *search;
searchpath_t *thedir;
pack_t *pak;
char curpath[MAX_OSPATH + 1], *pakfile;
int numfiles;
char **pakfiles;
char *sorted[MAX_PAKFILES];
// this fixes the case where fs_basepath is the same as fs_cdpath
// which happens on full installs
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
// TODO Sys_PathCmp SDL-Port will contain this for SP as well
// Should be Sys_PathCmp(sp->dir->path, path)
if ( sp->dir && !Q_stricmp(sp->dir->path, path) && !Q_stricmp(sp->dir->gamedir, dir)) {
return; // we've already got this one
}
}
Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) );
// find all pak files in this directory
Q_strncpyz(curpath, FS_BuildOSPath(path, dir, ""), sizeof(curpath));
curpath[strlen(curpath) - 1] = '\0'; // strip the trailing slash
//
// add the directory to the search path
//
search = (struct searchpath_s *)Z_Malloc (sizeof(searchpath_t), TAG_FILESYS, qtrue);
search->dir = (directory_t *)Z_Malloc( sizeof( *search->dir ), TAG_FILESYS, qtrue );
Q_strncpyz( search->dir->path, path, sizeof( search->dir->path ) );
Q_strncpyz( search->dir->fullpath, curpath, sizeof( search->dir->fullpath ) );
Q_strncpyz( search->dir->gamedir, dir, sizeof( search->dir->gamedir ) );
search->next = fs_searchpaths;
fs_searchpaths = search;
thedir = search;
pakfiles = Sys_ListFiles( curpath, ".pk3", NULL, &numfiles, qfalse );
// sort them so that later alphabetic matches override
// earlier ones. This makes pak1.pk3 override pak0.pk3
if ( numfiles > MAX_PAKFILES ) {
numfiles = MAX_PAKFILES;
}
for ( i = 0 ; i < numfiles ; i++ ) {
sorted[i] = pakfiles[i];
}
qsort( sorted, numfiles, sizeof(char*), paksort );
for ( i = 0 ; i < numfiles ; i++ ) {
pakfile = FS_BuildOSPath( path, dir, sorted[i] );
if ( ( pak = FS_LoadZipFile( pakfile, sorted[i] ) ) == 0 )
continue;
Q_strncpyz(pak->pakPathname, curpath, sizeof(pak->pakPathname));
// store the game name for downloading
Q_strncpyz(pak->pakGamename, dir, sizeof(pak->pakGamename));
fs_packFiles += pak->numfiles;
search = (searchpath_s *)Z_Malloc (sizeof(searchpath_t), TAG_FILESYS, qtrue);
search->pack = pak;
if (fs_dirbeforepak && fs_dirbeforepak->integer && thedir)
{
searchpath_t *oldnext = thedir->next;
thedir->next = search;
while (oldnext)
{
search->next = oldnext;
search = search->next;
oldnext = oldnext->next;
}
}
else
{
search->next = fs_searchpaths;
fs_searchpaths = search;
}
}
// done
Sys_FreeFileList( pakfiles );
}
/*
================
FS_CheckDirTraversal
Check whether the string contains stuff like "../" to prevent directory traversal bugs
and return qtrue if it does.
================
*/
qboolean FS_CheckDirTraversal(const char *checkdir)
{
if(strstr(checkdir, "../") || strstr(checkdir, "..\\"))
return qtrue;
return qfalse;
}
/*
================
FS_Shutdown
Frees all resources and closes all files
================
*/
void FS_Shutdown( void ) {
searchpath_t *p, *next;
int i;
for(i = 0; i < MAX_FILE_HANDLES; i++) {
if (fsh[i].fileSize) {
FS_FCloseFile(i);
}
}
// free everything
for ( p = fs_searchpaths ; p ; p = next ) {
next = p->next;
if ( p->pack ) {
FS_FreePak( p->pack );
}
if ( p->dir ) {
Z_Free( p->dir );
}
Z_Free( p );
}
// any FS_ calls will now be an error until reinitialized
fs_searchpaths = NULL;
Cmd_RemoveCommand( "path" );
Cmd_RemoveCommand( "dir" );
Cmd_RemoveCommand( "fdir" );
Cmd_RemoveCommand( "touchFile" );
Cmd_RemoveCommand( "which" );
}
/*
================
FS_Startup
================
*/
void FS_Startup( const char *gameName ) {
const char *homePath;
Com_Printf( "----- FS_Startup -----\n" );
fs_packFiles = 0;
fs_debug = Cvar_Get( "fs_debug", "0", 0 );
fs_copyfiles = Cvar_Get( "fs_copyfiles", "0", CVAR_INIT );
fs_cdpath = Cvar_Get ("fs_cdpath", "", CVAR_INIT|CVAR_PROTECTED );
fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT|CVAR_PROTECTED );
fs_basegame = Cvar_Get ("fs_basegame", "", CVAR_INIT );
homePath = Sys_DefaultHomePath();
if (!homePath || !homePath[0]) {
homePath = fs_basepath->string;
}
fs_homepath = Cvar_Get ("fs_homepath", homePath, CVAR_INIT|CVAR_PROTECTED );
fs_gamedirvar = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
fs_dirbeforepak = Cvar_Get("fs_dirbeforepak", "0", CVAR_INIT|CVAR_PROTECTED);
// add search path elements in reverse priority order
if (fs_cdpath->string[0]) {
FS_AddGameDirectory( fs_cdpath->string, gameName );
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory( fs_basepath->string, gameName );
}
#ifdef MACOS_X
fs_apppath = Cvar_Get ("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT|CVAR_PROTECTED );
// Make MacOSX also include the base path included with the .app bundle
if (fs_apppath->string[0]) {
FS_AddGameDirectory( fs_apppath->string, gameName );
}
#endif
// fs_homepath is somewhat particular to *nix systems, only add if relevant
// NOTE: same filtering below for mods and basegame
// TODO Sys_PathCmp see previous comment for why
// !Sys_PathCmp(fs_homepath->string, fs_basepath->string)
if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string, fs_basepath->string)) {
FS_CreatePath ( fs_homepath->string );
FS_AddGameDirectory ( fs_homepath->string, gameName );
}
// check for additional base game so mods can be based upon other mods
if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) ) {
if (fs_cdpath->string[0]) {
FS_AddGameDirectory(fs_cdpath->string, fs_basegame->string);
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory(fs_basepath->string, fs_basegame->string);
}
if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string, fs_basepath->string)) {
FS_AddGameDirectory(fs_homepath->string, fs_basegame->string);
}
}
// check for additional game folder for mods
if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) ) {
if (fs_cdpath->string[0]) {
FS_AddGameDirectory(fs_cdpath->string, fs_gamedirvar->string);
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory(fs_basepath->string, fs_gamedirvar->string);
}
if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string, fs_basepath->string)) {
FS_AddGameDirectory(fs_homepath->string, fs_gamedirvar->string);
}
}
// add our commands
Cmd_AddCommand ("path", FS_Path_f);
Cmd_AddCommand ("dir", FS_Dir_f );
Cmd_AddCommand ("fdir", FS_NewDir_f );
Cmd_AddCommand ("touchFile", FS_TouchFile_f );
Cmd_AddCommand ("which", FS_Which_f );
// print the current search paths
FS_Path_f();
fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified
Com_Printf( "----------------------\n" );
Com_Printf( "%d files in pk3 files\n", fs_packFiles );
}
/*
================
FS_InitFilesystem
Called only at inital startup, not when the filesystem
is resetting due to a game change
================
*/
void FS_InitFilesystem( void ) {
// allow command line parms to override our defaults
// we have to specially handle this, because normal command
// line variable sets don't happen until after the filesystem
// has already been initialized
Com_StartupVariable( "fs_cdpath" );
Com_StartupVariable( "fs_basepath" );
Com_StartupVariable( "fs_homepath" );
Com_StartupVariable( "fs_game" );
Com_StartupVariable( "fs_copyfiles" );
Com_StartupVariable( "fs_dirbeforepak" );
#ifdef MACOS_X
Com_StartupVariable( "fs_apppath" );
#endif
const char *gamedir = Cvar_VariableString("fs_game");
bool requestbase = false;
if ( !FS_FilenameCompare( gamedir, BASEGAME ) )
requestbase = true;
if ( requestbase )
Cvar_Set2( "fs_game", "", qtrue );
// try to start up normally
FS_Startup( BASEGAME );
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
// bk001208 - SafeMode see below, FIXME?
}
Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
// bk001208 - SafeMode see below, FIXME?
}
/*
================
FS_Restart
================
*/
void FS_Restart( void ) {
// free anything we currently have loaded
FS_Shutdown();
// try to start up normally
FS_Startup( BASEGAME );
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
// this might happen when connecting to a pure server not using BASEGAME/pak0.pk3
// (for instance a TA demo server)
if (lastValidBase[0]) {
Cvar_Set("fs_basepath", lastValidBase);
Cvar_Set("fs_game", lastValidGame);
lastValidBase[0] = '\0';
lastValidGame[0] = '\0';
FS_Restart();
Com_Error( ERR_DROP, "Invalid game folder" );
return;
}
Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
}
if ( Q_stricmp(fs_gamedirvar->string, lastValidGame) ) {
// skip the jaconfig.cfg if "safe" is on the command line
if ( !Com_SafeMode() ) {
Cbuf_AddText ("exec " Q3CONFIG_NAME "\n");
}
}
Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
}
/*
=================
FS_ConditionalRestart
Restart if necessary
=================
*/
qboolean FS_ConditionalRestart( void ) {
if(fs_gamedirvar->modified) {
FS_Restart();
return qtrue;
}
return qfalse;
}
/*
========================================================================================
Handle based file calls for virtual machines
========================================================================================
*/
int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
int r;
qboolean sync;
sync = qfalse;
switch( mode ) {
case FS_READ:
r = FS_FOpenFileRead( qpath, f, qtrue );
break;
case FS_WRITE:
*f = FS_FOpenFileWrite( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
case FS_APPEND_SYNC:
sync = qtrue;
case FS_APPEND:
*f = FS_FOpenFileAppend( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
default:
Com_Error( ERR_FATAL, "FSH_FOpenFile: bad mode" );
return -1;
}
if (!f) {
return r;
}
if ( *f ) {
fsh[*f].fileSize = r;
}
fsh[*f].handleSync = sync;
return r;
}
int FS_FTell( fileHandle_t f ) {
int pos;
if (fsh[f].zipFile == qtrue) {
pos = unztell(fsh[f].handleFiles.file.z);
} else {
pos = ftell(fsh[f].handleFiles.file.o);
}
return pos;
}
void FS_Flush( fileHandle_t f ) {
fflush(fsh[f].handleFiles.file.o);
}
void FS_FilenameCompletion( const char *dir, const char *ext, qboolean stripExt, callbackFunc_t callback, qboolean allowNonPureFilesOnDisk ) {
int nfiles;
char **filenames, filename[MAX_STRING_CHARS];
filenames = FS_ListFilteredFiles( dir, ext, NULL, &nfiles );
FS_SortFileList( filenames, nfiles );
// pass all the files to callback (FindMatches)
for ( int i=0; i<nfiles; i++ ) {
FS_ConvertPath( filenames[i] );
Q_strncpyz( filename, filenames[i], MAX_STRING_CHARS );
if ( stripExt )
COM_StripExtension( filename, filename, sizeof( filename ) );
callback( filename );
}
FS_FreeFileList( filenames );
}
const char *FS_GetCurrentGameDir(bool emptybase)
{
if(fs_gamedirvar->string[0])
return fs_gamedirvar->string;
return emptybase ? "" : BASEGAME;
}
qboolean FS_WriteToTemporaryFile( const void *data, size_t dataLength, char **tempFilePath )
{
// SP doesn't need to do this.
return qfalse;
}
| ./CrossVul/dataset_final_sorted/CWE-269/cpp/good_3234_1 |
crossvul-cpp_data_bad_3234_2 | /*
===========================================================================
Copyright (C) 1999 - 2005, Id Software, Inc.
Copyright (C) 2000 - 2013, Raven Software, Inc.
Copyright (C) 2001 - 2013, Activision, Inc.
Copyright (C) 2005 - 2015, ioquake3 contributors
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
// cl_main.c -- client main loop
#include "client.h"
#include <limits.h>
#include "ghoul2/G2.h"
#include "qcommon/cm_public.h"
#include "qcommon/MiniHeap.h"
#include "qcommon/stringed_ingame.h"
#include "cl_cgameapi.h"
#include "cl_uiapi.h"
#include "cl_lan.h"
#include "snd_local.h"
#include "sys/sys_loadlib.h"
cvar_t *cl_renderer;
cvar_t *cl_nodelta;
cvar_t *cl_debugMove;
cvar_t *cl_noprint;
cvar_t *cl_motd;
cvar_t *cl_motdServer[MAX_MASTER_SERVERS];
cvar_t *rcon_client_password;
cvar_t *rconAddress;
cvar_t *cl_timeout;
cvar_t *cl_maxpackets;
cvar_t *cl_packetdup;
cvar_t *cl_timeNudge;
cvar_t *cl_showTimeDelta;
cvar_t *cl_freezeDemo;
cvar_t *cl_shownet;
cvar_t *cl_showSend;
cvar_t *cl_timedemo;
cvar_t *cl_aviFrameRate;
cvar_t *cl_aviMotionJpeg;
cvar_t *cl_avi2GBLimit;
cvar_t *cl_forceavidemo;
cvar_t *cl_freelook;
cvar_t *cl_sensitivity;
cvar_t *cl_mouseAccel;
cvar_t *cl_mouseAccelOffset;
cvar_t *cl_mouseAccelStyle;
cvar_t *cl_showMouseRate;
cvar_t *m_pitchVeh;
cvar_t *m_pitch;
cvar_t *m_yaw;
cvar_t *m_forward;
cvar_t *m_side;
cvar_t *m_filter;
cvar_t *cl_activeAction;
cvar_t *cl_motdString;
cvar_t *cl_allowDownload;
cvar_t *cl_allowAltEnter;
cvar_t *cl_conXOffset;
cvar_t *cl_inGameVideo;
cvar_t *cl_serverStatusResendTime;
cvar_t *cl_framerate;
// cvar to enable sending a "ja_guid" player identifier in userinfo to servers
// ja_guid is a persistent "cookie" that allows servers to track players across game sessions
cvar_t *cl_enableGuid;
cvar_t *cl_guidServerUniq;
cvar_t *cl_autolodscale;
cvar_t *cl_consoleKeys;
cvar_t *cl_consoleUseScanCode;
cvar_t *cl_lanForcePackets;
vec3_t cl_windVec;
clientActive_t cl;
clientConnection_t clc;
clientStatic_t cls;
netadr_t rcon_address;
char cl_reconnectArgs[MAX_OSPATH] = {0};
// Structure containing functions exported from refresh DLL
refexport_t *re = NULL;
static void *rendererLib = NULL;
ping_t cl_pinglist[MAX_PINGREQUESTS];
typedef struct serverStatus_s
{
char string[BIG_INFO_STRING];
netadr_t address;
int time, startTime;
qboolean pending;
qboolean print;
qboolean retrieved;
} serverStatus_t;
serverStatus_t cl_serverStatusList[MAX_SERVERSTATUSREQUESTS];
int serverStatusCount;
IHeapAllocator *G2VertSpaceClient = 0;
extern void SV_BotFrame( int time );
void CL_CheckForResend( void );
void CL_ShowIP_f(void);
void CL_ServerStatus_f(void);
void CL_ServerStatusResponse( netadr_t from, msg_t *msg );
static void CL_ShutdownRef( qboolean restarting );
/*
=======================================================================
CLIENT RELIABLE COMMAND COMMUNICATION
=======================================================================
*/
/*
======================
CL_AddReliableCommand
The given command will be transmitted to the server, and is gauranteed to
not have future usercmd_t executed before it is executed
======================
*/
void CL_AddReliableCommand( const char *cmd, qboolean isDisconnectCmd ) {
int unacknowledged = clc.reliableSequence - clc.reliableAcknowledge;
// if we would be losing an old command that hasn't been acknowledged,
// we must drop the connection
// also leave one slot open for the disconnect command in this case.
if ((isDisconnectCmd && unacknowledged > MAX_RELIABLE_COMMANDS) ||
(!isDisconnectCmd && unacknowledged >= MAX_RELIABLE_COMMANDS))
{
if(com_errorEntered)
return;
else
Com_Error(ERR_DROP, "Client command overflow");
}
Q_strncpyz(clc.reliableCommands[++clc.reliableSequence & (MAX_RELIABLE_COMMANDS - 1)],
cmd, sizeof(*clc.reliableCommands));
}
/*
=======================================================================
CLIENT SIDE DEMO RECORDING
=======================================================================
*/
/*
====================
CL_WriteDemoMessage
Dumps the current net message, prefixed by the length
====================
*/
void CL_WriteDemoMessage ( msg_t *msg, int headerBytes ) {
int len, swlen;
// write the packet sequence
len = clc.serverMessageSequence;
swlen = LittleLong( len );
FS_Write (&swlen, 4, clc.demofile);
// skip the packet sequencing information
len = msg->cursize - headerBytes;
swlen = LittleLong(len);
FS_Write (&swlen, 4, clc.demofile);
FS_Write ( msg->data + headerBytes, len, clc.demofile );
}
/*
====================
CL_StopRecording_f
stop recording a demo
====================
*/
void CL_StopRecord_f( void ) {
int len;
if ( !clc.demorecording ) {
Com_Printf ("Not recording a demo.\n");
return;
}
// finish up
len = -1;
FS_Write (&len, 4, clc.demofile);
FS_Write (&len, 4, clc.demofile);
FS_FCloseFile (clc.demofile);
clc.demofile = 0;
clc.demorecording = qfalse;
clc.spDemoRecording = qfalse;
Com_Printf ("Stopped demo.\n");
}
/*
==================
CL_DemoFilename
==================
*/
void CL_DemoFilename( char *buf, int bufSize ) {
time_t rawtime;
char timeStr[32] = {0}; // should really only reach ~19 chars
time( &rawtime );
strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime
Com_sprintf( buf, bufSize, "demo%s", timeStr );
}
/*
====================
CL_Record_f
record <demoname>
Begins recording a demo from the current position
====================
*/
static char demoName[MAX_QPATH]; // compiler bug workaround
void CL_Record_f( void ) {
char name[MAX_OSPATH];
byte bufData[MAX_MSGLEN];
msg_t buf;
int i;
int len;
entityState_t *ent;
entityState_t nullstate;
char *s;
if ( Cmd_Argc() > 2 ) {
Com_Printf ("record <demoname>\n");
return;
}
if ( clc.demorecording ) {
if (!clc.spDemoRecording) {
Com_Printf ("Already recording.\n");
}
return;
}
if ( cls.state != CA_ACTIVE ) {
Com_Printf ("You must be in a level to record.\n");
return;
}
// sync 0 doesn't prevent recording, so not forcing it off .. everyone does g_sync 1 ; record ; g_sync 0 ..
if ( NET_IsLocalAddress( clc.serverAddress ) && !Cvar_VariableValue( "g_synchronousClients" ) ) {
Com_Printf (S_COLOR_YELLOW "WARNING: You should set 'g_synchronousClients 1' for smoother demo recording\n");
}
if ( Cmd_Argc() == 2 ) {
s = Cmd_Argv(1);
Q_strncpyz( demoName, s, sizeof( demoName ) );
Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION );
} else {
// timestamp the file
CL_DemoFilename( demoName, sizeof( demoName ) );
Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION );
if ( FS_FileExists( name ) ) {
Com_Printf( "Record: Couldn't create a file\n");
return;
}
}
// open the demo file
Com_Printf ("recording to %s.\n", name);
clc.demofile = FS_FOpenFileWrite( name );
if ( !clc.demofile ) {
Com_Printf ("ERROR: couldn't open.\n");
return;
}
clc.demorecording = qtrue;
if (Cvar_VariableValue("ui_recordSPDemo")) {
clc.spDemoRecording = qtrue;
} else {
clc.spDemoRecording = qfalse;
}
Q_strncpyz( clc.demoName, demoName, sizeof( clc.demoName ) );
// don't start saving messages until a non-delta compressed message is received
clc.demowaiting = qtrue;
// write out the gamestate message
MSG_Init (&buf, bufData, sizeof(bufData));
MSG_Bitstream(&buf);
// NOTE, MRE: all server->client messages now acknowledge
MSG_WriteLong( &buf, clc.reliableSequence );
MSG_WriteByte (&buf, svc_gamestate);
MSG_WriteLong (&buf, clc.serverCommandSequence );
// configstrings
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
if ( !cl.gameState.stringOffsets[i] ) {
continue;
}
s = cl.gameState.stringData + cl.gameState.stringOffsets[i];
MSG_WriteByte (&buf, svc_configstring);
MSG_WriteShort (&buf, i);
MSG_WriteBigString (&buf, s);
}
// baselines
Com_Memset (&nullstate, 0, sizeof(nullstate));
for ( i = 0; i < MAX_GENTITIES ; i++ ) {
ent = &cl.entityBaselines[i];
if ( !ent->number ) {
continue;
}
MSG_WriteByte (&buf, svc_baseline);
MSG_WriteDeltaEntity (&buf, &nullstate, ent, qtrue );
}
MSG_WriteByte( &buf, svc_EOF );
// finished writing the gamestate stuff
// write the client num
MSG_WriteLong(&buf, clc.clientNum);
// write the checksum feed
MSG_WriteLong(&buf, clc.checksumFeed);
// Filler for old RMG system.
MSG_WriteShort ( &buf, 0 );
// finished writing the client packet
MSG_WriteByte( &buf, svc_EOF );
// write it to the demo file
len = LittleLong( clc.serverMessageSequence - 1 );
FS_Write (&len, 4, clc.demofile);
len = LittleLong (buf.cursize);
FS_Write (&len, 4, clc.demofile);
FS_Write (buf.data, buf.cursize, clc.demofile);
// the rest of the demo file will be copied from net messages
}
/*
=======================================================================
CLIENT SIDE DEMO PLAYBACK
=======================================================================
*/
/*
=================
CL_DemoCompleted
=================
*/
void CL_DemoCompleted( void ) {
if (cl_timedemo && cl_timedemo->integer) {
int time;
time = Sys_Milliseconds() - clc.timeDemoStart;
if ( time > 0 ) {
Com_Printf ("%i frames, %3.1f seconds: %3.1f fps\n", clc.timeDemoFrames,
time/1000.0, clc.timeDemoFrames*1000.0 / time);
}
}
/* CL_Disconnect( qtrue );
CL_NextDemo();
*/
//rww - The above code seems to just stick you in a no-menu state and you can't do anything there.
//I'm not sure why it ever worked in TA, but whatever. This code will bring us back to the main menu
//after a demo is finished playing instead.
CL_Disconnect_f();
S_StopAllSounds();
UIVM_SetActiveMenu( UIMENU_MAIN );
CL_NextDemo();
}
/*
=================
CL_ReadDemoMessage
=================
*/
void CL_ReadDemoMessage( void ) {
int r;
msg_t buf;
byte bufData[ MAX_MSGLEN ];
int s;
if ( !clc.demofile ) {
CL_DemoCompleted ();
return;
}
// get the sequence number
r = FS_Read( &s, 4, clc.demofile);
if ( r != 4 ) {
CL_DemoCompleted ();
return;
}
clc.serverMessageSequence = LittleLong( s );
// init the message
MSG_Init( &buf, bufData, sizeof( bufData ) );
// get the length
r = FS_Read (&buf.cursize, 4, clc.demofile);
if ( r != 4 ) {
CL_DemoCompleted ();
return;
}
buf.cursize = LittleLong( buf.cursize );
if ( buf.cursize == -1 ) {
CL_DemoCompleted ();
return;
}
if ( buf.cursize > buf.maxsize ) {
Com_Error (ERR_DROP, "CL_ReadDemoMessage: demoMsglen > MAX_MSGLEN");
}
r = FS_Read( buf.data, buf.cursize, clc.demofile );
if ( r != buf.cursize ) {
Com_Printf( "Demo file was truncated.\n");
CL_DemoCompleted ();
return;
}
clc.lastPacketTime = cls.realtime;
buf.readcount = 0;
CL_ParseServerMessage( &buf );
}
/*
====================
CL_CompleteDemoName
====================
*/
static void CL_CompleteDemoName( char *args, int argNum )
{
if( argNum == 2 )
{
char demoExt[16];
Com_sprintf(demoExt, sizeof(demoExt), ".dm_%d", PROTOCOL_VERSION);
Field_CompleteFilename( "demos", demoExt, qtrue, qtrue );
}
}
/*
====================
CL_PlayDemo_f
demo <demoname>
====================
*/
void CL_PlayDemo_f( void ) {
char name[MAX_OSPATH], extension[32];
char *arg;
if (Cmd_Argc() != 2) {
Com_Printf ("demo <demoname>\n");
return;
}
// make sure a local server is killed
// 2 means don't force disconnect of local client
Cvar_Set( "sv_killserver", "2" );
// open the demo file
arg = Cmd_Argv(1);
CL_Disconnect( qtrue );
Com_sprintf(extension, sizeof(extension), ".dm_%d", PROTOCOL_VERSION);
if ( !Q_stricmp( arg + strlen(arg) - strlen(extension), extension ) ) {
Com_sprintf (name, sizeof(name), "demos/%s", arg);
} else {
Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", arg, PROTOCOL_VERSION);
}
FS_FOpenFileRead( name, &clc.demofile, qtrue );
if (!clc.demofile) {
if (!Q_stricmp(arg, "(null)"))
{
Com_Error( ERR_DROP, SE_GetString("CON_TEXT_NO_DEMO_SELECTED") );
}
else
{
Com_Error( ERR_DROP, "couldn't open %s", name);
}
return;
}
Q_strncpyz( clc.demoName, Cmd_Argv(1), sizeof( clc.demoName ) );
Con_Close();
cls.state = CA_CONNECTED;
clc.demoplaying = qtrue;
Q_strncpyz( cls.servername, Cmd_Argv(1), sizeof( cls.servername ) );
// read demo messages until connected
while ( cls.state >= CA_CONNECTED && cls.state < CA_PRIMED ) {
CL_ReadDemoMessage();
}
// don't get the first snapshot this frame, to prevent the long
// time from the gamestate load from messing causing a time skip
clc.firstDemoFrameSkipped = qfalse;
}
/*
====================
CL_StartDemoLoop
Closing the main menu will restart the demo loop
====================
*/
void CL_StartDemoLoop( void ) {
// start the demo loop again
Cbuf_AddText ("d1\n");
Key_SetCatcher( 0 );
}
/*
==================
CL_NextDemo
Called when a demo or cinematic finishes
If the "nextdemo" cvar is set, that command will be issued
==================
*/
void CL_NextDemo( void ) {
char v[MAX_STRING_CHARS];
Q_strncpyz( v, Cvar_VariableString ("nextdemo"), sizeof(v) );
v[MAX_STRING_CHARS-1] = 0;
Com_DPrintf("CL_NextDemo: %s\n", v );
if (!v[0]) {
return;
}
Cvar_Set ("nextdemo","");
Cbuf_AddText (v);
Cbuf_AddText ("\n");
Cbuf_Execute();
}
//======================================================================
/*
=====================
CL_ShutdownAll
=====================
*/
void CL_ShutdownAll( qboolean shutdownRef ) {
if(CL_VideoRecording())
CL_CloseAVI();
if(clc.demorecording)
CL_StopRecord_f();
#if 0 //rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug.
//so it doesn't barf on shutdown saying refentities belong to each other
tr.refdef.num_entities = 0;
#endif
// clear sounds
S_DisableSounds();
// shutdown CGame
CL_ShutdownCGame();
// shutdown UI
CL_ShutdownUI();
// shutdown the renderer
if(shutdownRef)
CL_ShutdownRef( qfalse );
if ( re && re->Shutdown ) {
re->Shutdown( qfalse, qfalse ); // don't destroy window or context
}
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.rendererStarted = qfalse;
cls.soundRegistered = qfalse;
}
/*
=================
CL_FlushMemory
Called by CL_MapLoading, CL_Connect_f, CL_PlayDemo_f, and CL_ParseGamestate the only
ways a client gets into a game
Also called by Com_Error
=================
*/
void CL_FlushMemory( void ) {
// shutdown all the client stuff
CL_ShutdownAll( qfalse );
// if not running a server clear the whole hunk
if ( !com_sv_running->integer ) {
// clear collision map data
CM_ClearMap();
// clear the whole hunk
Hunk_Clear();
}
else {
// clear all the client data on the hunk
Hunk_ClearToMark();
}
CL_StartHunkUsers();
}
/*
=====================
CL_MapLoading
A local server is starting to load a map, so update the
screen to let the user know about it, then dump all client
memory on the hunk from cgame, ui, and renderer
=====================
*/
void CL_MapLoading( void ) {
if ( !com_cl_running->integer ) {
return;
}
// Set this to localhost.
Cvar_Set( "cl_currentServerAddress", "Localhost");
Cvar_Set( "cl_currentServerIP", "loopback");
Con_Close();
Key_SetCatcher( 0 );
// if we are already connected to the local host, stay connected
if ( cls.state >= CA_CONNECTED && !Q_stricmp( cls.servername, "localhost" ) ) {
cls.state = CA_CONNECTED; // so the connect screen is drawn
Com_Memset( cls.updateInfoString, 0, sizeof( cls.updateInfoString ) );
Com_Memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) );
Com_Memset( &cl.gameState, 0, sizeof( cl.gameState ) );
clc.lastPacketSentTime = -9999;
SCR_UpdateScreen();
} else {
// clear nextmap so the cinematic shutdown doesn't execute it
Cvar_Set( "nextmap", "" );
CL_Disconnect( qtrue );
Q_strncpyz( cls.servername, "localhost", sizeof(cls.servername) );
cls.state = CA_CHALLENGING; // so the connect screen is drawn
Key_SetCatcher( 0 );
SCR_UpdateScreen();
clc.connectTime = -RETRANSMIT_TIMEOUT;
NET_StringToAdr( cls.servername, &clc.serverAddress);
// we don't need a challenge on the localhost
CL_CheckForResend();
}
}
/*
=====================
CL_ClearState
Called before parsing a gamestate
=====================
*/
void CL_ClearState (void) {
// S_StopAllSounds();
Com_Memset( &cl, 0, sizeof( cl ) );
}
/*
====================
CL_UpdateGUID
update cl_guid using QKEY_FILE and optional prefix
====================
*/
static void CL_UpdateGUID( const char *prefix, int prefix_len )
{
if (cl_enableGuid->integer) {
fileHandle_t f;
int len;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
// initialize the cvar here in case it's unset or was user-created
// while tracking was disabled (removes CVAR_USER_CREATED)
Cvar_Get( "ja_guid", "", CVAR_USERINFO | CVAR_ROM, "Client GUID" );
if( len != QKEY_SIZE ) {
Cvar_Set( "ja_guid", "" );
} else {
Cvar_Set( "ja_guid", Com_MD5File( QKEY_FILE, QKEY_SIZE,
prefix, prefix_len ) );
}
} else {
// Remove the cvar entirely if tracking is disabled
uint32_t flags = Cvar_Flags("ja_guid");
// keep the cvar if it's user-created, but destroy it otherwise
if (flags != CVAR_NONEXISTENT && !(flags & CVAR_USER_CREATED)) {
cvar_t *ja_guid = Cvar_Get("ja_guid", "", 0, "Client GUID" );
Cvar_Unset(ja_guid);
}
}
}
/*
=====================
CL_Disconnect
Called when a connection, demo, or cinematic is being terminated.
Goes from a connected state to either a menu state or a console state
Sends a disconnect message to the server
This is also called on Com_Error and Com_Quit, so it shouldn't cause any errors
=====================
*/
void CL_Disconnect( qboolean showMainMenu ) {
if ( !com_cl_running || !com_cl_running->integer ) {
return;
}
// shutting down the client so enter full screen ui mode
Cvar_Set("r_uiFullScreen", "1");
if ( clc.demorecording ) {
CL_StopRecord_f ();
}
if (clc.download) {
FS_FCloseFile( clc.download );
clc.download = 0;
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
if ( clc.demofile ) {
FS_FCloseFile( clc.demofile );
clc.demofile = 0;
}
if ( cls.uiStarted && showMainMenu ) {
UIVM_SetActiveMenu( UIMENU_NONE );
}
SCR_StopCinematic ();
S_ClearSoundBuffer();
// send a disconnect message to the server
// send it a few times in case one is dropped
if ( cls.state >= CA_CONNECTED ) {
CL_AddReliableCommand( "disconnect", qtrue );
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
// Remove pure paks
FS_PureServerSetLoadedPaks("", "");
FS_PureServerSetReferencedPaks("", "");
CL_ClearState ();
// wipe the client connection
Com_Memset( &clc, 0, sizeof( clc ) );
cls.state = CA_DISCONNECTED;
// allow cheats locally
Cvar_Set( "sv_cheats", "1" );
// not connected to a pure server anymore
cl_connectedToPureServer = qfalse;
// Stop recording any video
if( CL_VideoRecording( ) ) {
// Finish rendering current frame
SCR_UpdateScreen( );
CL_CloseAVI( );
}
CL_UpdateGUID( NULL, 0 );
}
/*
===================
CL_ForwardCommandToServer
adds the current command line as a clientCommand
things like godmode, noclip, etc, are commands directed to the server,
so when they are typed in at the console, they will need to be forwarded.
===================
*/
void CL_ForwardCommandToServer( const char *string ) {
char *cmd;
cmd = Cmd_Argv(0);
// ignore key up commands
if ( cmd[0] == '-' ) {
return;
}
if (clc.demoplaying || cls.state < CA_CONNECTED || cmd[0] == '+' ) {
Com_Printf ("Unknown command \"%s" S_COLOR_WHITE "\"\n", cmd);
return;
}
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand( string, qfalse );
} else {
CL_AddReliableCommand( cmd, qfalse );
}
}
/*
===================
CL_RequestMotd
===================
*/
void CL_RequestMotd( void ) {
netadr_t to;
int i;
char command[MAX_STRING_CHARS], info[MAX_INFO_STRING];
char *motdaddress;
if ( !cl_motd->integer ) {
return;
}
if ( cl_motd->integer < 1 || cl_motd->integer > MAX_MASTER_SERVERS ) {
Com_Printf( "CL_RequestMotd: Invalid motd server num. Valid values are 1-%d or 0 to disable\n", MAX_MASTER_SERVERS );
return;
}
Com_sprintf( command, sizeof(command), "cl_motdServer%d", cl_motd->integer );
motdaddress = Cvar_VariableString( command );
if ( !*motdaddress )
{
Com_Printf( "CL_RequestMotd: Error: No motd server address given.\n" );
return;
}
i = NET_StringToAdr( motdaddress, &to );
if ( !i )
{
Com_Printf( "CL_RequestMotd: Error: could not resolve address of motd server %s\n", motdaddress );
return;
}
to.type = NA_IP;
to.port = BigShort( PORT_UPDATE );
Com_Printf( "Requesting motd from update %s (%s)...\n", motdaddress, NET_AdrToString( to ) );
cls.updateServer = to;
info[0] = 0;
// NOTE TTimo xoring against Com_Milliseconds, otherwise we may not have a true randomization
// only srand I could catch before here is tr_noise.c l:26 srand(1001)
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=382
// NOTE: the Com_Milliseconds xoring only affects the lower 16-bit word,
// but I decided it was enough randomization
Com_sprintf( cls.updateChallenge, sizeof( cls.updateChallenge ), "%i", ((rand() << 16) ^ rand()) ^ Com_Milliseconds());
Info_SetValueForKey( info, "challenge", cls.updateChallenge );
Info_SetValueForKey( info, "renderer", cls.glconfig.renderer_string );
Info_SetValueForKey( info, "rvendor", cls.glconfig.vendor_string );
Info_SetValueForKey( info, "version", com_version->string );
//If raven starts filtering for this, add this code back in
#if 0
Info_SetValueForKey( info, "cputype", "Intel Pentium IV");
Info_SetValueForKey( info, "mhz", "3000" );
Info_SetValueForKey( info, "memory", "4096" );
#endif
Info_SetValueForKey( info, "joystick", Cvar_VariableString("in_joystick") );
Info_SetValueForKey( info, "colorbits", va("%d",cls.glconfig.colorBits) );
NET_OutOfBandPrint( NS_CLIENT, cls.updateServer, "getmotd \"%s\"\n", info );
}
/*
======================================================================
CONSOLE COMMANDS
======================================================================
*/
/*
==================
CL_ForwardToServer_f
==================
*/
void CL_ForwardToServer_f( void ) {
if ( cls.state != CA_ACTIVE || clc.demoplaying ) {
Com_Printf ("Not connected to a server.\n");
return;
}
// don't forward the first argument
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand( Cmd_Args(), qfalse );
}
}
/*
==================
CL_Disconnect_f
==================
*/
void CL_Disconnect_f( void ) {
SCR_StopCinematic();
Cvar_Set("ui_singlePlayerActive", "0");
if ( cls.state != CA_DISCONNECTED && cls.state != CA_CINEMATIC ) {
Com_Error (ERR_DISCONNECT, "Disconnected from server");
}
}
/*
================
CL_Reconnect_f
================
*/
void CL_Reconnect_f( void ) {
if ( !strlen( cl_reconnectArgs ) ) {
return;
}
Cvar_Set("ui_singlePlayerActive", "0");
Cbuf_AddText( va("connect %s\n", cl_reconnectArgs ) );
}
/*
================
CL_Connect_f
================
*/
void CL_Connect_f( void ) {
char *server;
const char *serverString;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: connect [server]\n");
return;
}
// save arguments for reconnect
Q_strncpyz( cl_reconnectArgs, Cmd_Args(), sizeof( cl_reconnectArgs ) );
Cvar_Set("ui_singlePlayerActive", "0");
// fire a message off to the motd server
CL_RequestMotd();
// clear any previous "server full" type messages
clc.serverMessage[0] = 0;
server = Cmd_Argv (1);
if ( com_sv_running->integer && !strcmp( server, "localhost" ) ) {
// if running a local server, kill it
SV_Shutdown( "Server quit\n" );
}
// make sure a local server is killed
Cvar_Set( "sv_killserver", "1" );
SV_Frame( 0 );
CL_Disconnect( qtrue );
Con_Close();
Q_strncpyz( cls.servername, server, sizeof(cls.servername) );
if (!NET_StringToAdr( cls.servername, &clc.serverAddress) ) {
Com_Printf ("Bad server address\n");
cls.state = CA_DISCONNECTED;
return;
}
if (clc.serverAddress.port == 0) {
clc.serverAddress.port = BigShort( PORT_SERVER );
}
serverString = NET_AdrToString(clc.serverAddress);
Com_Printf( "%s resolved to %s\n", cls.servername, serverString );
if( cl_guidServerUniq->integer )
CL_UpdateGUID( serverString, strlen( serverString ) );
else
CL_UpdateGUID( NULL, 0 );
// if we aren't playing on a lan, we need to authenticate
if ( NET_IsLocalAddress( clc.serverAddress ) ) {
cls.state = CA_CHALLENGING;
} else {
cls.state = CA_CONNECTING;
// Set a client challenge number that ideally is mirrored back by the server.
clc.challenge = ((rand() << 16) ^ rand()) ^ Com_Milliseconds();
}
Key_SetCatcher( 0 );
clc.connectTime = -99999; // CL_CheckForResend() will fire immediately
clc.connectPacketCount = 0;
// server connection string
Cvar_Set( "cl_currentServerAddress", server );
Cvar_Set( "cl_currentServerIP", serverString );
}
#define MAX_RCON_MESSAGE 1024
/*
==================
CL_CompleteRcon
==================
*/
static void CL_CompleteRcon( char *args, int argNum )
{
if( argNum == 2 )
{
// Skip "rcon "
char *p = Com_SkipTokens( args, 1, " " );
if( p > args )
Field_CompleteCommand( p, qtrue, qtrue );
}
}
/*
=====================
CL_Rcon_f
Send the rest of the command line over as
an unconnected command.
=====================
*/
void CL_Rcon_f( void ) {
char message[MAX_RCON_MESSAGE];
if ( !rcon_client_password->string[0] ) {
Com_Printf( "You must set 'rconpassword' before issuing an rcon command.\n" );
return;
}
message[0] = -1;
message[1] = -1;
message[2] = -1;
message[3] = -1;
message[4] = 0;
Q_strcat (message, MAX_RCON_MESSAGE, "rcon ");
Q_strcat (message, MAX_RCON_MESSAGE, rcon_client_password->string);
Q_strcat (message, MAX_RCON_MESSAGE, " ");
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543
Q_strcat (message, MAX_RCON_MESSAGE, Cmd_Cmd()+5);
if ( cls.state >= CA_CONNECTED ) {
rcon_address = clc.netchan.remoteAddress;
} else {
if (!strlen(rconAddress->string)) {
Com_Printf ("You must either be connected,\n"
"or set the 'rconAddress' cvar\n"
"to issue rcon commands\n");
return;
}
NET_StringToAdr (rconAddress->string, &rcon_address);
if (rcon_address.port == 0) {
rcon_address.port = BigShort (PORT_SERVER);
}
}
NET_SendPacket (NS_CLIENT, strlen(message)+1, message, rcon_address);
}
/*
=================
CL_SendPureChecksums
=================
*/
void CL_SendPureChecksums( void ) {
char cMsg[MAX_INFO_VALUE];
// if we are pure we need to send back a command with our referenced pk3 checksums
Com_sprintf(cMsg, sizeof(cMsg), "cp %s", FS_ReferencedPakPureChecksums());
CL_AddReliableCommand( cMsg, qfalse );
}
/*
=================
CL_ResetPureClientAtServer
=================
*/
void CL_ResetPureClientAtServer( void ) {
CL_AddReliableCommand( "vdr", qfalse );
}
/*
=================
CL_Vid_Restart_f
Restart the video subsystem
we also have to reload the UI and CGame because the renderer
doesn't know what graphics to reload
=================
*/
extern bool g_nOverrideChecked;
void CL_Vid_Restart_f( void ) {
// Settings may have changed so stop recording now
if( CL_VideoRecording( ) ) {
CL_CloseAVI( );
}
if(clc.demorecording)
CL_StopRecord_f();
//rww - sort of nasty, but when a user selects a mod
//from the menu all it does is a vid_restart, so we
//have to check for new net overrides for the mod then.
g_nOverrideChecked = false;
// don't let them loop during the restart
S_StopAllSounds();
// shutdown the UI
CL_ShutdownUI();
// shutdown the CGame
CL_ShutdownCGame();
// shutdown the renderer and clear the renderer interface
CL_ShutdownRef( qtrue );
// client is no longer pure untill new checksums are sent
CL_ResetPureClientAtServer();
// clear pak references
FS_ClearPakReferences( FS_UI_REF | FS_CGAME_REF );
// reinitialize the filesystem if the game directory or checksum has changed
FS_ConditionalRestart( clc.checksumFeed );
cls.rendererStarted = qfalse;
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.soundRegistered = qfalse;
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
// if not running a server clear the whole hunk
if ( !com_sv_running->integer ) {
CM_ClearMap();
// clear the whole hunk
Hunk_Clear();
}
else {
// clear all the client data on the hunk
Hunk_ClearToMark();
}
// initialize the renderer interface
CL_InitRef();
// startup all the client stuff
CL_StartHunkUsers();
// start the cgame if connected
if ( cls.state > CA_CONNECTED && cls.state != CA_CINEMATIC ) {
cls.cgameStarted = qtrue;
CL_InitCGame();
// send pure checksums
CL_SendPureChecksums();
}
}
/*
=================
CL_Snd_Restart_f
Restart the sound subsystem
The cgame and game must also be forced to restart because
handles will be invalid
=================
*/
// extern void S_UnCacheDynamicMusic( void );
void CL_Snd_Restart_f( void ) {
S_Shutdown();
S_Init();
// S_FreeAllSFXMem(); // These two removed by BTO (VV)
// S_UnCacheDynamicMusic(); // S_Shutdown() already does this!
// CL_Vid_Restart_f();
extern qboolean s_soundMuted;
s_soundMuted = qfalse; // we can play again
extern void S_RestartMusic( void );
S_RestartMusic();
}
/*
==================
CL_PK3List_f
==================
*/
void CL_OpenedPK3List_f( void ) {
Com_Printf("Opened PK3 Names: %s\n", FS_LoadedPakNames());
}
/*
==================
CL_PureList_f
==================
*/
void CL_ReferencedPK3List_f( void ) {
Com_Printf("Referenced PK3 Names: %s\n", FS_ReferencedPakNames());
}
/*
==================
CL_Configstrings_f
==================
*/
void CL_Configstrings_f( void ) {
int i;
int ofs;
if ( cls.state != CA_ACTIVE ) {
Com_Printf( "Not connected to a server.\n");
return;
}
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
ofs = cl.gameState.stringOffsets[ i ];
if ( !ofs ) {
continue;
}
Com_Printf( "%4i: %s\n", i, cl.gameState.stringData + ofs );
}
}
/*
==============
CL_Clientinfo_f
==============
*/
void CL_Clientinfo_f( void ) {
Com_Printf( "--------- Client Information ---------\n" );
Com_Printf( "state: %i\n", cls.state );
Com_Printf( "Server: %s\n", cls.servername );
Com_Printf ("User info settings:\n");
Info_Print( Cvar_InfoString( CVAR_USERINFO ) );
Com_Printf( "--------------------------------------\n" );
}
//====================================================================
/*
=================
CL_DownloadsComplete
Called when all downloading has been completed
=================
*/
void CL_DownloadsComplete( void ) {
// if we downloaded files we need to restart the file system
if (clc.downloadRestart) {
clc.downloadRestart = qfalse;
FS_Restart(clc.checksumFeed); // We possibly downloaded a pak, restart the file system to load it
// inform the server so we get new gamestate info
CL_AddReliableCommand( "donedl", qfalse );
// by sending the donedl command we request a new gamestate
// so we don't want to load stuff yet
return;
}
// let the client game init and load data
cls.state = CA_LOADING;
// Pump the loop, this may change gamestate!
Com_EventLoop();
// if the gamestate was changed by calling Com_EventLoop
// then we loaded everything already and we don't want to do it again.
if ( cls.state != CA_LOADING ) {
return;
}
// starting to load a map so we get out of full screen ui mode
Cvar_Set("r_uiFullScreen", "0");
// flush client memory and start loading stuff
// this will also (re)load the UI
// if this is a local client then only the client part of the hunk
// will be cleared, note that this is done after the hunk mark has been set
CL_FlushMemory();
// initialize the CGame
cls.cgameStarted = qtrue;
CL_InitCGame();
// set pure checksums
CL_SendPureChecksums();
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
/*
=================
CL_BeginDownload
Requests a file to download from the server. Stores it in the current
game directory.
=================
*/
void CL_BeginDownload( const char *localName, const char *remoteName ) {
Com_DPrintf("***** CL_BeginDownload *****\n"
"Localname: %s\n"
"Remotename: %s\n"
"****************************\n", localName, remoteName);
Q_strncpyz ( clc.downloadName, localName, sizeof(clc.downloadName) );
Com_sprintf( clc.downloadTempName, sizeof(clc.downloadTempName), "%s.tmp", localName );
// Set so UI gets access to it
Cvar_Set( "cl_downloadName", remoteName );
Cvar_Set( "cl_downloadSize", "0" );
Cvar_Set( "cl_downloadCount", "0" );
Cvar_SetValue( "cl_downloadTime", (float) cls.realtime );
clc.downloadBlock = 0; // Starting new file
clc.downloadCount = 0;
CL_AddReliableCommand( va("download %s", remoteName), qfalse );
}
/*
=================
CL_NextDownload
A download completed or failed
=================
*/
void CL_NextDownload(void) {
char *s;
char *remoteName, *localName;
// A download has finished, check whether this matches a referenced checksum
if(*clc.downloadName)
{
char *zippath = FS_BuildOSPath(Cvar_VariableString("fs_homepath"), clc.downloadName, "");
zippath[strlen(zippath)-1] = '\0';
if(!FS_CompareZipChecksum(zippath))
Com_Error(ERR_DROP, "Incorrect checksum for file: %s", clc.downloadName);
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set("cl_downloadName", "");
// We are looking to start a download here
if (*clc.downloadList) {
s = clc.downloadList;
// format is:
// @remotename@localname@remotename@localname, etc.
if (*s == '@')
s++;
remoteName = s;
if ( (s = strchr(s, '@')) == NULL ) {
CL_DownloadsComplete();
return;
}
*s++ = 0;
localName = s;
if ( (s = strchr(s, '@')) != NULL )
*s++ = 0;
else
s = localName + strlen(localName); // point at the nul byte
if (!cl_allowDownload->integer) {
Com_Error(ERR_DROP, "UDP Downloads are disabled on your client. (cl_allowDownload is %d)", cl_allowDownload->integer);
return;
}
else {
CL_BeginDownload( localName, remoteName );
}
clc.downloadRestart = qtrue;
// move over the rest
memmove( clc.downloadList, s, strlen(s) + 1);
return;
}
CL_DownloadsComplete();
}
/*
=================
CL_InitDownloads
After receiving a valid game state, we valid the cgame and local zip files here
and determine if we need to download them
=================
*/
void CL_InitDownloads(void) {
char missingfiles[1024];
if ( !cl_allowDownload->integer )
{
// autodownload is disabled on the client
// but it's possible that some referenced files on the server are missing
if (FS_ComparePaks( missingfiles, sizeof( missingfiles ), qfalse ) )
{
// NOTE TTimo I would rather have that printed as a modal message box
// but at this point while joining the game we don't know wether we will successfully join or not
Com_Printf( "\nWARNING: You are missing some files referenced by the server:\n%s"
"You might not be able to join the game\n"
"Go to the setting menu to turn on autodownload, or get the file elsewhere\n\n", missingfiles );
}
}
else if ( FS_ComparePaks( clc.downloadList, sizeof( clc.downloadList ) , qtrue ) ) {
Com_Printf("Need paks: %s\n", clc.downloadList );
if ( *clc.downloadList ) {
// if autodownloading is not enabled on the server
cls.state = CA_CONNECTED;
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
CL_NextDownload();
return;
}
}
CL_DownloadsComplete();
}
/*
=================
CL_CheckForResend
Resend a connect message if the last one has timed out
=================
*/
void CL_CheckForResend( void ) {
int port;
char info[MAX_INFO_STRING];
char data[MAX_INFO_STRING+10];
// don't send anything if playing back a demo
if ( clc.demoplaying ) {
return;
}
// resend if we haven't gotten a reply yet
if ( cls.state != CA_CONNECTING && cls.state != CA_CHALLENGING ) {
return;
}
if ( cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT ) {
return;
}
clc.connectTime = cls.realtime; // for retransmit requests
clc.connectPacketCount++;
switch ( cls.state ) {
case CA_CONNECTING:
// requesting a challenge
// The challenge request shall be followed by a client challenge so no malicious server can hijack this connection.
Com_sprintf(data, sizeof(data), "getchallenge %d", clc.challenge);
NET_OutOfBandPrint(NS_CLIENT, clc.serverAddress, data);
break;
case CA_CHALLENGING:
// sending back the challenge
port = (int) Cvar_VariableValue ("net_qport");
Q_strncpyz( info, Cvar_InfoString( CVAR_USERINFO ), sizeof( info ) );
Info_SetValueForKey( info, "protocol", va("%i", PROTOCOL_VERSION ) );
Info_SetValueForKey( info, "qport", va("%i", port ) );
Info_SetValueForKey( info, "challenge", va("%i", clc.challenge ) );
Com_sprintf(data, sizeof(data), "connect \"%s\"", info );
NET_OutOfBandData( NS_CLIENT, clc.serverAddress, (byte *)data, strlen(data) );
// the most current userinfo has been sent, so watch for any
// newer changes to userinfo variables
cvar_modifiedFlags &= ~CVAR_USERINFO;
break;
default:
Com_Error( ERR_FATAL, "CL_CheckForResend: bad cls.state" );
}
}
/*
===================
CL_DisconnectPacket
Sometimes the server can drop the client and the netchan based
disconnect can be lost. If the client continues to send packets
to the server, the server will send out of band disconnect packets
to the client so it doesn't have to wait for the full timeout period.
===================
*/
void CL_DisconnectPacket( netadr_t from ) {
if ( cls.state < CA_AUTHORIZING ) {
return;
}
// if not from our server, ignore it
if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
return;
}
// if we have received packets within three seconds, ignore it
// (it might be a malicious spoof)
if ( cls.realtime - clc.lastPacketTime < 3000 ) {
return;
}
// drop the connection (FIXME: connection dropped dialog)
Com_Printf( "Server disconnected for unknown reason\n" );
CL_Disconnect( qtrue );
}
/*
===================
CL_MotdPacket
===================
*/
void CL_MotdPacket( netadr_t from ) {
char *challenge;
char *info;
// if not from our server, ignore it
if ( !NET_CompareAdr( from, cls.updateServer ) ) {
return;
}
info = Cmd_Argv(1);
// check challenge
challenge = Info_ValueForKey( info, "challenge" );
if ( strcmp( challenge, cls.updateChallenge ) ) {
return;
}
challenge = Info_ValueForKey( info, "motd" );
Q_strncpyz( cls.updateInfoString, info, sizeof( cls.updateInfoString ) );
Cvar_Set( "cl_motdString", challenge );
}
/*
===================
CL_InitServerInfo
===================
*/
void CL_InitServerInfo( serverInfo_t *server, netadr_t *address ) {
server->adr = *address;
server->clients = 0;
server->hostName[0] = '\0';
server->mapName[0] = '\0';
server->maxClients = 0;
server->maxPing = 0;
server->minPing = 0;
server->netType = 0;
server->needPassword = qfalse;
server->trueJedi = 0;
server->weaponDisable = 0;
server->forceDisable = 0;
server->ping = -1;
server->game[0] = '\0';
server->gameType = 0;
server->humans = server->bots = 0;
}
#define MAX_SERVERSPERPACKET 256
/*
===================
CL_ServersResponsePacket
===================
*/
void CL_ServersResponsePacket( const netadr_t *from, msg_t *msg ) {
int i, j, count, total;
netadr_t addresses[MAX_SERVERSPERPACKET];
int numservers;
byte* buffptr;
byte* buffend;
Com_Printf("CL_ServersResponsePacket\n");
if (cls.numglobalservers == -1) {
// state to detect lack of servers or lack of response
cls.numglobalservers = 0;
cls.numGlobalServerAddresses = 0;
}
// parse through server response string
numservers = 0;
buffptr = msg->data;
buffend = buffptr + msg->cursize;
// advance to initial token
do
{
if(*buffptr == '\\')
break;
buffptr++;
} while (buffptr < buffend);
while (buffptr + 1 < buffend)
{
// IPv4 address
if (*buffptr == '\\')
{
buffptr++;
if (buffend - buffptr < (int)(sizeof(addresses[numservers].ip) + sizeof(addresses[numservers].port) + 1))
break;
for(size_t i = 0; i < sizeof(addresses[numservers].ip); i++)
addresses[numservers].ip[i] = *buffptr++;
addresses[numservers].type = NA_IP;
}
else
// syntax error!
break;
// parse out port
addresses[numservers].port = (*buffptr++) << 8;
addresses[numservers].port += *buffptr++;
addresses[numservers].port = BigShort( addresses[numservers].port );
// syntax check
if (*buffptr != '\\')
break;
numservers++;
if (numservers >= MAX_SERVERSPERPACKET)
break;
}
count = cls.numglobalservers;
for (i = 0; i < numservers && count < MAX_GLOBAL_SERVERS; i++) {
// build net address
serverInfo_t *server = &cls.globalServers[count];
// Tequila: It's possible to have sent many master server requests. Then
// we may receive many times the same addresses from the master server.
// We just avoid to add a server if it is still in the global servers list.
for (j = 0; j < count; j++)
{
if (NET_CompareAdr(cls.globalServers[j].adr, addresses[i]))
break;
}
if (j < count)
continue;
CL_InitServerInfo( server, &addresses[i] );
// advance to next slot
count++;
}
// if getting the global list
if ( count >= MAX_GLOBAL_SERVERS && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS )
{
// if we couldn't store the servers in the main list anymore
for (; i < numservers && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS; i++)
{
// just store the addresses in an additional list
cls.globalServerAddresses[cls.numGlobalServerAddresses++] = addresses[i];
}
}
cls.numglobalservers = count;
total = count + cls.numGlobalServerAddresses;
Com_Printf("%d servers parsed (total %d)\n", numservers, total);
}
#ifndef MAX_STRINGED_SV_STRING
#define MAX_STRINGED_SV_STRING 1024
#endif
static void CL_CheckSVStringEdRef(char *buf, const char *str)
{ //I don't really like doing this. But it utilizes the system that was already in place.
int i = 0;
int b = 0;
int strLen = 0;
qboolean gotStrip = qfalse;
if (!str || !str[0])
{
if (str)
{
strcpy(buf, str);
}
return;
}
strcpy(buf, str);
strLen = strlen(str);
if (strLen >= MAX_STRINGED_SV_STRING)
{
return;
}
while (i < strLen && str[i])
{
gotStrip = qfalse;
if (str[i] == '@' && (i+1) < strLen)
{
if (str[i+1] == '@' && (i+2) < strLen)
{
if (str[i+2] == '@' && (i+3) < strLen)
{ //@@@ should mean to insert a stringed reference here, so insert it into buf at the current place
char stripRef[MAX_STRINGED_SV_STRING];
int r = 0;
while (i < strLen && str[i] == '@')
{
i++;
}
while (i < strLen && str[i] && str[i] != ' ' && str[i] != ':' && str[i] != '.' && str[i] != '\n')
{
stripRef[r] = str[i];
r++;
i++;
}
stripRef[r] = 0;
buf[b] = 0;
Q_strcat(buf, MAX_STRINGED_SV_STRING, SE_GetString(va("MP_SVGAME_%s", stripRef)));
b = strlen(buf);
}
}
}
if (!gotStrip)
{
buf[b] = str[i];
b++;
}
i++;
}
buf[b] = 0;
}
/*
=================
CL_ConnectionlessPacket
Responses to broadcasts, etc
=================
*/
void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) {
char *s;
char *c;
int challenge = 0;
MSG_BeginReadingOOB( msg );
MSG_ReadLong( msg ); // skip the -1
s = MSG_ReadStringLine( msg );
Cmd_TokenizeString( s );
c = Cmd_Argv(0);
Com_DPrintf ("CL packet %s: %s\n", NET_AdrToString(from), c);
// challenge from the server we are connecting to
if ( !Q_stricmp(c, "challengeResponse") )
{
if ( cls.state != CA_CONNECTING )
{
Com_Printf( "Unwanted challenge response received. Ignored.\n" );
return;
}
c = Cmd_Argv(2);
if(*c)
challenge = atoi(c);
if(!NET_CompareAdr(from, clc.serverAddress))
{
// This challenge response is not coming from the expected address.
// Check whether we have a matching client challenge to prevent
// connection hi-jacking.
if(!*c || challenge != clc.challenge)
{
Com_DPrintf("Challenge response received from unexpected source. Ignored.\n");
return;
}
}
// start sending challenge response instead of challenge request packets
clc.challenge = atoi(Cmd_Argv(1));
cls.state = CA_CHALLENGING;
clc.connectPacketCount = 0;
clc.connectTime = -99999;
// take this address as the new server address. This allows
// a server proxy to hand off connections to multiple servers
clc.serverAddress = from;
Com_DPrintf ("challengeResponse: %d\n", clc.challenge);
return;
}
// server connection
if ( !Q_stricmp(c, "connectResponse") ) {
if ( cls.state >= CA_CONNECTED ) {
Com_Printf ("Dup connect received. Ignored.\n");
return;
}
if ( cls.state != CA_CHALLENGING ) {
Com_Printf ("connectResponse packet while not connecting. Ignored.\n");
return;
}
if ( !NET_CompareAdr( from, clc.serverAddress ) ) {
Com_Printf( "connectResponse from wrong address. Ignored.\n" );
return;
}
Netchan_Setup (NS_CLIENT, &clc.netchan, from, Cvar_VariableValue( "net_qport" ) );
cls.state = CA_CONNECTED;
clc.lastPacketSentTime = -9999; // send first packet immediately
return;
}
// server responding to an info broadcast
if ( !Q_stricmp(c, "infoResponse") ) {
CL_ServerInfoPacket( from, msg );
return;
}
// server responding to a get playerlist
if ( !Q_stricmp(c, "statusResponse") ) {
CL_ServerStatusResponse( from, msg );
return;
}
// a disconnect message from the server, which will happen if the server
// dropped the connection but it is still getting packets from us
if (!Q_stricmp(c, "disconnect")) {
CL_DisconnectPacket( from );
return;
}
// echo request from server
if ( !Q_stricmp(c, "echo") ) {
NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv(1) );
return;
}
// cd check
if ( !Q_stricmp(c, "keyAuthorize") ) {
// we don't use these now, so dump them on the floor
return;
}
// global MOTD from id
if ( !Q_stricmp(c, "motd") ) {
CL_MotdPacket( from );
return;
}
// echo request from server
if ( !Q_stricmp(c, "print") )
{
// NOTE: we may have to add exceptions for auth and update servers
if (NET_CompareAdr(from, clc.serverAddress) || NET_CompareAdr(from, rcon_address))
{
char sTemp[MAX_STRINGED_SV_STRING];
s = MSG_ReadString( msg );
CL_CheckSVStringEdRef(sTemp, s);
Q_strncpyz( clc.serverMessage, sTemp, sizeof( clc.serverMessage ) );
Com_Printf( "%s", sTemp );
}
return;
}
// list of servers sent back by a master server (classic)
if ( !Q_strncmp(c, "getserversResponse", 18) ) {
CL_ServersResponsePacket( &from, msg );
return;
}
Com_DPrintf ("Unknown connectionless packet command.\n");
}
/*
=================
CL_PacketEvent
A packet has arrived from the main event loop
=================
*/
void CL_PacketEvent( netadr_t from, msg_t *msg ) {
int headerBytes;
clc.lastPacketTime = cls.realtime;
if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) {
CL_ConnectionlessPacket( from, msg );
return;
}
if ( cls.state < CA_CONNECTED ) {
return; // can't be a valid sequenced packet
}
if ( msg->cursize < 4 ) {
Com_Printf ("%s: Runt packet\n",NET_AdrToString( from ));
return;
}
//
// packet from server
//
if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
Com_DPrintf ("%s:sequenced packet without connection\n"
,NET_AdrToString( from ) );
// FIXME: send a client disconnect?
return;
}
if (!CL_Netchan_Process( &clc.netchan, msg) ) {
return; // out of order, duplicated, etc
}
// the header is different lengths for reliable and unreliable messages
headerBytes = msg->readcount;
// track the last message received so it can be returned in
// client messages, allowing the server to detect a dropped
// gamestate
clc.serverMessageSequence = LittleLong( *(int *)msg->data );
clc.lastPacketTime = cls.realtime;
CL_ParseServerMessage( msg );
//
// we don't know if it is ok to save a demo message until
// after we have parsed the frame
//
if ( clc.demorecording && !clc.demowaiting ) {
CL_WriteDemoMessage( msg, headerBytes );
}
}
/*
==================
CL_CheckTimeout
==================
*/
void CL_CheckTimeout( void ) {
//
// check timeout
//
if ( ( !CL_CheckPaused() || !sv_paused->integer )
&& cls.state >= CA_CONNECTED && cls.state != CA_CINEMATIC
&& cls.realtime - clc.lastPacketTime > cl_timeout->value*1000) {
if (++cl.timeoutcount > 5) { // timeoutcount saves debugger
const char *psTimedOut = SE_GetString("MP_SVGAME_SERVER_CONNECTION_TIMED_OUT");
Com_Printf ("\n%s\n",psTimedOut);
Com_Error(ERR_DROP, psTimedOut);
//CL_Disconnect( qtrue );
return;
}
} else {
cl.timeoutcount = 0;
}
}
/*
==================
CL_CheckPaused
Check whether client has been paused.
==================
*/
qboolean CL_CheckPaused(void)
{
// if cl_paused->modified is set, the cvar has only been changed in
// this frame. Keep paused in this frame to ensure the server doesn't
// lag behind.
if(cl_paused->integer || cl_paused->modified)
return qtrue;
return qfalse;
}
//============================================================================
/*
==================
CL_CheckUserinfo
==================
*/
void CL_CheckUserinfo( void ) {
// don't add reliable commands when not yet connected
if ( cls.state < CA_CONNECTED ) {
return;
}
// don't overflow the reliable command buffer when paused
if ( CL_CheckPaused() ) {
return;
}
// send a reliable userinfo update if needed
if ( cvar_modifiedFlags & CVAR_USERINFO ) {
cvar_modifiedFlags &= ~CVAR_USERINFO;
CL_AddReliableCommand( va("userinfo \"%s\"", Cvar_InfoString( CVAR_USERINFO ) ), qfalse );
}
}
/*
==================
CL_Frame
==================
*/
static unsigned int frameCount;
static float avgFrametime=0.0;
extern void SE_CheckForLanguageUpdates(void);
void CL_Frame ( int msec ) {
qboolean takeVideoFrame = qfalse;
if ( !com_cl_running->integer ) {
return;
}
SE_CheckForLanguageUpdates(); // will take zero time to execute unless language changes, then will reload strings.
// of course this still doesn't work for menus...
if ( cls.state == CA_DISCONNECTED && !( Key_GetCatcher( ) & KEYCATCH_UI )
&& !com_sv_running->integer && cls.uiStarted ) {
// if disconnected, bring up the menu
S_StopAllSounds();
UIVM_SetActiveMenu( UIMENU_MAIN );
}
// if recording an avi, lock to a fixed fps
if ( CL_VideoRecording( ) && cl_aviFrameRate->integer && msec) {
if ( cls.state == CA_ACTIVE || cl_forceavidemo->integer) {
float fps = Q_min(cl_aviFrameRate->value * com_timescale->value, 1000.0f);
float frameDuration = Q_max(1000.0f / fps, 1.0f) + clc.aviVideoFrameRemainder;
takeVideoFrame = qtrue;
msec = (int)frameDuration;
clc.aviVideoFrameRemainder = frameDuration - msec;
}
}
// save the msec before checking pause
cls.realFrametime = msec;
// decide the simulation time
cls.frametime = msec;
if(cl_framerate->integer)
{
avgFrametime+=msec;
char mess[256];
if(!(frameCount&0x1f))
{
Com_sprintf(mess,sizeof(mess),"Frame rate=%f\n\n",1000.0f*(1.0/(avgFrametime/32.0f)));
// Com_OPrintf("%s", mess);
Com_Printf("%s", mess);
avgFrametime=0.0f;
}
frameCount++;
}
cls.realtime += cls.frametime;
if ( cl_timegraph->integer ) {
SCR_DebugGraph ( cls.realFrametime * 0.25, 0 );
}
// see if we need to update any userinfo
CL_CheckUserinfo();
// if we haven't gotten a packet in a long time,
// drop the connection
CL_CheckTimeout();
// send intentions now
CL_SendCmd();
// resend a connection request if necessary
CL_CheckForResend();
// decide on the serverTime to render
CL_SetCGameTime();
// update the screen
SCR_UpdateScreen();
// update audio
S_Update();
// advance local effects for next frame
SCR_RunCinematic();
Con_RunConsole();
// reset the heap for Ghoul2 vert transform space gameside
if (G2VertSpaceServer)
{
G2VertSpaceServer->ResetHeap();
}
cls.framecount++;
if ( takeVideoFrame ) {
// save the current screen
CL_TakeVideoFrame( );
}
}
//============================================================================
/*
================
CL_RefPrintf
DLL glue
================
*/
void QDECL CL_RefPrintf( int print_level, const char *fmt, ...) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start (argptr,fmt);
Q_vsnprintf(msg, sizeof(msg), fmt, argptr);
va_end (argptr);
if ( print_level == PRINT_ALL ) {
Com_Printf ("%s", msg);
} else if ( print_level == PRINT_WARNING ) {
Com_Printf (S_COLOR_YELLOW "%s", msg); // yellow
} else if ( print_level == PRINT_DEVELOPER ) {
Com_DPrintf (S_COLOR_RED "%s", msg); // red
}
}
/*
============
CL_ShutdownRef
============
*/
static void CL_ShutdownRef( qboolean restarting ) {
if ( re )
{
if ( re->Shutdown )
{
re->Shutdown( qtrue, restarting );
}
}
re = NULL;
if ( rendererLib != NULL ) {
Sys_UnloadDll (rendererLib);
rendererLib = NULL;
}
}
/*
============
CL_InitRenderer
============
*/
void CL_InitRenderer( void ) {
// this sets up the renderer and calls R_Init
re->BeginRegistration( &cls.glconfig );
// load character sets
cls.charSetShader = re->RegisterShaderNoMip("gfx/2d/charsgrid_med");
cls.whiteShader = re->RegisterShader( "white" );
cls.consoleShader = re->RegisterShader( "console" );
g_console_field_width = cls.glconfig.vidWidth / SMALLCHAR_WIDTH - 2;
g_consoleField.widthInChars = g_console_field_width;
}
/*
============================
CL_StartHunkUsers
After the server has cleared the hunk, these will need to be restarted
This is the only place that any of these functions are called from
============================
*/
void CL_StartHunkUsers( void ) {
if (!com_cl_running) {
return;
}
if ( !com_cl_running->integer ) {
return;
}
if ( !cls.rendererStarted ) {
cls.rendererStarted = qtrue;
CL_InitRenderer();
}
if ( !cls.soundStarted ) {
cls.soundStarted = qtrue;
S_Init();
}
if ( !cls.soundRegistered ) {
cls.soundRegistered = qtrue;
S_BeginRegistration();
}
if ( !cls.uiStarted ) {
cls.uiStarted = qtrue;
CL_InitUI();
}
}
/*
============
CL_InitRef
============
*/
qboolean Com_TheHunkMarkHasBeenMade(void);
//qcommon/cm_load.cpp
extern void *gpvCachedMapDiskImage;
extern qboolean gbUsingCachedMapDataRightNow;
static char *GetSharedMemory( void ) { return cl.mSharedMemory; }
static vm_t *GetCurrentVM( void ) { return currentVM; }
static qboolean CGVMLoaded( void ) { return (qboolean)cls.cgameStarted; }
static void *CM_GetCachedMapDiskImage( void ) { return gpvCachedMapDiskImage; }
static void CM_SetCachedMapDiskImage( void *ptr ) { gpvCachedMapDiskImage = ptr; }
static void CM_SetUsingCache( qboolean usingCache ) { gbUsingCachedMapDataRightNow = usingCache; }
#define G2_VERT_SPACE_SERVER_SIZE 256
IHeapAllocator *G2VertSpaceServer = NULL;
CMiniHeap IHeapAllocator_singleton(G2_VERT_SPACE_SERVER_SIZE * 1024);
static IHeapAllocator *GetG2VertSpaceServer( void ) {
return G2VertSpaceServer;
}
#define DEFAULT_RENDER_LIBRARY "rd-vanilla"
void CL_InitRef( void ) {
static refimport_t ri;
refexport_t *ret;
GetRefAPI_t GetRefAPI;
char dllName[MAX_OSPATH];
Com_Printf( "----- Initializing Renderer ----\n" );
cl_renderer = Cvar_Get( "cl_renderer", DEFAULT_RENDER_LIBRARY, CVAR_ARCHIVE|CVAR_LATCH, "Which renderer library to use" );
Com_sprintf( dllName, sizeof( dllName ), "%s_" ARCH_STRING DLL_EXT, cl_renderer->string );
if( !(rendererLib = Sys_LoadDll( dllName, qfalse )) && strcmp( cl_renderer->string, cl_renderer->resetString ) )
{
Com_Printf( "failed: trying to load fallback renderer\n" );
Cvar_ForceReset( "cl_renderer" );
Com_sprintf( dllName, sizeof( dllName ), DEFAULT_RENDER_LIBRARY "_" ARCH_STRING DLL_EXT );
rendererLib = Sys_LoadDll( dllName, qfalse );
}
if ( !rendererLib ) {
Com_Error( ERR_FATAL, "Failed to load renderer\n" );
}
memset( &ri, 0, sizeof( ri ) );
GetRefAPI = (GetRefAPI_t)Sys_LoadFunction( rendererLib, "GetRefAPI" );
if ( !GetRefAPI )
Com_Error( ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError() );
//set up the import table
ri.Printf = CL_RefPrintf;
ri.Error = Com_Error;
ri.OPrintf = Com_OPrintf;
ri.Milliseconds = Sys_Milliseconds2; //FIXME: unix+mac need this
ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
ri.Hunk_Alloc = Hunk_Alloc;
ri.Hunk_MemoryRemaining = Hunk_MemoryRemaining;
ri.Z_Malloc = Z_Malloc;
ri.Z_Free = Z_Free;
ri.Z_MemSize = Z_MemSize;
ri.Z_MorphMallocTag = Z_MorphMallocTag;
ri.Cmd_ExecuteString = Cmd_ExecuteString;
ri.Cmd_Argc = Cmd_Argc;
ri.Cmd_Argv = Cmd_Argv;
ri.Cmd_ArgsBuffer = Cmd_ArgsBuffer;
ri.Cmd_AddCommand = Cmd_AddCommand;
ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
ri.Cvar_Set = Cvar_Set;
ri.Cvar_Get = Cvar_Get;
ri.Cvar_SetValue = Cvar_SetValue;
ri.Cvar_CheckRange = Cvar_CheckRange;
ri.Cvar_VariableStringBuffer = Cvar_VariableStringBuffer;
ri.Cvar_VariableString = Cvar_VariableString;
ri.Cvar_VariableValue = Cvar_VariableValue;
ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;
ri.SE_GetString = SE_GetString;
ri.FS_FreeFile = FS_FreeFile;
ri.FS_FreeFileList = FS_FreeFileList;
ri.FS_Read = FS_Read;
ri.FS_ReadFile = FS_ReadFile;
ri.FS_FCloseFile = FS_FCloseFile;
ri.FS_FOpenFileRead = FS_FOpenFileRead;
ri.FS_FOpenFileWrite = FS_FOpenFileWrite;
ri.FS_FOpenFileByMode = FS_FOpenFileByMode;
ri.FS_FileExists = FS_FileExists;
ri.FS_FileIsInPAK = FS_FileIsInPAK;
ri.FS_ListFiles = FS_ListFiles;
ri.FS_Write = FS_Write;
ri.FS_WriteFile = FS_WriteFile;
ri.CM_BoxTrace = CM_BoxTrace;
ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
ri.CM_CullWorldBox = CM_CullWorldBox;
ri.CM_ClusterPVS = CM_ClusterPVS;
ri.CM_LeafArea = CM_LeafArea;
ri.CM_LeafCluster = CM_LeafCluster;
ri.CM_PointLeafnum = CM_PointLeafnum;
ri.CM_PointContents = CM_PointContents;
ri.Com_TheHunkMarkHasBeenMade = Com_TheHunkMarkHasBeenMade;
ri.S_RestartMusic = S_RestartMusic;
ri.SND_RegisterAudio_LevelLoadEnd = SND_RegisterAudio_LevelLoadEnd;
ri.CIN_RunCinematic = CIN_RunCinematic;
ri.CIN_PlayCinematic = CIN_PlayCinematic;
ri.CIN_UploadCinematic = CIN_UploadCinematic;
ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;
// g2 data access
ri.GetSharedMemory = GetSharedMemory;
// (c)g vm callbacks
ri.GetCurrentVM = GetCurrentVM;
ri.CGVMLoaded = CGVMLoaded;
ri.CGVM_RagCallback = CGVM_RagCallback;
ri.WIN_Init = WIN_Init;
ri.WIN_SetGamma = WIN_SetGamma;
ri.WIN_Shutdown = WIN_Shutdown;
ri.WIN_Present = WIN_Present;
ri.GL_GetProcAddress = WIN_GL_GetProcAddress;
ri.GL_ExtensionSupported = WIN_GL_ExtensionSupported;
ri.CM_GetCachedMapDiskImage = CM_GetCachedMapDiskImage;
ri.CM_SetCachedMapDiskImage = CM_SetCachedMapDiskImage;
ri.CM_SetUsingCache = CM_SetUsingCache;
//FIXME: Might have to do something about this...
ri.GetG2VertSpaceServer = GetG2VertSpaceServer;
G2VertSpaceServer = &IHeapAllocator_singleton;
ri.PD_Store = PD_Store;
ri.PD_Load = PD_Load;
ret = GetRefAPI( REF_API_VERSION, &ri );
// Com_Printf( "-------------------------------\n");
if ( !ret ) {
Com_Error (ERR_FATAL, "Couldn't initialize refresh" );
}
re = ret;
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
}
//===========================================================================================
#define MODEL_CHANGE_DELAY 5000
int gCLModelDelay = 0;
void CL_SetModel_f( void ) {
char *arg;
char name[256];
arg = Cmd_Argv( 1 );
if (arg[0])
{
/*
//If you wanted to be foolproof you would put this on the server I guess. But that
//tends to put things out of sync regarding cvar status. And I sort of doubt someone
//is going to write a client and figure out the protocol so that they can annoy people
//by changing models real fast.
int curTime = Com_Milliseconds();
if (gCLModelDelay > curTime)
{
Com_Printf("You can only change your model every %i seconds.\n", (MODEL_CHANGE_DELAY/1000));
return;
}
gCLModelDelay = curTime + MODEL_CHANGE_DELAY;
*/
//rwwFIXMEFIXME: This is currently broken and doesn't seem to work for connecting clients
Cvar_Set( "model", arg );
}
else
{
Cvar_VariableStringBuffer( "model", name, sizeof(name) );
Com_Printf("model is set to %s\n", name);
}
}
void CL_SetForcePowers_f( void ) {
return;
}
/*
==================
CL_VideoFilename
==================
*/
void CL_VideoFilename( char *buf, int bufSize ) {
time_t rawtime;
char timeStr[32] = {0}; // should really only reach ~19 chars
time( &rawtime );
strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime
Com_sprintf( buf, bufSize, "videos/video%s.avi", timeStr );
}
/*
===============
CL_Video_f
video
video [filename]
===============
*/
void CL_Video_f( void )
{
char filename[ MAX_OSPATH ];
if( !clc.demoplaying )
{
Com_Printf( "The video command can only be used when playing back demos\n" );
return;
}
if( Cmd_Argc( ) == 2 )
{
// explicit filename
Com_sprintf( filename, MAX_OSPATH, "videos/%s.avi", Cmd_Argv( 1 ) );
}
else
{
CL_VideoFilename( filename, MAX_OSPATH );
if ( FS_FileExists( filename ) ) {
Com_Printf( "Video: Couldn't create a file\n");
return;
}
}
CL_OpenAVIForWriting( filename );
}
/*
===============
CL_StopVideo_f
===============
*/
void CL_StopVideo_f( void )
{
CL_CloseAVI( );
}
static void CL_AddFavorite_f( void ) {
const bool connected = (cls.state == CA_ACTIVE) && !clc.demoplaying;
const int argc = Cmd_Argc();
if ( !connected && argc != 2 ) {
Com_Printf( "syntax: addFavorite <ip or hostname>\n" );
return;
}
const char *server = (argc == 2) ? Cmd_Argv( 1 ) : NET_AdrToString( clc.serverAddress );
const int status = LAN_AddFavAddr( server );
switch ( status ) {
case -1:
Com_Printf( "error adding favorite server: too many favorite servers\n" );
break;
case 0:
Com_Printf( "error adding favorite server: server already exists\n" );
break;
case 1:
Com_Printf( "successfully added favorite server \"%s\"\n", server );
break;
default:
Com_Printf( "unknown error (%i) adding favorite server\n", status );
break;
}
}
#define G2_VERT_SPACE_CLIENT_SIZE 256
/*
===============
CL_GenerateQKey
test to see if a valid QKEY_FILE exists. If one does not, try to generate
it by filling it with 2048 bytes of random data.
===============
*/
static void CL_GenerateQKey(void)
{
if (cl_enableGuid->integer) {
int len = 0;
unsigned char buff[ QKEY_SIZE ];
fileHandle_t f;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
if( len == QKEY_SIZE ) {
Com_Printf( "QKEY found.\n" );
return;
}
else {
if( len > 0 ) {
Com_Printf( "QKEY file size != %d, regenerating\n",
QKEY_SIZE );
}
Com_Printf( "QKEY building random string\n" );
Com_RandomBytes( buff, sizeof(buff) );
f = FS_SV_FOpenFileWrite( QKEY_FILE );
if( !f ) {
Com_Printf( "QKEY could not open %s for write\n",
QKEY_FILE );
return;
}
FS_Write( buff, sizeof(buff), f );
FS_FCloseFile( f );
Com_Printf( "QKEY generated\n" );
}
}
}
/*
====================
CL_Init
====================
*/
void CL_Init( void ) {
// Com_Printf( "----- Client Initialization -----\n" );
Con_Init ();
CL_ClearState ();
cls.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
cls.realtime = 0;
CL_InitInput ();
//
// register our variables
//
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
cl_motd = Cvar_Get ("cl_motd", "1", CVAR_ARCHIVE, "Display welcome message from master server on the bottom of connection screen" );
cl_motdServer[0] = Cvar_Get( "cl_motdServer1", UPDATE_SERVER_NAME, 0 );
cl_motdServer[1] = Cvar_Get( "cl_motdServer2", JKHUB_UPDATE_SERVER_NAME, 0 );
for ( int index = 2; index < MAX_MASTER_SERVERS; index++ )
cl_motdServer[index] = Cvar_Get( va( "cl_motdServer%d", index + 1 ), "", CVAR_ARCHIVE );
cl_timeout = Cvar_Get ("cl_timeout", "200", 0);
cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP );
cl_showSend = Cvar_Get ("cl_showSend", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP );
cl_freezeDemo = Cvar_Get ("cl_freezeDemo", "0", CVAR_TEMP );
rcon_client_password = Cvar_Get ("rconPassword", "", CVAR_TEMP, "Password for remote console access" );
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_timedemo = Cvar_Get ("timedemo", "0", 0);
cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE);
cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE);
cl_avi2GBLimit = Cvar_Get ("cl_avi2GBLimit", "1", CVAR_ARCHIVE );
cl_forceavidemo = Cvar_Get ("cl_forceavidemo", "0", 0);
rconAddress = Cvar_Get ("rconAddress", "", 0, "Alternate server address to remotely access via rcon protocol");
cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE);
cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE);
cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", CVAR_ARCHIVE);
cl_maxpackets = Cvar_Get ("cl_maxpackets", "63", CVAR_ARCHIVE );
cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE );
cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE, "Always run");
cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE, "Mouse sensitivity value");
cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE, "Mouse acceleration value");
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE, "Mouse look" );
// 0: legacy mouse acceleration
// 1: new implementation
cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE, "Mouse accelration style (0:legacy, 1:QuakeLive)" );
// offset for the power function (for style 1, ignored otherwise)
// this should be set to the max rate value
cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE, "Mouse acceleration offset for style 1" );
cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0);
cl_framerate = Cvar_Get ("cl_framerate", "0", CVAR_TEMP);
cl_allowDownload = Cvar_Get ("cl_allowDownload", "0", CVAR_ARCHIVE, "Allow downloading custom paks from server");
cl_allowAltEnter = Cvar_Get ("cl_allowAltEnter", "1", CVAR_ARCHIVE, "Enables use of ALT+ENTER keyboard combo to toggle fullscreen" );
cl_autolodscale = Cvar_Get( "cl_autolodscale", "1", CVAR_ARCHIVE );
cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0);
cl_inGameVideo = Cvar_Get ("r_inGameVideo", "1", CVAR_ARCHIVE);
cl_serverStatusResendTime = Cvar_Get ("cl_serverStatusResendTime", "750", 0);
// init autoswitch so the ui will have it correctly even
// if the cgame hasn't been started
Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE);
m_pitchVeh = Cvar_Get ("m_pitchVeh", "0.022", CVAR_ARCHIVE);
m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE);
m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE);
m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE);
m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE);
#ifdef MACOS_X
// Input is jittery on OS X w/o this
m_filter = Cvar_Get ("m_filter", "1", CVAR_ARCHIVE);
#else
m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE);
#endif
cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM );
Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE, "Max. ping for servers when searching the serverlist" );
cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE);
// enable the ja_guid player identifier in userinfo by default in OpenJK
cl_enableGuid = Cvar_Get("cl_enableGuid", "1", CVAR_ARCHIVE, "Enable GUID userinfo identifier" );
cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE, "Use a unique guid value per server" );
// ~ and `, as keys and characters
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60 0xb2", CVAR_ARCHIVE, "Which keys are used to toggle the console");
cl_consoleUseScanCode = Cvar_Get( "cl_consoleUseScanCode", "1", CVAR_ARCHIVE, "Use native console key detection" );
// userinfo
Cvar_Get ("name", "Padawan", CVAR_USERINFO | CVAR_ARCHIVE, "Player name" );
Cvar_Get ("rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE, "Data rate" );
Cvar_Get ("snaps", "40", CVAR_USERINFO | CVAR_ARCHIVE, "Client snapshots per second" );
Cvar_Get ("model", DEFAULT_MODEL"/default", CVAR_USERINFO | CVAR_ARCHIVE, "Player model" );
Cvar_Get ("forcepowers", "7-1-032330000000001333", CVAR_USERINFO | CVAR_ARCHIVE, "Player forcepowers" );
// Cvar_Get ("g_redTeam", DEFAULT_REDTEAM_NAME, CVAR_SERVERINFO | CVAR_ARCHIVE);
// Cvar_Get ("g_blueTeam", DEFAULT_BLUETEAM_NAME, CVAR_SERVERINFO | CVAR_ARCHIVE);
Cvar_Get ("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE, "Player saber1 color" );
Cvar_Get ("color2", "4", CVAR_USERINFO | CVAR_ARCHIVE, "Player saber2 color" );
Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE, "Player handicap" );
Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE, "Player sex" );
Cvar_Get ("password", "", CVAR_USERINFO, "Password to join server" );
Cvar_Get ("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE );
//default sabers
Cvar_Get ("saber1", DEFAULT_SABER, CVAR_USERINFO | CVAR_ARCHIVE, "Player default right hand saber" );
Cvar_Get ("saber2", "none", CVAR_USERINFO | CVAR_ARCHIVE, "Player left hand saber" );
//skin color
Cvar_Get ("char_color_red", "255", CVAR_USERINFO | CVAR_ARCHIVE, "Player tint (Red)" );
Cvar_Get ("char_color_green", "255", CVAR_USERINFO | CVAR_ARCHIVE, "Player tint (Green)" );
Cvar_Get ("char_color_blue", "255", CVAR_USERINFO | CVAR_ARCHIVE, "Player tint (Blue)" );
// cgame might not be initialized before menu is used
Cvar_Get ("cg_viewsize", "100", CVAR_ARCHIVE );
//
// register our commands
//
Cmd_AddCommand ("cmd", CL_ForwardToServer_f, "Forward command to server" );
Cmd_AddCommand ("globalservers", CL_GlobalServers_f, "Query the masterserver for serverlist" );
Cmd_AddCommand( "addFavorite", CL_AddFavorite_f, "Add server to favorites" );
Cmd_AddCommand ("record", CL_Record_f, "Record a demo" );
Cmd_AddCommand ("demo", CL_PlayDemo_f, "Playback a demo" );
Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName );
Cmd_AddCommand ("stoprecord", CL_StopRecord_f, "Stop recording a demo" );
Cmd_AddCommand ("configstrings", CL_Configstrings_f, "Prints the configstrings list" );
Cmd_AddCommand ("clientinfo", CL_Clientinfo_f, "Prints the userinfo variables" );
Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f, "Restart sound" );
Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f, "Restart the renderer - or change the resolution" );
Cmd_AddCommand ("disconnect", CL_Disconnect_f, "Disconnect from current server" );
Cmd_AddCommand ("cinematic", CL_PlayCinematic_f, "Play a cinematic video" );
Cmd_AddCommand ("connect", CL_Connect_f, "Connect to a server" );
Cmd_AddCommand ("reconnect", CL_Reconnect_f, "Reconnect to current server" );
Cmd_AddCommand ("localservers", CL_LocalServers_f, "Query LAN for local servers" );
Cmd_AddCommand ("rcon", CL_Rcon_f, "Execute commands remotely to a server" );
Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon );
Cmd_AddCommand ("ping", CL_Ping_f, "Ping a server for info response" );
Cmd_AddCommand ("serverstatus", CL_ServerStatus_f, "Retrieve current or specified server's status" );
Cmd_AddCommand ("showip", CL_ShowIP_f, "Shows local IP" );
Cmd_AddCommand ("fs_openedList", CL_OpenedPK3List_f, "Lists open pak files" );
Cmd_AddCommand ("fs_referencedList", CL_ReferencedPK3List_f, "Lists referenced pak files" );
Cmd_AddCommand ("model", CL_SetModel_f, "Set the player model" );
Cmd_AddCommand ("forcepowers", CL_SetForcePowers_f );
Cmd_AddCommand ("video", CL_Video_f, "Record demo to avi" );
Cmd_AddCommand ("stopvideo", CL_StopVideo_f, "Stop avi recording" );
CL_InitRef();
SCR_Init ();
Cbuf_Execute ();
Cvar_Set( "cl_running", "1" );
G2VertSpaceClient = new CMiniHeap (G2_VERT_SPACE_CLIENT_SIZE * 1024);
CL_GenerateQKey();
CL_UpdateGUID( NULL, 0 );
// Com_Printf( "----- Client Initialization Complete -----\n" );
}
/*
===============
CL_Shutdown
===============
*/
void CL_Shutdown( void ) {
static qboolean recursive = qfalse;
//Com_Printf( "----- CL_Shutdown -----\n" );
if ( recursive ) {
printf ("recursive CL_Shutdown shutdown\n");
return;
}
recursive = qtrue;
if (G2VertSpaceClient)
{
delete G2VertSpaceClient;
G2VertSpaceClient = 0;
}
CL_Disconnect( qtrue );
// RJ: added the shutdown all to close down the cgame (to free up some memory, such as in the fx system)
CL_ShutdownAll( qtrue );
S_Shutdown();
//CL_ShutdownUI();
Cmd_RemoveCommand ("cmd");
Cmd_RemoveCommand ("configstrings");
Cmd_RemoveCommand ("clientinfo");
Cmd_RemoveCommand ("snd_restart");
Cmd_RemoveCommand ("vid_restart");
Cmd_RemoveCommand ("disconnect");
Cmd_RemoveCommand ("record");
Cmd_RemoveCommand ("demo");
Cmd_RemoveCommand ("cinematic");
Cmd_RemoveCommand ("stoprecord");
Cmd_RemoveCommand ("connect");
Cmd_RemoveCommand ("reconnect");
Cmd_RemoveCommand ("localservers");
Cmd_RemoveCommand ("globalservers");
Cmd_RemoveCommand( "addFavorite" );
Cmd_RemoveCommand ("rcon");
Cmd_RemoveCommand ("ping");
Cmd_RemoveCommand ("serverstatus");
Cmd_RemoveCommand ("showip");
Cmd_RemoveCommand ("fs_openedList");
Cmd_RemoveCommand ("fs_referencedList");
Cmd_RemoveCommand ("model");
Cmd_RemoveCommand ("forcepowers");
Cmd_RemoveCommand ("video");
Cmd_RemoveCommand ("stopvideo");
CL_ShutdownInput();
Con_Shutdown();
Cvar_Set( "cl_running", "0" );
recursive = qfalse;
Com_Memset( &cls, 0, sizeof( cls ) );
Key_SetCatcher( 0 );
//Com_Printf( "-----------------------\n" );
}
qboolean CL_ConnectedToRemoteServer( void ) {
return (qboolean)( com_sv_running && !com_sv_running->integer && cls.state >= CA_CONNECTED && !clc.demoplaying );
}
static void CL_SetServerInfo(serverInfo_t *server, const char *info, int ping) {
if (server) {
if (info) {
server->clients = atoi(Info_ValueForKey(info, "clients"));
Q_strncpyz(server->hostName,Info_ValueForKey(info, "hostname"), MAX_NAME_LENGTH);
Q_strncpyz(server->mapName, Info_ValueForKey(info, "mapname"), MAX_NAME_LENGTH);
server->maxClients = atoi(Info_ValueForKey(info, "sv_maxclients"));
Q_strncpyz(server->game,Info_ValueForKey(info, "game"), MAX_NAME_LENGTH);
server->gameType = atoi(Info_ValueForKey(info, "gametype"));
server->netType = atoi(Info_ValueForKey(info, "nettype"));
server->minPing = atoi(Info_ValueForKey(info, "minping"));
server->maxPing = atoi(Info_ValueForKey(info, "maxping"));
// server->allowAnonymous = atoi(Info_ValueForKey(info, "sv_allowAnonymous"));
server->needPassword = (qboolean)atoi(Info_ValueForKey(info, "needpass" ));
server->trueJedi = atoi(Info_ValueForKey(info, "truejedi" ));
server->weaponDisable = atoi(Info_ValueForKey(info, "wdisable" ));
server->forceDisable = atoi(Info_ValueForKey(info, "fdisable" ));
server->humans = atoi( Info_ValueForKey( info, "g_humanplayers" ) );
server->bots = atoi( Info_ValueForKey( info, "bots" ) );
// server->pure = (qboolean)atoi(Info_ValueForKey(info, "pure" ));
}
server->ping = ping;
}
}
static void CL_SetServerInfoByAddress(netadr_t from, const char *info, int ping) {
int i;
for (i = 0; i < MAX_OTHER_SERVERS; i++) {
if (NET_CompareAdr(from, cls.localServers[i].adr)) {
CL_SetServerInfo(&cls.localServers[i], info, ping);
}
}
for (i = 0; i < MAX_GLOBAL_SERVERS; i++) {
if (NET_CompareAdr(from, cls.globalServers[i].adr)) {
CL_SetServerInfo(&cls.globalServers[i], info, ping);
}
}
for (i = 0; i < MAX_OTHER_SERVERS; i++) {
if (NET_CompareAdr(from, cls.favoriteServers[i].adr)) {
CL_SetServerInfo(&cls.favoriteServers[i], info, ping);
}
}
}
/*
===================
CL_ServerInfoPacket
===================
*/
void CL_ServerInfoPacket( netadr_t from, msg_t *msg ) {
int i, type;
char info[MAX_INFO_STRING];
char *infoString;
int prot;
infoString = MSG_ReadString( msg );
// if this isn't the correct protocol version, ignore it
prot = atoi( Info_ValueForKey( infoString, "protocol" ) );
if ( prot != PROTOCOL_VERSION ) {
Com_DPrintf( "Different protocol info packet: %s\n", infoString );
return;
}
// iterate servers waiting for ping response
for (i=0; i<MAX_PINGREQUESTS; i++)
{
if ( cl_pinglist[i].adr.port && !cl_pinglist[i].time && NET_CompareAdr( from, cl_pinglist[i].adr ) )
{
// calc ping time
cl_pinglist[i].time = Sys_Milliseconds() - cl_pinglist[i].start;
Com_DPrintf( "ping time %dms from %s\n", cl_pinglist[i].time, NET_AdrToString( from ) );
// save of info
Q_strncpyz( cl_pinglist[i].info, infoString, sizeof( cl_pinglist[i].info ) );
// tack on the net type
// NOTE: make sure these types are in sync with the netnames strings in the UI
switch (from.type)
{
case NA_BROADCAST:
case NA_IP:
type = 1;
break;
default:
type = 0;
break;
}
Info_SetValueForKey( cl_pinglist[i].info, "nettype", va("%d", type) );
CL_SetServerInfoByAddress(from, infoString, cl_pinglist[i].time);
return;
}
}
// if not just sent a local broadcast or pinging local servers
if (cls.pingUpdateSource != AS_LOCAL) {
return;
}
for ( i = 0 ; i < MAX_OTHER_SERVERS ; i++ ) {
// empty slot
if ( cls.localServers[i].adr.port == 0 ) {
break;
}
// avoid duplicate
if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) {
return;
}
}
if ( i == MAX_OTHER_SERVERS ) {
Com_DPrintf( "MAX_OTHER_SERVERS hit, dropping infoResponse\n" );
return;
}
// add this to the list
cls.numlocalservers = i+1;
CL_InitServerInfo( &cls.localServers[i], &from );
Q_strncpyz( info, MSG_ReadString( msg ), MAX_INFO_STRING );
if (strlen(info)) {
if (info[strlen(info)-1] != '\n') {
strncat(info, "\n", sizeof(info) -1);
}
Com_Printf( "%s: %s", NET_AdrToString( from ), info );
}
}
/*
===================
CL_GetServerStatus
===================
*/
serverStatus_t *CL_GetServerStatus( netadr_t from ) {
int i, oldest, oldestTime;
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
return &cl_serverStatusList[i];
}
}
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
if ( cl_serverStatusList[i].retrieved ) {
return &cl_serverStatusList[i];
}
}
oldest = -1;
oldestTime = 0;
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
if (oldest == -1 || cl_serverStatusList[i].startTime < oldestTime) {
oldest = i;
oldestTime = cl_serverStatusList[i].startTime;
}
}
if (oldest != -1) {
return &cl_serverStatusList[oldest];
}
serverStatusCount++;
return &cl_serverStatusList[serverStatusCount & (MAX_SERVERSTATUSREQUESTS-1)];
}
/*
===================
CL_ServerStatus
===================
*/
int CL_ServerStatus( const char *serverAddress, char *serverStatusString, int maxLen ) {
int i;
netadr_t to;
serverStatus_t *serverStatus;
// if no server address then reset all server status requests
if ( !serverAddress ) {
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
cl_serverStatusList[i].address.port = 0;
cl_serverStatusList[i].retrieved = qtrue;
}
return qfalse;
}
// get the address
if ( !NET_StringToAdr( serverAddress, &to ) ) {
return qfalse;
}
serverStatus = CL_GetServerStatus( to );
// if no server status string then reset the server status request for this address
if ( !serverStatusString ) {
serverStatus->retrieved = qtrue;
return qfalse;
}
// if this server status request has the same address
if ( NET_CompareAdr( to, serverStatus->address) ) {
// if we received a response for this server status request
if (!serverStatus->pending) {
Q_strncpyz(serverStatusString, serverStatus->string, maxLen);
serverStatus->retrieved = qtrue;
serverStatus->startTime = 0;
return qtrue;
}
// resend the request regularly
else if ( serverStatus->startTime < Com_Milliseconds() - cl_serverStatusResendTime->integer ) {
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->time = 0;
serverStatus->startTime = Com_Milliseconds();
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
}
// if retrieved
else if ( serverStatus->retrieved ) {
serverStatus->address = to;
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->startTime = Com_Milliseconds();
serverStatus->time = 0;
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
return qfalse;
}
/*
===================
CL_ServerStatusResponse
===================
*/
void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) {
char *s;
char info[MAX_INFO_STRING];
int i, l, score, ping;
int len;
serverStatus_t *serverStatus;
serverStatus = NULL;
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
serverStatus = &cl_serverStatusList[i];
break;
}
}
// if we didn't request this server status
if (!serverStatus) {
return;
}
s = MSG_ReadStringLine( msg );
len = 0;
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "%s", s);
if (serverStatus->print) {
Com_Printf( "Server (%s)\n",
NET_AdrToString( serverStatus->address ) );
Com_Printf("Server settings:\n");
// print cvars
while (*s) {
for (i = 0; i < 2 && *s; i++) {
if (*s == '\\')
s++;
l = 0;
while (*s) {
info[l++] = *s;
if (l >= MAX_INFO_STRING-1)
break;
s++;
if (*s == '\\') {
break;
}
}
info[l] = '\0';
if (i) {
Com_Printf("%s\n", info);
}
else {
Com_Printf("%-24s", info);
}
}
}
}
len = strlen(serverStatus->string);
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\");
if (serverStatus->print) {
Com_Printf("\nPlayers:\n");
Com_Printf("num: score: ping: name:\n");
}
for (i = 0, s = MSG_ReadStringLine( msg ); *s; s = MSG_ReadStringLine( msg ), i++) {
len = strlen(serverStatus->string);
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\%s", s);
if (serverStatus->print) {
score = ping = 0;
sscanf(s, "%d %d", &score, &ping);
s = strchr(s, ' ');
if (s)
s = strchr(s+1, ' ');
if (s)
s++;
else
s = "unknown";
Com_Printf("%-2d %-3d %-3d %s\n", i, score, ping, s );
}
}
len = strlen(serverStatus->string);
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\");
serverStatus->time = Com_Milliseconds();
serverStatus->address = from;
serverStatus->pending = qfalse;
if (serverStatus->print) {
serverStatus->retrieved = qtrue;
}
}
/*
==================
CL_LocalServers_f
==================
*/
void CL_LocalServers_f( void ) {
char *message;
int i, j;
netadr_t to;
Com_Printf( "Scanning for servers on the local network...\n");
// reset the list, waiting for response
cls.numlocalservers = 0;
cls.pingUpdateSource = AS_LOCAL;
for (i = 0; i < MAX_OTHER_SERVERS; i++) {
qboolean b = cls.localServers[i].visible;
Com_Memset(&cls.localServers[i], 0, sizeof(cls.localServers[i]));
cls.localServers[i].visible = b;
}
Com_Memset( &to, 0, sizeof( to ) );
// The 'xxx' in the message is a challenge that will be echoed back
// by the server. We don't care about that here, but master servers
// can use that to prevent spoofed server responses from invalid ip
message = "\377\377\377\377getinfo xxx";
// send each message twice in case one is dropped
for ( i = 0 ; i < 2 ; i++ ) {
// send a broadcast packet on each server port
// we support multiple server ports so a single machine
// can nicely run multiple servers
for ( j = 0 ; j < NUM_SERVER_PORTS ; j++ ) {
to.port = BigShort( (short)(PORT_SERVER + j) );
to.type = NA_BROADCAST;
NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
}
}
}
/*
==================
CL_GlobalServers_f
==================
*/
void CL_GlobalServers_f( void ) {
netadr_t to;
int count, i, masterNum;
char command[1024], *masteraddress;
if ((count = Cmd_Argc()) < 3 || (masterNum = atoi(Cmd_Argv(1))) < 0 || masterNum > MAX_MASTER_SERVERS - 1)
{
Com_Printf("usage: globalservers <master# 0-%d> <protocol> [keywords]\n", MAX_MASTER_SERVERS - 1);
return;
}
Com_sprintf( command, sizeof(command), "sv_master%d", masterNum + 1 );
masteraddress = Cvar_VariableString( command );
if ( !*masteraddress )
{
Com_Printf( "CL_GlobalServers_f: Error: No master server address given.\n" );
return;
}
// reset the list, waiting for response
// -1 is used to distinguish a "no response"
i = NET_StringToAdr( masteraddress, &to );
if (!i)
{
Com_Printf( "CL_GlobalServers_f: Error: could not resolve address of master %s\n", masteraddress );
return;
}
to.type = NA_IP;
to.port = BigShort(PORT_MASTER);
Com_Printf( "Requesting servers from the master %s (%s)...\n", masteraddress, NET_AdrToString( to ) );
cls.numglobalservers = -1;
cls.pingUpdateSource = AS_GLOBAL;
Com_sprintf(command, sizeof(command), "getservers %s", Cmd_Argv(2));
// tack on keywords
for (i = 3; i < count; i++)
{
Q_strcat(command, sizeof(command), " ");
Q_strcat(command, sizeof(command), Cmd_Argv(i));
}
NET_OutOfBandPrint( NS_SERVER, to, "%s", command );
}
/*
==================
CL_GetPing
==================
*/
void CL_GetPing( int n, char *buf, int buflen, int *pingtime )
{
const char *str;
int time;
int maxPing;
if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port)
{
// empty or invalid slot
buf[0] = '\0';
*pingtime = 0;
return;
}
str = NET_AdrToString( cl_pinglist[n].adr );
Q_strncpyz( buf, str, buflen );
time = cl_pinglist[n].time;
if (!time)
{
// check for timeout
time = Sys_Milliseconds() - cl_pinglist[n].start;
maxPing = Cvar_VariableIntegerValue( "cl_maxPing" );
if( maxPing < 100 ) {
maxPing = 100;
}
if (time < maxPing)
{
// not timed out yet
time = 0;
}
}
CL_SetServerInfoByAddress(cl_pinglist[n].adr, cl_pinglist[n].info, cl_pinglist[n].time);
*pingtime = time;
}
/*
==================
CL_GetPingInfo
==================
*/
void CL_GetPingInfo( int n, char *buf, int buflen )
{
if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port)
{
// empty or invalid slot
if (buflen)
buf[0] = '\0';
return;
}
Q_strncpyz( buf, cl_pinglist[n].info, buflen );
}
/*
==================
CL_ClearPing
==================
*/
void CL_ClearPing( int n )
{
if (n < 0 || n >= MAX_PINGREQUESTS)
return;
cl_pinglist[n].adr.port = 0;
}
/*
==================
CL_GetPingQueueCount
==================
*/
int CL_GetPingQueueCount( void )
{
int i;
int count;
ping_t* pingptr;
count = 0;
pingptr = cl_pinglist;
for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ ) {
if (pingptr->adr.port) {
count++;
}
}
return (count);
}
/*
==================
CL_GetFreePing
==================
*/
ping_t* CL_GetFreePing( void )
{
ping_t* pingptr;
ping_t* best;
int oldest;
int i;
int time;
pingptr = cl_pinglist;
for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ )
{
// find free ping slot
if (pingptr->adr.port)
{
if (!pingptr->time)
{
if (Sys_Milliseconds() - pingptr->start < 500)
{
// still waiting for response
continue;
}
}
else if (pingptr->time < 500)
{
// results have not been queried
continue;
}
}
// clear it
pingptr->adr.port = 0;
return (pingptr);
}
// use oldest entry
pingptr = cl_pinglist;
best = cl_pinglist;
oldest = INT_MIN;
for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ )
{
// scan for oldest
time = Sys_Milliseconds() - pingptr->start;
if (time > oldest)
{
oldest = time;
best = pingptr;
}
}
return (best);
}
/*
==================
CL_Ping_f
==================
*/
void CL_Ping_f( void ) {
netadr_t to;
ping_t* pingptr;
char* server;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: ping [server]\n");
return;
}
Com_Memset( &to, 0, sizeof(netadr_t) );
server = Cmd_Argv(1);
if ( !NET_StringToAdr( server, &to ) ) {
return;
}
pingptr = CL_GetFreePing();
memcpy( &pingptr->adr, &to, sizeof (netadr_t) );
pingptr->start = Sys_Milliseconds();
pingptr->time = 0;
CL_SetServerInfoByAddress(pingptr->adr, NULL, 0);
NET_OutOfBandPrint( NS_CLIENT, to, "getinfo xxx" );
}
/*
==================
CL_UpdateVisiblePings_f
==================
*/
qboolean CL_UpdateVisiblePings_f(int source) {
int slots, i;
char buff[MAX_STRING_CHARS];
int pingTime;
int max;
qboolean status = qfalse;
if (source < 0 || source > AS_FAVORITES) {
return qfalse;
}
cls.pingUpdateSource = source;
slots = CL_GetPingQueueCount();
if (slots < MAX_PINGREQUESTS) {
serverInfo_t *server = NULL;
switch (source) {
case AS_LOCAL :
server = &cls.localServers[0];
max = cls.numlocalservers;
break;
case AS_GLOBAL :
server = &cls.globalServers[0];
max = cls.numglobalservers;
break;
case AS_FAVORITES :
server = &cls.favoriteServers[0];
max = cls.numfavoriteservers;
break;
default:
return qfalse;
}
for (i = 0; i < max; i++) {
if (server[i].visible) {
if (server[i].ping == -1) {
int j;
if (slots >= MAX_PINGREQUESTS) {
break;
}
for (j = 0; j < MAX_PINGREQUESTS; j++) {
if (!cl_pinglist[j].adr.port) {
continue;
}
if (NET_CompareAdr( cl_pinglist[j].adr, server[i].adr)) {
// already on the list
break;
}
}
if (j >= MAX_PINGREQUESTS) {
status = qtrue;
for (j = 0; j < MAX_PINGREQUESTS; j++) {
if (!cl_pinglist[j].adr.port) {
break;
}
}
memcpy(&cl_pinglist[j].adr, &server[i].adr, sizeof(netadr_t));
cl_pinglist[j].start = Sys_Milliseconds();
cl_pinglist[j].time = 0;
NET_OutOfBandPrint( NS_CLIENT, cl_pinglist[j].adr, "getinfo xxx" );
slots++;
}
}
// if the server has a ping higher than cl_maxPing or
// the ping packet got lost
else if (server[i].ping == 0) {
// if we are updating global servers
if (source == AS_GLOBAL) {
//
if ( cls.numGlobalServerAddresses > 0 ) {
// overwrite this server with one from the additional global servers
cls.numGlobalServerAddresses--;
CL_InitServerInfo(&server[i], &cls.globalServerAddresses[cls.numGlobalServerAddresses]);
// NOTE: the server[i].visible flag stays untouched
}
}
}
}
}
}
if (slots) {
status = qtrue;
}
for (i = 0; i < MAX_PINGREQUESTS; i++) {
if (!cl_pinglist[i].adr.port) {
continue;
}
CL_GetPing( i, buff, MAX_STRING_CHARS, &pingTime );
if (pingTime != 0) {
CL_ClearPing(i);
status = qtrue;
}
}
return status;
}
/*
==================
CL_ServerStatus_f
==================
*/
void CL_ServerStatus_f(void) {
netadr_t to, *toptr = NULL;
char *server;
serverStatus_t *serverStatus;
if ( Cmd_Argc() != 2 ) {
if ( cls.state != CA_ACTIVE || clc.demoplaying ) {
Com_Printf ("Not connected to a server.\n");
Com_Printf( "Usage: serverstatus [server]\n");
return;
}
toptr = &clc.serverAddress;
}
if(!toptr)
{
Com_Memset( &to, 0, sizeof(netadr_t) );
server = Cmd_Argv(1);
toptr = &to;
if ( !NET_StringToAdr( server, toptr ) )
return;
}
NET_OutOfBandPrint( NS_CLIENT, *toptr, "getstatus" );
serverStatus = CL_GetServerStatus( *toptr );
serverStatus->address = *toptr;
serverStatus->print = qtrue;
serverStatus->pending = qtrue;
}
/*
==================
CL_ShowIP_f
==================
*/
void CL_ShowIP_f(void) {
Sys_ShowIP();
}
| ./CrossVul/dataset_final_sorted/CWE-269/cpp/bad_3234_2 |
crossvul-cpp_data_good_1350_0 | #include "CMOS.h"
#include "Process.h"
#include "StdLib.h"
#include <AK/Assertions.h>
#include <AK/kstdio.h>
#include <Kernel/Arch/i386/CPU.h>
#include <Kernel/FileSystem/Inode.h>
#include <Kernel/Multiboot.h>
#include <Kernel/VM/AnonymousVMObject.h>
#include <Kernel/VM/InodeVMObject.h>
#include <Kernel/VM/MemoryManager.h>
#include <Kernel/VM/PurgeableVMObject.h>
//#define MM_DEBUG
//#define PAGE_FAULT_DEBUG
static MemoryManager* s_the;
MemoryManager& MM
{
return *s_the;
}
MemoryManager::MemoryManager(u32 physical_address_for_kernel_page_tables)
{
CPUID id(0x80000001);
m_has_nx_support = (id.edx() & (1 << 20)) != 0;
m_kernel_page_directory = PageDirectory::create_at_fixed_address(PhysicalAddress(physical_address_for_kernel_page_tables));
for (size_t i = 0; i < 4; ++i) {
m_low_page_tables[i] = (PageTableEntry*)(physical_address_for_kernel_page_tables + PAGE_SIZE * (5 + i));
memset(m_low_page_tables[i], 0, PAGE_SIZE);
}
initialize_paging();
kprintf("MM initialized.\n");
}
MemoryManager::~MemoryManager()
{
}
void MemoryManager::initialize_paging()
{
#ifdef MM_DEBUG
dbgprintf("MM: Kernel page directory @ %p\n", kernel_page_directory().cr3());
#endif
#ifdef MM_DEBUG
dbgprintf("MM: Protect against null dereferences\n");
#endif
// Make null dereferences crash.
map_protected(VirtualAddress(0), PAGE_SIZE);
#ifdef MM_DEBUG
dbgprintf("MM: Identity map bottom 8MB\n");
#endif
// The bottom 8 MB (except for the null page) are identity mapped & supervisor only.
// Every process shares these mappings.
create_identity_mapping(kernel_page_directory(), VirtualAddress(PAGE_SIZE), (8 * MB) - PAGE_SIZE);
// Disable execution from 0MB through 1MB (BIOS data, legacy things, ...)
for (size_t i = 0; i < (1 * MB); ++i) {
auto& pte = ensure_pte(kernel_page_directory(), VirtualAddress(i));
if (m_has_nx_support)
pte.set_execute_disabled(true);
}
// Disable execution from 2MB through 8MB (kmalloc, kmalloc_eternal, slabs, page tables, ...)
for (size_t i = 1; i < 4; ++i) {
auto& pte = kernel_page_directory().table().directory(0)[i];
if (m_has_nx_support)
pte.set_execute_disabled(true);
}
// FIXME: We should move everything kernel-related above the 0xc0000000 virtual mark.
// Basic physical memory map:
// 0 -> 1 MB We're just leaving this alone for now.
// 1 -> 3 MB Kernel image.
// (last page before 2MB) Used by quickmap_page().
// 2 MB -> 4 MB kmalloc_eternal() space.
// 4 MB -> 7 MB kmalloc() space.
// 7 MB -> 8 MB Supervisor physical pages (available for allocation!)
// 8 MB -> MAX Userspace physical pages (available for allocation!)
// Basic virtual memory map:
// 0 -> 4 KB Null page (so nullptr dereferences crash!)
// 4 KB -> 8 MB Identity mapped.
// 8 MB -> 3 GB Available to userspace.
// 3GB -> 4 GB Kernel-only virtual address space (>0xc0000000)
#ifdef MM_DEBUG
dbgprintf("MM: Quickmap will use %p\n", m_quickmap_addr.get());
#endif
m_quickmap_addr = VirtualAddress((2 * MB) - PAGE_SIZE);
RefPtr<PhysicalRegion> region;
bool region_is_super = false;
for (auto* mmap = (multiboot_memory_map_t*)multiboot_info_ptr->mmap_addr; (unsigned long)mmap < multiboot_info_ptr->mmap_addr + multiboot_info_ptr->mmap_length; mmap = (multiboot_memory_map_t*)((unsigned long)mmap + mmap->size + sizeof(mmap->size))) {
kprintf("MM: Multiboot mmap: base_addr = 0x%x%08x, length = 0x%x%08x, type = 0x%x\n",
(u32)(mmap->addr >> 32),
(u32)(mmap->addr & 0xffffffff),
(u32)(mmap->len >> 32),
(u32)(mmap->len & 0xffffffff),
(u32)mmap->type);
if (mmap->type != MULTIBOOT_MEMORY_AVAILABLE)
continue;
// FIXME: Maybe make use of stuff below the 1MB mark?
if (mmap->addr < (1 * MB))
continue;
if ((mmap->addr + mmap->len) > 0xffffffff)
continue;
auto diff = (u32)mmap->addr % PAGE_SIZE;
if (diff != 0) {
kprintf("MM: got an unaligned region base from the bootloader; correcting %p by %d bytes\n", mmap->addr, diff);
diff = PAGE_SIZE - diff;
mmap->addr += diff;
mmap->len -= diff;
}
if ((mmap->len % PAGE_SIZE) != 0) {
kprintf("MM: got an unaligned region length from the bootloader; correcting %d by %d bytes\n", mmap->len, mmap->len % PAGE_SIZE);
mmap->len -= mmap->len % PAGE_SIZE;
}
if (mmap->len < PAGE_SIZE) {
kprintf("MM: memory region from bootloader is too small; we want >= %d bytes, but got %d bytes\n", PAGE_SIZE, mmap->len);
continue;
}
#ifdef MM_DEBUG
kprintf("MM: considering memory at %p - %p\n",
(u32)mmap->addr, (u32)(mmap->addr + mmap->len));
#endif
for (size_t page_base = mmap->addr; page_base < (mmap->addr + mmap->len); page_base += PAGE_SIZE) {
auto addr = PhysicalAddress(page_base);
if (page_base < 7 * MB) {
// nothing
} else if (page_base >= 7 * MB && page_base < 8 * MB) {
if (region.is_null() || !region_is_super || region->upper().offset(PAGE_SIZE) != addr) {
m_super_physical_regions.append(PhysicalRegion::create(addr, addr));
region = m_super_physical_regions.last();
region_is_super = true;
} else {
region->expand(region->lower(), addr);
}
} else {
if (region.is_null() || region_is_super || region->upper().offset(PAGE_SIZE) != addr) {
m_user_physical_regions.append(PhysicalRegion::create(addr, addr));
region = m_user_physical_regions.last();
region_is_super = false;
} else {
region->expand(region->lower(), addr);
}
}
}
}
for (auto& region : m_super_physical_regions)
m_super_physical_pages += region.finalize_capacity();
for (auto& region : m_user_physical_regions)
m_user_physical_pages += region.finalize_capacity();
#ifdef MM_DEBUG
dbgprintf("MM: Installing page directory\n");
#endif
// Turn on CR4.PGE so the CPU will respect the G bit in page tables.
asm volatile(
"mov %cr4, %eax\n"
"orl $0x80, %eax\n"
"mov %eax, %cr4\n");
// Turn on CR4.PAE
asm volatile(
"mov %cr4, %eax\n"
"orl $0x20, %eax\n"
"mov %eax, %cr4\n");
if (m_has_nx_support) {
kprintf("MM: NX support detected; enabling NXE flag\n");
// Turn on IA32_EFER.NXE
asm volatile(
"movl $0xc0000080, %ecx\n"
"rdmsr\n"
"orl $0x800, %eax\n"
"wrmsr\n");
} else {
kprintf("MM: NX support not detected\n");
}
asm volatile("movl %%eax, %%cr3" ::"a"(kernel_page_directory().cr3()));
asm volatile(
"movl %%cr0, %%eax\n"
"orl $0x80010001, %%eax\n"
"movl %%eax, %%cr0\n" ::
: "%eax", "memory");
#ifdef MM_DEBUG
dbgprintf("MM: Paging initialized.\n");
#endif
}
PageTableEntry& MemoryManager::ensure_pte(PageDirectory& page_directory, VirtualAddress vaddr)
{
ASSERT_INTERRUPTS_DISABLED();
u32 page_directory_table_index = (vaddr.get() >> 30) & 0x3;
u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
PageDirectoryEntry& pde = page_directory.table().directory(page_directory_table_index)[page_directory_index];
if (!pde.is_present()) {
#ifdef MM_DEBUG
dbgprintf("MM: PDE %u not present (requested for V%p), allocating\n", page_directory_index, vaddr.get());
#endif
if (page_directory_table_index == 0 && page_directory_index < 4) {
ASSERT(&page_directory == m_kernel_page_directory);
pde.set_page_table_base((u32)m_low_page_tables[page_directory_index]);
pde.set_user_allowed(false);
pde.set_present(true);
pde.set_writable(true);
pde.set_global(true);
} else {
auto page_table = allocate_supervisor_physical_page();
#ifdef MM_DEBUG
dbgprintf("MM: PD K%p (%s) at P%p allocated page table #%u (for V%p) at P%p\n",
&page_directory,
&page_directory == m_kernel_page_directory ? "Kernel" : "User",
page_directory.cr3(),
page_directory_index,
vaddr.get(),
page_table->paddr().get());
#endif
pde.set_page_table_base(page_table->paddr().get());
pde.set_user_allowed(true);
pde.set_present(true);
pde.set_writable(true);
pde.set_global(&page_directory == m_kernel_page_directory.ptr());
page_directory.m_physical_pages.set(page_directory_index, move(page_table));
}
}
return pde.page_table_base()[page_table_index];
}
void MemoryManager::map_protected(VirtualAddress vaddr, size_t length)
{
InterruptDisabler disabler;
ASSERT(vaddr.is_page_aligned());
for (u32 offset = 0; offset < length; offset += PAGE_SIZE) {
auto pte_address = vaddr.offset(offset);
auto& pte = ensure_pte(kernel_page_directory(), pte_address);
pte.set_physical_page_base(pte_address.get());
pte.set_user_allowed(false);
pte.set_present(false);
pte.set_writable(false);
flush_tlb(pte_address);
}
}
void MemoryManager::create_identity_mapping(PageDirectory& page_directory, VirtualAddress vaddr, size_t size)
{
InterruptDisabler disabler;
ASSERT((vaddr.get() & ~PAGE_MASK) == 0);
for (u32 offset = 0; offset < size; offset += PAGE_SIZE) {
auto pte_address = vaddr.offset(offset);
auto& pte = ensure_pte(page_directory, pte_address);
pte.set_physical_page_base(pte_address.get());
pte.set_user_allowed(false);
pte.set_present(true);
pte.set_writable(true);
page_directory.flush(pte_address);
}
}
void MemoryManager::initialize(u32 physical_address_for_kernel_page_tables)
{
s_the = new MemoryManager(physical_address_for_kernel_page_tables);
}
Region* MemoryManager::kernel_region_from_vaddr(VirtualAddress vaddr)
{
if (vaddr.get() < 0xc0000000)
return nullptr;
for (auto& region : MM.m_kernel_regions) {
if (region.contains(vaddr))
return ®ion;
}
return nullptr;
}
Region* MemoryManager::user_region_from_vaddr(Process& process, VirtualAddress vaddr)
{
// FIXME: Use a binary search tree (maybe red/black?) or some other more appropriate data structure!
for (auto& region : process.m_regions) {
if (region.contains(vaddr))
return ®ion;
}
dbg() << process << " Couldn't find user region for " << vaddr;
return nullptr;
}
Region* MemoryManager::region_from_vaddr(Process& process, VirtualAddress vaddr)
{
if (auto* region = kernel_region_from_vaddr(vaddr))
return region;
return user_region_from_vaddr(process, vaddr);
}
const Region* MemoryManager::region_from_vaddr(const Process& process, VirtualAddress vaddr)
{
if (auto* region = kernel_region_from_vaddr(vaddr))
return region;
return user_region_from_vaddr(const_cast<Process&>(process), vaddr);
}
Region* MemoryManager::region_from_vaddr(VirtualAddress vaddr)
{
if (auto* region = kernel_region_from_vaddr(vaddr))
return region;
auto page_directory = PageDirectory::find_by_cr3(cpu_cr3());
if (!page_directory)
return nullptr;
ASSERT(page_directory->process());
return user_region_from_vaddr(*page_directory->process(), vaddr);
}
PageFaultResponse MemoryManager::handle_page_fault(const PageFault& fault)
{
ASSERT_INTERRUPTS_DISABLED();
ASSERT(current);
#ifdef PAGE_FAULT_DEBUG
dbgprintf("MM: handle_page_fault(%w) at V%p\n", fault.code(), fault.vaddr().get());
#endif
ASSERT(fault.vaddr() != m_quickmap_addr);
auto* region = region_from_vaddr(fault.vaddr());
if (!region) {
kprintf("NP(error) fault at invalid address V%p\n", fault.vaddr().get());
return PageFaultResponse::ShouldCrash;
}
return region->handle_fault(fault);
}
OwnPtr<Region> MemoryManager::allocate_kernel_region(size_t size, const StringView& name, u8 access, bool user_accessible, bool should_commit)
{
InterruptDisabler disabler;
ASSERT(!(size % PAGE_SIZE));
auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
ASSERT(range.is_valid());
OwnPtr<Region> region;
if (user_accessible)
region = Region::create_user_accessible(range, name, access);
else
region = Region::create_kernel_only(range, name, access);
region->map(kernel_page_directory());
// FIXME: It would be cool if these could zero-fill on demand instead.
if (should_commit)
region->commit();
return region;
}
OwnPtr<Region> MemoryManager::allocate_user_accessible_kernel_region(size_t size, const StringView& name, u8 access)
{
return allocate_kernel_region(size, name, access, true);
}
OwnPtr<Region> MemoryManager::allocate_kernel_region_with_vmobject(VMObject& vmobject, size_t size, const StringView& name, u8 access)
{
InterruptDisabler disabler;
ASSERT(!(size % PAGE_SIZE));
auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
ASSERT(range.is_valid());
auto region = make<Region>(range, vmobject, 0, name, access);
region->map(kernel_page_directory());
return region;
}
void MemoryManager::deallocate_user_physical_page(PhysicalPage&& page)
{
for (auto& region : m_user_physical_regions) {
if (!region.contains(page)) {
kprintf(
"MM: deallocate_user_physical_page: %p not in %p -> %p\n",
page.paddr().get(), region.lower().get(), region.upper().get());
continue;
}
region.return_page(move(page));
--m_user_physical_pages_used;
return;
}
kprintf("MM: deallocate_user_physical_page couldn't figure out region for user page @ %p\n", page.paddr().get());
ASSERT_NOT_REACHED();
}
RefPtr<PhysicalPage> MemoryManager::find_free_user_physical_page()
{
RefPtr<PhysicalPage> page;
for (auto& region : m_user_physical_regions) {
page = region.take_free_page(false);
if (!page.is_null())
break;
}
return page;
}
RefPtr<PhysicalPage> MemoryManager::allocate_user_physical_page(ShouldZeroFill should_zero_fill)
{
InterruptDisabler disabler;
RefPtr<PhysicalPage> page = find_free_user_physical_page();
if (!page) {
if (m_user_physical_regions.is_empty()) {
kprintf("MM: no user physical regions available (?)\n");
}
for_each_vmobject([&](auto& vmobject) {
if (vmobject.is_purgeable()) {
auto& purgeable_vmobject = static_cast<PurgeableVMObject&>(vmobject);
int purged_page_count = purgeable_vmobject.purge_with_interrupts_disabled({});
if (purged_page_count) {
kprintf("MM: Purge saved the day! Purged %d pages from PurgeableVMObject{%p}\n", purged_page_count, &purgeable_vmobject);
page = find_free_user_physical_page();
ASSERT(page);
return IterationDecision::Break;
}
}
return IterationDecision::Continue;
});
if (!page) {
kprintf("MM: no user physical pages available\n");
ASSERT_NOT_REACHED();
return {};
}
}
#ifdef MM_DEBUG
dbgprintf("MM: allocate_user_physical_page vending P%p\n", page->paddr().get());
#endif
if (should_zero_fill == ShouldZeroFill::Yes) {
auto* ptr = (u32*)quickmap_page(*page);
fast_u32_fill(ptr, 0, PAGE_SIZE / sizeof(u32));
unquickmap_page();
}
++m_user_physical_pages_used;
return page;
}
void MemoryManager::deallocate_supervisor_physical_page(PhysicalPage&& page)
{
for (auto& region : m_super_physical_regions) {
if (!region.contains(page)) {
kprintf(
"MM: deallocate_supervisor_physical_page: %p not in %p -> %p\n",
page.paddr().get(), region.lower().get(), region.upper().get());
continue;
}
region.return_page(move(page));
--m_super_physical_pages_used;
return;
}
kprintf("MM: deallocate_supervisor_physical_page couldn't figure out region for super page @ %p\n", page.paddr().get());
ASSERT_NOT_REACHED();
}
RefPtr<PhysicalPage> MemoryManager::allocate_supervisor_physical_page()
{
InterruptDisabler disabler;
RefPtr<PhysicalPage> page;
for (auto& region : m_super_physical_regions) {
page = region.take_free_page(true);
if (page.is_null())
continue;
}
if (!page) {
if (m_super_physical_regions.is_empty()) {
kprintf("MM: no super physical regions available (?)\n");
}
kprintf("MM: no super physical pages available\n");
ASSERT_NOT_REACHED();
return {};
}
#ifdef MM_DEBUG
dbgprintf("MM: allocate_supervisor_physical_page vending P%p\n", page->paddr().get());
#endif
fast_u32_fill((u32*)page->paddr().as_ptr(), 0, PAGE_SIZE / sizeof(u32));
++m_super_physical_pages_used;
return page;
}
void MemoryManager::enter_process_paging_scope(Process& process)
{
ASSERT(current);
InterruptDisabler disabler;
current->tss().cr3 = process.page_directory().cr3();
asm volatile("movl %%eax, %%cr3" ::"a"(process.page_directory().cr3())
: "memory");
}
void MemoryManager::flush_entire_tlb()
{
asm volatile(
"mov %%cr3, %%eax\n"
"mov %%eax, %%cr3\n" ::
: "%eax", "memory");
}
void MemoryManager::flush_tlb(VirtualAddress vaddr)
{
asm volatile("invlpg %0"
:
: "m"(*(char*)vaddr.get())
: "memory");
}
void MemoryManager::map_for_kernel(VirtualAddress vaddr, PhysicalAddress paddr, bool cache_disabled)
{
auto& pte = ensure_pte(kernel_page_directory(), vaddr);
pte.set_physical_page_base(paddr.get());
pte.set_present(true);
pte.set_writable(true);
pte.set_user_allowed(false);
pte.set_cache_disabled(cache_disabled);
flush_tlb(vaddr);
}
u8* MemoryManager::quickmap_page(PhysicalPage& physical_page)
{
ASSERT_INTERRUPTS_DISABLED();
ASSERT(!m_quickmap_in_use);
m_quickmap_in_use = true;
auto page_vaddr = m_quickmap_addr;
auto& pte = ensure_pte(kernel_page_directory(), page_vaddr);
pte.set_physical_page_base(physical_page.paddr().get());
pte.set_present(true);
pte.set_writable(true);
pte.set_user_allowed(false);
flush_tlb(page_vaddr);
ASSERT((u32)pte.physical_page_base() == physical_page.paddr().get());
#ifdef MM_DEBUG
dbg() << "MM: >> quickmap_page " << page_vaddr << " => " << physical_page.paddr() << " @ PTE=" << (void*)pte.raw() << " {" << &pte << "}";
#endif
return page_vaddr.as_ptr();
}
void MemoryManager::unquickmap_page()
{
ASSERT_INTERRUPTS_DISABLED();
ASSERT(m_quickmap_in_use);
auto page_vaddr = m_quickmap_addr;
auto& pte = ensure_pte(kernel_page_directory(), page_vaddr);
#ifdef MM_DEBUG
auto old_physical_address = pte.physical_page_base();
#endif
pte.set_physical_page_base(0);
pte.set_present(false);
pte.set_writable(false);
flush_tlb(page_vaddr);
#ifdef MM_DEBUG
dbg() << "MM: >> unquickmap_page " << page_vaddr << " =/> " << old_physical_address;
#endif
m_quickmap_in_use = false;
}
bool MemoryManager::validate_user_stack(const Process& process, VirtualAddress vaddr) const
{
auto* region = region_from_vaddr(process, vaddr);
return region && region->is_stack();
}
bool MemoryManager::validate_user_read(const Process& process, VirtualAddress vaddr) const
{
auto* region = user_region_from_vaddr(const_cast<Process&>(process), vaddr);
return region && region->is_user_accessible() && region->is_readable();
}
bool MemoryManager::validate_user_write(const Process& process, VirtualAddress vaddr) const
{
auto* region = user_region_from_vaddr(const_cast<Process&>(process), vaddr);
return region && region->is_user_accessible() && region->is_writable();
}
void MemoryManager::register_vmobject(VMObject& vmobject)
{
InterruptDisabler disabler;
m_vmobjects.append(&vmobject);
}
void MemoryManager::unregister_vmobject(VMObject& vmobject)
{
InterruptDisabler disabler;
m_vmobjects.remove(&vmobject);
}
void MemoryManager::register_region(Region& region)
{
InterruptDisabler disabler;
if (region.vaddr().get() >= 0xc0000000)
m_kernel_regions.append(®ion);
else
m_user_regions.append(®ion);
}
void MemoryManager::unregister_region(Region& region)
{
InterruptDisabler disabler;
if (region.vaddr().get() >= 0xc0000000)
m_kernel_regions.remove(®ion);
else
m_user_regions.remove(®ion);
}
ProcessPagingScope::ProcessPagingScope(Process& process)
{
ASSERT(current);
MM.enter_process_paging_scope(process);
}
ProcessPagingScope::~ProcessPagingScope()
{
MM.enter_process_paging_scope(current->process());
}
| ./CrossVul/dataset_final_sorted/CWE-269/cpp/good_1350_0 |
crossvul-cpp_data_good_3234_4 | /*
===========================================================================
Copyright (C) 2005 - 2015, ioquake3 contributors
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
#include <csignal>
#include <cstdlib>
#include <cstdarg>
#include <cstdio>
#include <sys/stat.h>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include "qcommon/qcommon.h"
#include "sys_local.h"
#include "sys_loadlib.h"
#include "sys_public.h"
#include "con_local.h"
static char binaryPath[ MAX_OSPATH ] = { 0 };
static char installPath[ MAX_OSPATH ] = { 0 };
cvar_t *com_minimized;
cvar_t *com_unfocused;
cvar_t *com_maxfps;
cvar_t *com_maxfpsMinimized;
cvar_t *com_maxfpsUnfocused;
/*
=================
Sys_SetBinaryPath
=================
*/
void Sys_SetBinaryPath(const char *path)
{
Q_strncpyz(binaryPath, path, sizeof(binaryPath));
}
/*
=================
Sys_BinaryPath
=================
*/
char *Sys_BinaryPath(void)
{
return binaryPath;
}
/*
=================
Sys_SetDefaultInstallPath
=================
*/
void Sys_SetDefaultInstallPath(const char *path)
{
Q_strncpyz(installPath, path, sizeof(installPath));
}
/*
=================
Sys_DefaultInstallPath
=================
*/
char *Sys_DefaultInstallPath(void)
{
if (*installPath)
return installPath;
else
return Sys_Cwd();
}
/*
=================
Sys_DefaultAppPath
=================
*/
char *Sys_DefaultAppPath(void)
{
return Sys_BinaryPath();
}
/*
==================
Sys_GetClipboardData
==================
*/
char *Sys_GetClipboardData( void ) {
#ifdef DEDICATED
return NULL;
#else
if ( !SDL_HasClipboardText() )
return NULL;
char *cbText = SDL_GetClipboardText();
size_t len = strlen( cbText ) + 1;
char *buf = (char *)Z_Malloc( len, TAG_CLIPBOARD );
Q_strncpyz( buf, cbText, len );
SDL_free( cbText );
return buf;
#endif
}
/*
=================
Sys_ConsoleInput
Handle new console input
=================
*/
char *Sys_ConsoleInput(void)
{
return CON_Input( );
}
void Sys_Print( const char *msg ) {
// TTimo - prefix for text that shows up in console but not in notify
// backported from RTCW
if ( !Q_strncmp( msg, "[skipnotify]", 12 ) ) {
msg += 12;
}
if ( msg[0] == '*' ) {
msg += 1;
}
ConsoleLogAppend( msg );
CON_Print( msg );
}
/*
================
Sys_Init
Called after the common systems (cvars, files, etc)
are initialized
================
*/
void Sys_Init( void ) {
Cmd_AddCommand ("in_restart", IN_Restart);
Cvar_Get( "arch", OS_STRING " " ARCH_STRING, CVAR_ROM );
Cvar_Get( "username", Sys_GetCurrentUser(), CVAR_ROM );
com_unfocused = Cvar_Get( "com_unfocused", "0", CVAR_ROM );
com_minimized = Cvar_Get( "com_minimized", "0", CVAR_ROM );
#ifdef _JK2EXE
com_maxfps = Cvar_Get ("com_maxfps", "125", CVAR_ARCHIVE );
#else
com_maxfps = Cvar_Get( "com_maxfps", "125", CVAR_ARCHIVE, "Maximum frames per second" );
#endif
com_maxfpsUnfocused = Cvar_Get( "com_maxfpsUnfocused", "0", CVAR_ARCHIVE );
com_maxfpsMinimized = Cvar_Get( "com_maxfpsMinimized", "50", CVAR_ARCHIVE );
}
static void NORETURN Sys_Exit( int ex ) {
IN_Shutdown();
#ifndef DEDICATED
SDL_Quit();
#endif
NET_Shutdown();
Sys_PlatformExit();
Com_ShutdownHunkMemory();
Com_ShutdownZoneMemory();
CON_Shutdown();
exit( ex );
}
#if !defined(DEDICATED)
static void Sys_ErrorDialog( const char *error )
{
time_t rawtime;
char timeStr[32] = {}; // should really only reach ~19 chars
char crashLogPath[MAX_OSPATH];
time( &rawtime );
strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime
Com_sprintf( crashLogPath, sizeof( crashLogPath ),
"%s%ccrashlog-%s.txt",
Sys_DefaultHomePath(), PATH_SEP, timeStr );
Sys_Mkdir( Sys_DefaultHomePath() );
FILE *fp = fopen( crashLogPath, "w" );
if ( fp )
{
ConsoleLogWriteOut( fp );
fclose( fp );
const char *errorMessage = va( "%s\n\nThe crash log was written to %s", error, crashLogPath );
if ( SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "Error", errorMessage, NULL ) < 0 )
{
fprintf( stderr, "%s", errorMessage );
}
}
else
{
// Getting pretty desperate now
ConsoleLogWriteOut( stderr );
fflush( stderr );
const char *errorMessage = va( "%s\nCould not write the crash log file, but we printed it to stderr.\n"
"Try running the game using a command line interface.", error );
if ( SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "Error", errorMessage, NULL ) < 0 )
{
// We really have hit rock bottom here :(
fprintf( stderr, "%s", errorMessage );
}
}
}
#endif
void NORETURN QDECL Sys_Error( const char *error, ... )
{
va_list argptr;
char string[1024];
va_start (argptr,error);
Q_vsnprintf (string, sizeof(string), error, argptr);
va_end (argptr);
Sys_Print( string );
// Only print Sys_ErrorDialog for client binary. The dedicated
// server binary is meant to be a command line program so you would
// expect to see the error printed.
#if !defined(DEDICATED)
Sys_ErrorDialog( string );
#endif
Sys_Exit( 3 );
}
void NORETURN Sys_Quit (void) {
Sys_Exit(0);
}
/*
============
Sys_FileTime
returns -1 if not present
============
*/
time_t Sys_FileTime( const char *path )
{
struct stat buf;
if ( stat( path, &buf ) == -1 )
return -1;
return buf.st_mtime;
}
/*
=================
Sys_UnloadDll
=================
*/
void Sys_UnloadDll( void *dllHandle )
{
if( !dllHandle )
{
Com_Printf("Sys_UnloadDll(NULL)\n");
return;
}
Sys_UnloadLibrary(dllHandle);
}
/*
=================
Sys_LoadDll
First try to load library name from system library path,
from executable path, then fs_basepath.
=================
*/
void *Sys_LoadDll( const char *name, qboolean useSystemLib )
{
void *dllhandle = NULL;
// Don't load any DLLs that end with the pk3 extension
if ( COM_CompareExtension( name, ".pk3" ) )
{
Com_Printf( S_COLOR_YELLOW "WARNING: Rejecting DLL named \"%s\"", name );
return NULL;
}
if ( useSystemLib )
{
Com_Printf( "Trying to load \"%s\"...\n", name );
dllhandle = Sys_LoadLibrary( name );
if ( dllhandle )
return dllhandle;
Com_Printf( "%s(%s) failed: \"%s\"\n", __FUNCTION__, name, Sys_LibraryError() );
}
const char *binarypath = Sys_BinaryPath();
const char *basepath = Cvar_VariableString( "fs_basepath" );
if ( !*binarypath )
binarypath = ".";
const char *searchPaths[] = {
binarypath,
basepath,
};
const size_t numPaths = ARRAY_LEN( searchPaths );
for ( size_t i = 0; i < numPaths; i++ )
{
const char *libDir = searchPaths[i];
if ( !libDir[0] )
continue;
Com_Printf( "Trying to load \"%s\" from \"%s\"...\n", name, libDir );
char *fn = va( "%s%c%s", libDir, PATH_SEP, name );
dllhandle = Sys_LoadLibrary( fn );
if ( dllhandle )
return dllhandle;
Com_Printf( "%s(%s) failed: \"%s\"\n", __FUNCTION__, fn, Sys_LibraryError() );
}
return NULL;
}
#if defined(MACOS_X) && !defined(_JK2EXE)
void *Sys_LoadMachOBundle( const char *name )
{
if ( !FS_LoadMachOBundle(name) )
return NULL;
char *homepath = Cvar_VariableString( "fs_homepath" );
char *gamedir = Cvar_VariableString( "fs_game" );
char dllName[MAX_QPATH];
Com_sprintf( dllName, sizeof(dllName), "%s_pk3" DLL_EXT, name );
//load the unzipped library
char *fn = FS_BuildOSPath( homepath, gamedir, dllName );
void *libHandle = Sys_LoadLibrary( fn );
if ( libHandle != NULL ) {
Com_Printf( "Loaded pk3 bundle %s.\n", name );
}
return libHandle;
}
#endif
enum SearchPathFlag
{
SEARCH_PATH_MOD = 1 << 0,
SEARCH_PATH_BASE = 1 << 1,
SEARCH_PATH_OPENJK = 1 << 2,
SEARCH_PATH_ROOT = 1 << 3
};
static void *Sys_LoadDllFromPaths( const char *filename, const char *gamedir, const char **searchPaths,
size_t numPaths, uint32_t searchFlags, const char *callerName )
{
char *fn;
void *libHandle;
if ( searchFlags & SEARCH_PATH_MOD )
{
for ( size_t i = 0; i < numPaths; i++ )
{
const char *libDir = searchPaths[i];
if ( !libDir[0] )
continue;
fn = FS_BuildOSPath( libDir, gamedir, filename );
libHandle = Sys_LoadLibrary( fn );
if ( libHandle )
return libHandle;
Com_Printf( "%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError() );
}
}
if ( searchFlags & SEARCH_PATH_BASE )
{
for ( size_t i = 0; i < numPaths; i++ )
{
const char *libDir = searchPaths[i];
if ( !libDir[0] )
continue;
fn = FS_BuildOSPath( libDir, BASEGAME, filename );
libHandle = Sys_LoadLibrary( fn );
if ( libHandle )
return libHandle;
Com_Printf( "%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError() );
}
}
if ( searchFlags & SEARCH_PATH_OPENJK )
{
for ( size_t i = 0; i < numPaths; i++ )
{
const char *libDir = searchPaths[i];
if ( !libDir[0] )
continue;
fn = FS_BuildOSPath( libDir, OPENJKGAME, filename );
libHandle = Sys_LoadLibrary( fn );
if ( libHandle )
return libHandle;
Com_Printf( "%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError() );
}
}
if ( searchFlags & SEARCH_PATH_ROOT )
{
for ( size_t i = 0; i < numPaths; i++ )
{
const char *libDir = searchPaths[i];
if ( !libDir[0] )
continue;
fn = va( "%s%c%s", libDir, PATH_SEP, filename );
libHandle = Sys_LoadLibrary( fn );
if ( libHandle )
return libHandle;
Com_Printf( "%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError() );
}
}
return NULL;
}
static void FreeUnpackDLLResult(UnpackDLLResult *result)
{
if ( result->tempDLLPath )
Z_Free((void *)result->tempDLLPath);
}
void *Sys_LoadLegacyGameDll( const char *name, VMMainProc **vmMain, SystemCallProc *systemcalls )
{
void *libHandle = NULL;
char filename[MAX_OSPATH];
Com_sprintf (filename, sizeof(filename), "%s" ARCH_STRING DLL_EXT, name);
#if defined(_DEBUG)
libHandle = Sys_LoadLibrary( name );
if ( !libHandle )
#endif
{
UnpackDLLResult unpackResult = Sys_UnpackDLL(filename);
if ( !unpackResult.succeeded )
{
if ( Sys_DLLNeedsUnpacking() )
{
FreeUnpackDLLResult(&unpackResult);
Com_DPrintf( "Sys_LoadLegacyGameDll: Failed to unpack %s from PK3.\n", filename );
return NULL;
}
}
else
{
libHandle = Sys_LoadLibrary(unpackResult.tempDLLPath);
}
FreeUnpackDLLResult(&unpackResult);
if ( !libHandle )
{
#if defined(MACOS_X) && !defined(_JK2EXE)
//First, look for the old-style mac .bundle that's inside a pk3
//It's actually zipped, and the zipfile has the same name as 'name'
libHandle = Sys_LoadMachOBundle( name );
#endif
if (!libHandle) {
char *basepath = Cvar_VariableString( "fs_basepath" );
char *homepath = Cvar_VariableString( "fs_homepath" );
char *cdpath = Cvar_VariableString( "fs_cdpath" );
char *gamedir = Cvar_VariableString( "fs_game" );
#ifdef MACOS_X
char *apppath = Cvar_VariableString( "fs_apppath" );
#endif
const char *searchPaths[] = {
homepath,
#ifdef MACOS_X
apppath,
#endif
basepath,
cdpath,
};
size_t numPaths = ARRAY_LEN( searchPaths );
libHandle = Sys_LoadDllFromPaths( filename, gamedir, searchPaths, numPaths, SEARCH_PATH_BASE | SEARCH_PATH_MOD, __FUNCTION__ );
if ( !libHandle )
return NULL;
}
}
}
typedef void QDECL DllEntryProc( SystemCallProc *syscallptr );
DllEntryProc *dllEntry = (DllEntryProc *)Sys_LoadFunction( libHandle, "dllEntry" );
*vmMain = (VMMainProc *)Sys_LoadFunction( libHandle, "vmMain" );
if ( !*vmMain || !dllEntry ) {
Com_DPrintf ( "Sys_LoadLegacyGameDll(%s) failed to find vmMain function:\n...%s!\n", name, Sys_LibraryError() );
Sys_UnloadLibrary( libHandle );
return NULL;
}
Com_DPrintf ( "Sys_LoadLegacyGameDll(%s) found vmMain function at 0x%" PRIxPTR "\n", name, *vmMain );
dllEntry( systemcalls );
return libHandle;
}
void *Sys_LoadSPGameDll( const char *name, GetGameAPIProc **GetGameAPI )
{
void *libHandle = NULL;
char filename[MAX_OSPATH];
assert( GetGameAPI );
Com_sprintf (filename, sizeof(filename), "%s" ARCH_STRING DLL_EXT, name);
#if defined(MACOS_X) && !defined(_JK2EXE)
//First, look for the old-style mac .bundle that's inside a pk3
//It's actually zipped, and the zipfile has the same name as 'name'
libHandle = Sys_LoadMachOBundle( filename );
#endif
if (!libHandle) {
char *basepath = Cvar_VariableString( "fs_basepath" );
char *homepath = Cvar_VariableString( "fs_homepath" );
char *cdpath = Cvar_VariableString( "fs_cdpath" );
char *gamedir = Cvar_VariableString( "fs_game" );
#ifdef MACOS_X
char *apppath = Cvar_VariableString( "fs_apppath" );
#endif
const char *searchPaths[] = {
homepath,
#ifdef MACOS_X
apppath,
#endif
basepath,
cdpath,
};
size_t numPaths = ARRAY_LEN( searchPaths );
libHandle = Sys_LoadDllFromPaths( filename, gamedir, searchPaths, numPaths,
SEARCH_PATH_BASE | SEARCH_PATH_MOD | SEARCH_PATH_OPENJK | SEARCH_PATH_ROOT,
__FUNCTION__ );
if ( !libHandle )
return NULL;
}
*GetGameAPI = (GetGameAPIProc *)Sys_LoadFunction( libHandle, "GetGameAPI" );
if ( !*GetGameAPI ) {
Com_DPrintf ( "%s(%s) failed to find GetGameAPI function:\n...%s!\n", __FUNCTION__, name, Sys_LibraryError() );
Sys_UnloadLibrary( libHandle );
return NULL;
}
return libHandle;
}
void *Sys_LoadGameDll( const char *name, GetModuleAPIProc **moduleAPI )
{
void *libHandle = NULL;
char filename[MAX_OSPATH];
Com_sprintf (filename, sizeof(filename), "%s" ARCH_STRING DLL_EXT, name);
#if defined(_DEBUG)
libHandle = Sys_LoadLibrary( filename );
if ( !libHandle )
#endif
{
UnpackDLLResult unpackResult = Sys_UnpackDLL(filename);
if ( !unpackResult.succeeded )
{
if ( Sys_DLLNeedsUnpacking() )
{
FreeUnpackDLLResult(&unpackResult);
Com_DPrintf( "Sys_LoadLegacyGameDll: Failed to unpack %s from PK3.\n", filename );
return NULL;
}
}
else
{
libHandle = Sys_LoadLibrary(unpackResult.tempDLLPath);
}
FreeUnpackDLLResult(&unpackResult);
if ( !libHandle )
{
#if defined(MACOS_X) && !defined(_JK2EXE)
//First, look for the old-style mac .bundle that's inside a pk3
//It's actually zipped, and the zipfile has the same name as 'name'
libHandle = Sys_LoadMachOBundle( name );
#endif
if (!libHandle) {
char *basepath = Cvar_VariableString( "fs_basepath" );
char *homepath = Cvar_VariableString( "fs_homepath" );
char *cdpath = Cvar_VariableString( "fs_cdpath" );
char *gamedir = Cvar_VariableString( "fs_game" );
#ifdef MACOS_X
char *apppath = Cvar_VariableString( "fs_apppath" );
#endif
const char *searchPaths[] = {
homepath,
#ifdef MACOS_X
apppath,
#endif
basepath,
cdpath,
};
size_t numPaths = ARRAY_LEN( searchPaths );
libHandle = Sys_LoadDllFromPaths( filename, gamedir, searchPaths, numPaths, SEARCH_PATH_BASE | SEARCH_PATH_MOD, __FUNCTION__ );
if ( !libHandle )
return NULL;
}
}
}
*moduleAPI = (GetModuleAPIProc *)Sys_LoadFunction( libHandle, "GetModuleAPI" );
if ( !*moduleAPI ) {
Com_DPrintf ( "Sys_LoadGameDll(%s) failed to find GetModuleAPI function:\n...%s!\n", name, Sys_LibraryError() );
Sys_UnloadLibrary( libHandle );
return NULL;
}
return libHandle;
}
/*
=================
Sys_SigHandler
=================
*/
void Sys_SigHandler( int signal )
{
static qboolean signalcaught = qfalse;
if( signalcaught )
{
fprintf( stderr, "DOUBLE SIGNAL FAULT: Received signal %d, exiting...\n",
signal );
}
else
{
signalcaught = qtrue;
//VM_Forced_Unload_Start();
#ifndef DEDICATED
CL_Shutdown();
//CL_Shutdown(va("Received signal %d", signal), qtrue, qtrue);
#endif
SV_Shutdown(va("Received signal %d", signal) );
//VM_Forced_Unload_Done();
}
if( signal == SIGTERM || signal == SIGINT )
Sys_Exit( 1 );
else
Sys_Exit( 2 );
}
#ifdef MACOS_X
/*
=================
Sys_StripAppBundle
Discovers if passed dir is suffixed with the directory structure of a Mac OS X
.app bundle. If it is, the .app directory structure is stripped off the end and
the result is returned. If not, dir is returned untouched.
=================
*/
char *Sys_StripAppBundle( char *dir )
{
static char cwd[MAX_OSPATH];
Q_strncpyz(cwd, dir, sizeof(cwd));
if(strcmp(Sys_Basename(cwd), "MacOS"))
return dir;
Q_strncpyz(cwd, Sys_Dirname(cwd), sizeof(cwd));
if(strcmp(Sys_Basename(cwd), "Contents"))
return dir;
Q_strncpyz(cwd, Sys_Dirname(cwd), sizeof(cwd));
if(!strstr(Sys_Basename(cwd), ".app"))
return dir;
Q_strncpyz(cwd, Sys_Dirname(cwd), sizeof(cwd));
return cwd;
}
#endif
#ifndef DEFAULT_BASEDIR
# ifdef MACOS_X
# define DEFAULT_BASEDIR Sys_StripAppBundle(Sys_BinaryPath())
# else
# define DEFAULT_BASEDIR Sys_BinaryPath()
# endif
#endif
int main ( int argc, char* argv[] )
{
int i;
char commandLine[ MAX_STRING_CHARS ] = { 0 };
Sys_PlatformInit();
CON_Init();
// get the initial time base
Sys_Milliseconds();
#ifdef MACOS_X
// This is passed if we are launched by double-clicking
if ( argc >= 2 && Q_strncmp ( argv[1], "-psn", 4 ) == 0 )
argc = 1;
#endif
Sys_SetBinaryPath( Sys_Dirname( argv[ 0 ] ) );
Sys_SetDefaultInstallPath( DEFAULT_BASEDIR );
// Concatenate the command line for passing to Com_Init
for( i = 1; i < argc; i++ )
{
const bool containsSpaces = (strchr(argv[i], ' ') != NULL);
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), argv[ i ] );
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), " " );
}
Com_Init (commandLine);
NET_Init();
// main game loop
while (1)
{
if ( com_busyWait->integer )
{
bool shouldSleep = false;
#if !defined(_JK2EXE)
if ( com_dedicated->integer )
{
shouldSleep = true;
}
#endif
if ( com_minimized->integer )
{
shouldSleep = true;
}
if ( shouldSleep )
{
Sys_Sleep( 5 );
}
}
// run the game
Com_Frame();
}
// never gets here
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/cpp/good_3234_4 |
crossvul-cpp_data_bad_3234_4 | /*
===========================================================================
Copyright (C) 2005 - 2015, ioquake3 contributors
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
#include <csignal>
#include <cstdlib>
#include <cstdarg>
#include <cstdio>
#include <sys/stat.h>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include "qcommon/qcommon.h"
#include "sys_local.h"
#include "sys_loadlib.h"
#include "sys_public.h"
#include "con_local.h"
static char binaryPath[ MAX_OSPATH ] = { 0 };
static char installPath[ MAX_OSPATH ] = { 0 };
cvar_t *com_minimized;
cvar_t *com_unfocused;
cvar_t *com_maxfps;
cvar_t *com_maxfpsMinimized;
cvar_t *com_maxfpsUnfocused;
/*
=================
Sys_SetBinaryPath
=================
*/
void Sys_SetBinaryPath(const char *path)
{
Q_strncpyz(binaryPath, path, sizeof(binaryPath));
}
/*
=================
Sys_BinaryPath
=================
*/
char *Sys_BinaryPath(void)
{
return binaryPath;
}
/*
=================
Sys_SetDefaultInstallPath
=================
*/
void Sys_SetDefaultInstallPath(const char *path)
{
Q_strncpyz(installPath, path, sizeof(installPath));
}
/*
=================
Sys_DefaultInstallPath
=================
*/
char *Sys_DefaultInstallPath(void)
{
if (*installPath)
return installPath;
else
return Sys_Cwd();
}
/*
=================
Sys_DefaultAppPath
=================
*/
char *Sys_DefaultAppPath(void)
{
return Sys_BinaryPath();
}
/*
==================
Sys_GetClipboardData
==================
*/
char *Sys_GetClipboardData( void ) {
#ifdef DEDICATED
return NULL;
#else
if ( !SDL_HasClipboardText() )
return NULL;
char *cbText = SDL_GetClipboardText();
size_t len = strlen( cbText ) + 1;
char *buf = (char *)Z_Malloc( len, TAG_CLIPBOARD );
Q_strncpyz( buf, cbText, len );
SDL_free( cbText );
return buf;
#endif
}
/*
=================
Sys_ConsoleInput
Handle new console input
=================
*/
char *Sys_ConsoleInput(void)
{
return CON_Input( );
}
void Sys_Print( const char *msg ) {
// TTimo - prefix for text that shows up in console but not in notify
// backported from RTCW
if ( !Q_strncmp( msg, "[skipnotify]", 12 ) ) {
msg += 12;
}
if ( msg[0] == '*' ) {
msg += 1;
}
ConsoleLogAppend( msg );
CON_Print( msg );
}
/*
================
Sys_Init
Called after the common systems (cvars, files, etc)
are initialized
================
*/
void Sys_Init( void ) {
Cmd_AddCommand ("in_restart", IN_Restart);
Cvar_Get( "arch", OS_STRING " " ARCH_STRING, CVAR_ROM );
Cvar_Get( "username", Sys_GetCurrentUser(), CVAR_ROM );
com_unfocused = Cvar_Get( "com_unfocused", "0", CVAR_ROM );
com_minimized = Cvar_Get( "com_minimized", "0", CVAR_ROM );
#ifdef _JK2EXE
com_maxfps = Cvar_Get ("com_maxfps", "125", CVAR_ARCHIVE );
#else
com_maxfps = Cvar_Get( "com_maxfps", "125", CVAR_ARCHIVE, "Maximum frames per second" );
#endif
com_maxfpsUnfocused = Cvar_Get( "com_maxfpsUnfocused", "0", CVAR_ARCHIVE );
com_maxfpsMinimized = Cvar_Get( "com_maxfpsMinimized", "50", CVAR_ARCHIVE );
}
static void NORETURN Sys_Exit( int ex ) {
IN_Shutdown();
#ifndef DEDICATED
SDL_Quit();
#endif
NET_Shutdown();
Sys_PlatformExit();
Com_ShutdownHunkMemory();
Com_ShutdownZoneMemory();
CON_Shutdown();
exit( ex );
}
#if !defined(DEDICATED)
static void Sys_ErrorDialog( const char *error )
{
time_t rawtime;
char timeStr[32] = {}; // should really only reach ~19 chars
char crashLogPath[MAX_OSPATH];
time( &rawtime );
strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime
Com_sprintf( crashLogPath, sizeof( crashLogPath ),
"%s%ccrashlog-%s.txt",
Sys_DefaultHomePath(), PATH_SEP, timeStr );
Sys_Mkdir( Sys_DefaultHomePath() );
FILE *fp = fopen( crashLogPath, "w" );
if ( fp )
{
ConsoleLogWriteOut( fp );
fclose( fp );
const char *errorMessage = va( "%s\n\nThe crash log was written to %s", error, crashLogPath );
if ( SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "Error", errorMessage, NULL ) < 0 )
{
fprintf( stderr, "%s", errorMessage );
}
}
else
{
// Getting pretty desperate now
ConsoleLogWriteOut( stderr );
fflush( stderr );
const char *errorMessage = va( "%s\nCould not write the crash log file, but we printed it to stderr.\n"
"Try running the game using a command line interface.", error );
if ( SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "Error", errorMessage, NULL ) < 0 )
{
// We really have hit rock bottom here :(
fprintf( stderr, "%s", errorMessage );
}
}
}
#endif
void NORETURN QDECL Sys_Error( const char *error, ... )
{
va_list argptr;
char string[1024];
va_start (argptr,error);
Q_vsnprintf (string, sizeof(string), error, argptr);
va_end (argptr);
Sys_Print( string );
// Only print Sys_ErrorDialog for client binary. The dedicated
// server binary is meant to be a command line program so you would
// expect to see the error printed.
#if !defined(DEDICATED)
Sys_ErrorDialog( string );
#endif
Sys_Exit( 3 );
}
void NORETURN Sys_Quit (void) {
Sys_Exit(0);
}
/*
============
Sys_FileTime
returns -1 if not present
============
*/
time_t Sys_FileTime( const char *path )
{
struct stat buf;
if ( stat( path, &buf ) == -1 )
return -1;
return buf.st_mtime;
}
/*
=================
Sys_UnloadDll
=================
*/
void Sys_UnloadDll( void *dllHandle )
{
if( !dllHandle )
{
Com_Printf("Sys_UnloadDll(NULL)\n");
return;
}
Sys_UnloadLibrary(dllHandle);
}
/*
=================
Sys_LoadDll
First try to load library name from system library path,
from executable path, then fs_basepath.
=================
*/
void *Sys_LoadDll( const char *name, qboolean useSystemLib )
{
void *dllhandle = NULL;
if ( useSystemLib )
{
Com_Printf( "Trying to load \"%s\"...\n", name );
dllhandle = Sys_LoadLibrary( name );
if ( dllhandle )
return dllhandle;
Com_Printf( "%s(%s) failed: \"%s\"\n", __FUNCTION__, name, Sys_LibraryError() );
}
const char *binarypath = Sys_BinaryPath();
const char *basepath = Cvar_VariableString( "fs_basepath" );
if ( !*binarypath )
binarypath = ".";
const char *searchPaths[] = {
binarypath,
basepath,
};
const size_t numPaths = ARRAY_LEN( searchPaths );
for ( size_t i = 0; i < numPaths; i++ )
{
const char *libDir = searchPaths[i];
if ( !libDir[0] )
continue;
Com_Printf( "Trying to load \"%s\" from \"%s\"...\n", name, libDir );
char *fn = va( "%s%c%s", libDir, PATH_SEP, name );
dllhandle = Sys_LoadLibrary( fn );
if ( dllhandle )
return dllhandle;
Com_Printf( "%s(%s) failed: \"%s\"\n", __FUNCTION__, fn, Sys_LibraryError() );
}
return NULL;
}
#if defined(MACOS_X) && !defined(_JK2EXE)
void *Sys_LoadMachOBundle( const char *name )
{
if ( !FS_LoadMachOBundle(name) )
return NULL;
char *homepath = Cvar_VariableString( "fs_homepath" );
char *gamedir = Cvar_VariableString( "fs_game" );
char dllName[MAX_QPATH];
Com_sprintf( dllName, sizeof(dllName), "%s_pk3" DLL_EXT, name );
//load the unzipped library
char *fn = FS_BuildOSPath( homepath, gamedir, dllName );
void *libHandle = Sys_LoadLibrary( fn );
if ( libHandle != NULL ) {
Com_Printf( "Loaded pk3 bundle %s.\n", name );
}
return libHandle;
}
#endif
enum SearchPathFlag
{
SEARCH_PATH_MOD = 1 << 0,
SEARCH_PATH_BASE = 1 << 1,
SEARCH_PATH_OPENJK = 1 << 2,
SEARCH_PATH_ROOT = 1 << 3
};
static void *Sys_LoadDllFromPaths( const char *filename, const char *gamedir, const char **searchPaths,
size_t numPaths, uint32_t searchFlags, const char *callerName )
{
char *fn;
void *libHandle;
if ( searchFlags & SEARCH_PATH_MOD )
{
for ( size_t i = 0; i < numPaths; i++ )
{
const char *libDir = searchPaths[i];
if ( !libDir[0] )
continue;
fn = FS_BuildOSPath( libDir, gamedir, filename );
libHandle = Sys_LoadLibrary( fn );
if ( libHandle )
return libHandle;
Com_Printf( "%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError() );
}
}
if ( searchFlags & SEARCH_PATH_BASE )
{
for ( size_t i = 0; i < numPaths; i++ )
{
const char *libDir = searchPaths[i];
if ( !libDir[0] )
continue;
fn = FS_BuildOSPath( libDir, BASEGAME, filename );
libHandle = Sys_LoadLibrary( fn );
if ( libHandle )
return libHandle;
Com_Printf( "%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError() );
}
}
if ( searchFlags & SEARCH_PATH_OPENJK )
{
for ( size_t i = 0; i < numPaths; i++ )
{
const char *libDir = searchPaths[i];
if ( !libDir[0] )
continue;
fn = FS_BuildOSPath( libDir, OPENJKGAME, filename );
libHandle = Sys_LoadLibrary( fn );
if ( libHandle )
return libHandle;
Com_Printf( "%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError() );
}
}
if ( searchFlags & SEARCH_PATH_ROOT )
{
for ( size_t i = 0; i < numPaths; i++ )
{
const char *libDir = searchPaths[i];
if ( !libDir[0] )
continue;
fn = va( "%s%c%s", libDir, PATH_SEP, filename );
libHandle = Sys_LoadLibrary( fn );
if ( libHandle )
return libHandle;
Com_Printf( "%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError() );
}
}
return NULL;
}
static void FreeUnpackDLLResult(UnpackDLLResult *result)
{
if ( result->tempDLLPath )
Z_Free((void *)result->tempDLLPath);
}
void *Sys_LoadLegacyGameDll( const char *name, VMMainProc **vmMain, SystemCallProc *systemcalls )
{
void *libHandle = NULL;
char filename[MAX_OSPATH];
Com_sprintf (filename, sizeof(filename), "%s" ARCH_STRING DLL_EXT, name);
#if defined(_DEBUG)
libHandle = Sys_LoadLibrary( name );
if ( !libHandle )
#endif
{
UnpackDLLResult unpackResult = Sys_UnpackDLL(filename);
if ( !unpackResult.succeeded )
{
if ( Sys_DLLNeedsUnpacking() )
{
FreeUnpackDLLResult(&unpackResult);
Com_DPrintf( "Sys_LoadLegacyGameDll: Failed to unpack %s from PK3.\n", filename );
return NULL;
}
}
else
{
libHandle = Sys_LoadLibrary(unpackResult.tempDLLPath);
}
FreeUnpackDLLResult(&unpackResult);
if ( !libHandle )
{
#if defined(MACOS_X) && !defined(_JK2EXE)
//First, look for the old-style mac .bundle that's inside a pk3
//It's actually zipped, and the zipfile has the same name as 'name'
libHandle = Sys_LoadMachOBundle( name );
#endif
if (!libHandle) {
char *basepath = Cvar_VariableString( "fs_basepath" );
char *homepath = Cvar_VariableString( "fs_homepath" );
char *cdpath = Cvar_VariableString( "fs_cdpath" );
char *gamedir = Cvar_VariableString( "fs_game" );
#ifdef MACOS_X
char *apppath = Cvar_VariableString( "fs_apppath" );
#endif
const char *searchPaths[] = {
homepath,
#ifdef MACOS_X
apppath,
#endif
basepath,
cdpath,
};
size_t numPaths = ARRAY_LEN( searchPaths );
libHandle = Sys_LoadDllFromPaths( filename, gamedir, searchPaths, numPaths, SEARCH_PATH_BASE | SEARCH_PATH_MOD, __FUNCTION__ );
if ( !libHandle )
return NULL;
}
}
}
typedef void QDECL DllEntryProc( SystemCallProc *syscallptr );
DllEntryProc *dllEntry = (DllEntryProc *)Sys_LoadFunction( libHandle, "dllEntry" );
*vmMain = (VMMainProc *)Sys_LoadFunction( libHandle, "vmMain" );
if ( !*vmMain || !dllEntry ) {
Com_DPrintf ( "Sys_LoadLegacyGameDll(%s) failed to find vmMain function:\n...%s!\n", name, Sys_LibraryError() );
Sys_UnloadLibrary( libHandle );
return NULL;
}
Com_DPrintf ( "Sys_LoadLegacyGameDll(%s) found vmMain function at 0x%" PRIxPTR "\n", name, *vmMain );
dllEntry( systemcalls );
return libHandle;
}
void *Sys_LoadSPGameDll( const char *name, GetGameAPIProc **GetGameAPI )
{
void *libHandle = NULL;
char filename[MAX_OSPATH];
assert( GetGameAPI );
Com_sprintf (filename, sizeof(filename), "%s" ARCH_STRING DLL_EXT, name);
#if defined(MACOS_X) && !defined(_JK2EXE)
//First, look for the old-style mac .bundle that's inside a pk3
//It's actually zipped, and the zipfile has the same name as 'name'
libHandle = Sys_LoadMachOBundle( filename );
#endif
if (!libHandle) {
char *basepath = Cvar_VariableString( "fs_basepath" );
char *homepath = Cvar_VariableString( "fs_homepath" );
char *cdpath = Cvar_VariableString( "fs_cdpath" );
char *gamedir = Cvar_VariableString( "fs_game" );
#ifdef MACOS_X
char *apppath = Cvar_VariableString( "fs_apppath" );
#endif
const char *searchPaths[] = {
homepath,
#ifdef MACOS_X
apppath,
#endif
basepath,
cdpath,
};
size_t numPaths = ARRAY_LEN( searchPaths );
libHandle = Sys_LoadDllFromPaths( filename, gamedir, searchPaths, numPaths,
SEARCH_PATH_BASE | SEARCH_PATH_MOD | SEARCH_PATH_OPENJK | SEARCH_PATH_ROOT,
__FUNCTION__ );
if ( !libHandle )
return NULL;
}
*GetGameAPI = (GetGameAPIProc *)Sys_LoadFunction( libHandle, "GetGameAPI" );
if ( !*GetGameAPI ) {
Com_DPrintf ( "%s(%s) failed to find GetGameAPI function:\n...%s!\n", __FUNCTION__, name, Sys_LibraryError() );
Sys_UnloadLibrary( libHandle );
return NULL;
}
return libHandle;
}
void *Sys_LoadGameDll( const char *name, GetModuleAPIProc **moduleAPI )
{
void *libHandle = NULL;
char filename[MAX_OSPATH];
Com_sprintf (filename, sizeof(filename), "%s" ARCH_STRING DLL_EXT, name);
#if defined(_DEBUG)
libHandle = Sys_LoadLibrary( filename );
if ( !libHandle )
#endif
{
UnpackDLLResult unpackResult = Sys_UnpackDLL(filename);
if ( !unpackResult.succeeded )
{
if ( Sys_DLLNeedsUnpacking() )
{
FreeUnpackDLLResult(&unpackResult);
Com_DPrintf( "Sys_LoadLegacyGameDll: Failed to unpack %s from PK3.\n", filename );
return NULL;
}
}
else
{
libHandle = Sys_LoadLibrary(unpackResult.tempDLLPath);
}
FreeUnpackDLLResult(&unpackResult);
if ( !libHandle )
{
#if defined(MACOS_X) && !defined(_JK2EXE)
//First, look for the old-style mac .bundle that's inside a pk3
//It's actually zipped, and the zipfile has the same name as 'name'
libHandle = Sys_LoadMachOBundle( name );
#endif
if (!libHandle) {
char *basepath = Cvar_VariableString( "fs_basepath" );
char *homepath = Cvar_VariableString( "fs_homepath" );
char *cdpath = Cvar_VariableString( "fs_cdpath" );
char *gamedir = Cvar_VariableString( "fs_game" );
#ifdef MACOS_X
char *apppath = Cvar_VariableString( "fs_apppath" );
#endif
const char *searchPaths[] = {
homepath,
#ifdef MACOS_X
apppath,
#endif
basepath,
cdpath,
};
size_t numPaths = ARRAY_LEN( searchPaths );
libHandle = Sys_LoadDllFromPaths( filename, gamedir, searchPaths, numPaths, SEARCH_PATH_BASE | SEARCH_PATH_MOD, __FUNCTION__ );
if ( !libHandle )
return NULL;
}
}
}
*moduleAPI = (GetModuleAPIProc *)Sys_LoadFunction( libHandle, "GetModuleAPI" );
if ( !*moduleAPI ) {
Com_DPrintf ( "Sys_LoadGameDll(%s) failed to find GetModuleAPI function:\n...%s!\n", name, Sys_LibraryError() );
Sys_UnloadLibrary( libHandle );
return NULL;
}
return libHandle;
}
/*
=================
Sys_SigHandler
=================
*/
void Sys_SigHandler( int signal )
{
static qboolean signalcaught = qfalse;
if( signalcaught )
{
fprintf( stderr, "DOUBLE SIGNAL FAULT: Received signal %d, exiting...\n",
signal );
}
else
{
signalcaught = qtrue;
//VM_Forced_Unload_Start();
#ifndef DEDICATED
CL_Shutdown();
//CL_Shutdown(va("Received signal %d", signal), qtrue, qtrue);
#endif
SV_Shutdown(va("Received signal %d", signal) );
//VM_Forced_Unload_Done();
}
if( signal == SIGTERM || signal == SIGINT )
Sys_Exit( 1 );
else
Sys_Exit( 2 );
}
#ifdef MACOS_X
/*
=================
Sys_StripAppBundle
Discovers if passed dir is suffixed with the directory structure of a Mac OS X
.app bundle. If it is, the .app directory structure is stripped off the end and
the result is returned. If not, dir is returned untouched.
=================
*/
char *Sys_StripAppBundle( char *dir )
{
static char cwd[MAX_OSPATH];
Q_strncpyz(cwd, dir, sizeof(cwd));
if(strcmp(Sys_Basename(cwd), "MacOS"))
return dir;
Q_strncpyz(cwd, Sys_Dirname(cwd), sizeof(cwd));
if(strcmp(Sys_Basename(cwd), "Contents"))
return dir;
Q_strncpyz(cwd, Sys_Dirname(cwd), sizeof(cwd));
if(!strstr(Sys_Basename(cwd), ".app"))
return dir;
Q_strncpyz(cwd, Sys_Dirname(cwd), sizeof(cwd));
return cwd;
}
#endif
#ifndef DEFAULT_BASEDIR
# ifdef MACOS_X
# define DEFAULT_BASEDIR Sys_StripAppBundle(Sys_BinaryPath())
# else
# define DEFAULT_BASEDIR Sys_BinaryPath()
# endif
#endif
int main ( int argc, char* argv[] )
{
int i;
char commandLine[ MAX_STRING_CHARS ] = { 0 };
Sys_PlatformInit();
CON_Init();
// get the initial time base
Sys_Milliseconds();
#ifdef MACOS_X
// This is passed if we are launched by double-clicking
if ( argc >= 2 && Q_strncmp ( argv[1], "-psn", 4 ) == 0 )
argc = 1;
#endif
Sys_SetBinaryPath( Sys_Dirname( argv[ 0 ] ) );
Sys_SetDefaultInstallPath( DEFAULT_BASEDIR );
// Concatenate the command line for passing to Com_Init
for( i = 1; i < argc; i++ )
{
const bool containsSpaces = (strchr(argv[i], ' ') != NULL);
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), argv[ i ] );
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), " " );
}
Com_Init (commandLine);
NET_Init();
// main game loop
while (1)
{
if ( com_busyWait->integer )
{
bool shouldSleep = false;
#if !defined(_JK2EXE)
if ( com_dedicated->integer )
{
shouldSleep = true;
}
#endif
if ( com_minimized->integer )
{
shouldSleep = true;
}
if ( shouldSleep )
{
Sys_Sleep( 5 );
}
}
// run the game
Com_Frame();
}
// never gets here
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/cpp/bad_3234_4 |
crossvul-cpp_data_bad_1350_0 | #include "CMOS.h"
#include "Process.h"
#include "StdLib.h"
#include <AK/Assertions.h>
#include <AK/kstdio.h>
#include <Kernel/Arch/i386/CPU.h>
#include <Kernel/FileSystem/Inode.h>
#include <Kernel/Multiboot.h>
#include <Kernel/VM/AnonymousVMObject.h>
#include <Kernel/VM/InodeVMObject.h>
#include <Kernel/VM/MemoryManager.h>
#include <Kernel/VM/PurgeableVMObject.h>
//#define MM_DEBUG
//#define PAGE_FAULT_DEBUG
static MemoryManager* s_the;
MemoryManager& MM
{
return *s_the;
}
MemoryManager::MemoryManager(u32 physical_address_for_kernel_page_tables)
{
CPUID id(0x80000001);
m_has_nx_support = (id.edx() & (1 << 20)) != 0;
m_kernel_page_directory = PageDirectory::create_at_fixed_address(PhysicalAddress(physical_address_for_kernel_page_tables));
for (size_t i = 0; i < 4; ++i) {
m_low_page_tables[i] = (PageTableEntry*)(physical_address_for_kernel_page_tables + PAGE_SIZE * (5 + i));
memset(m_low_page_tables[i], 0, PAGE_SIZE);
}
initialize_paging();
kprintf("MM initialized.\n");
}
MemoryManager::~MemoryManager()
{
}
void MemoryManager::initialize_paging()
{
#ifdef MM_DEBUG
dbgprintf("MM: Kernel page directory @ %p\n", kernel_page_directory().cr3());
#endif
#ifdef MM_DEBUG
dbgprintf("MM: Protect against null dereferences\n");
#endif
// Make null dereferences crash.
map_protected(VirtualAddress(0), PAGE_SIZE);
#ifdef MM_DEBUG
dbgprintf("MM: Identity map bottom 8MB\n");
#endif
// The bottom 8 MB (except for the null page) are identity mapped & supervisor only.
// Every process shares these mappings.
create_identity_mapping(kernel_page_directory(), VirtualAddress(PAGE_SIZE), (8 * MB) - PAGE_SIZE);
// Disable execution from 0MB through 1MB (BIOS data, legacy things, ...)
for (size_t i = 0; i < (1 * MB); ++i) {
auto& pte = ensure_pte(kernel_page_directory(), VirtualAddress(i));
if (m_has_nx_support)
pte.set_execute_disabled(true);
}
// Disable execution from 2MB through 8MB (kmalloc, kmalloc_eternal, slabs, page tables, ...)
for (size_t i = 1; i < 4; ++i) {
auto& pte = kernel_page_directory().table().directory(0)[i];
if (m_has_nx_support)
pte.set_execute_disabled(true);
}
// FIXME: We should move everything kernel-related above the 0xc0000000 virtual mark.
// Basic physical memory map:
// 0 -> 1 MB We're just leaving this alone for now.
// 1 -> 3 MB Kernel image.
// (last page before 2MB) Used by quickmap_page().
// 2 MB -> 4 MB kmalloc_eternal() space.
// 4 MB -> 7 MB kmalloc() space.
// 7 MB -> 8 MB Supervisor physical pages (available for allocation!)
// 8 MB -> MAX Userspace physical pages (available for allocation!)
// Basic virtual memory map:
// 0 -> 4 KB Null page (so nullptr dereferences crash!)
// 4 KB -> 8 MB Identity mapped.
// 8 MB -> 3 GB Available to userspace.
// 3GB -> 4 GB Kernel-only virtual address space (>0xc0000000)
#ifdef MM_DEBUG
dbgprintf("MM: Quickmap will use %p\n", m_quickmap_addr.get());
#endif
m_quickmap_addr = VirtualAddress((2 * MB) - PAGE_SIZE);
RefPtr<PhysicalRegion> region;
bool region_is_super = false;
for (auto* mmap = (multiboot_memory_map_t*)multiboot_info_ptr->mmap_addr; (unsigned long)mmap < multiboot_info_ptr->mmap_addr + multiboot_info_ptr->mmap_length; mmap = (multiboot_memory_map_t*)((unsigned long)mmap + mmap->size + sizeof(mmap->size))) {
kprintf("MM: Multiboot mmap: base_addr = 0x%x%08x, length = 0x%x%08x, type = 0x%x\n",
(u32)(mmap->addr >> 32),
(u32)(mmap->addr & 0xffffffff),
(u32)(mmap->len >> 32),
(u32)(mmap->len & 0xffffffff),
(u32)mmap->type);
if (mmap->type != MULTIBOOT_MEMORY_AVAILABLE)
continue;
// FIXME: Maybe make use of stuff below the 1MB mark?
if (mmap->addr < (1 * MB))
continue;
if ((mmap->addr + mmap->len) > 0xffffffff)
continue;
auto diff = (u32)mmap->addr % PAGE_SIZE;
if (diff != 0) {
kprintf("MM: got an unaligned region base from the bootloader; correcting %p by %d bytes\n", mmap->addr, diff);
diff = PAGE_SIZE - diff;
mmap->addr += diff;
mmap->len -= diff;
}
if ((mmap->len % PAGE_SIZE) != 0) {
kprintf("MM: got an unaligned region length from the bootloader; correcting %d by %d bytes\n", mmap->len, mmap->len % PAGE_SIZE);
mmap->len -= mmap->len % PAGE_SIZE;
}
if (mmap->len < PAGE_SIZE) {
kprintf("MM: memory region from bootloader is too small; we want >= %d bytes, but got %d bytes\n", PAGE_SIZE, mmap->len);
continue;
}
#ifdef MM_DEBUG
kprintf("MM: considering memory at %p - %p\n",
(u32)mmap->addr, (u32)(mmap->addr + mmap->len));
#endif
for (size_t page_base = mmap->addr; page_base < (mmap->addr + mmap->len); page_base += PAGE_SIZE) {
auto addr = PhysicalAddress(page_base);
if (page_base < 7 * MB) {
// nothing
} else if (page_base >= 7 * MB && page_base < 8 * MB) {
if (region.is_null() || !region_is_super || region->upper().offset(PAGE_SIZE) != addr) {
m_super_physical_regions.append(PhysicalRegion::create(addr, addr));
region = m_super_physical_regions.last();
region_is_super = true;
} else {
region->expand(region->lower(), addr);
}
} else {
if (region.is_null() || region_is_super || region->upper().offset(PAGE_SIZE) != addr) {
m_user_physical_regions.append(PhysicalRegion::create(addr, addr));
region = m_user_physical_regions.last();
region_is_super = false;
} else {
region->expand(region->lower(), addr);
}
}
}
}
for (auto& region : m_super_physical_regions)
m_super_physical_pages += region.finalize_capacity();
for (auto& region : m_user_physical_regions)
m_user_physical_pages += region.finalize_capacity();
#ifdef MM_DEBUG
dbgprintf("MM: Installing page directory\n");
#endif
// Turn on CR4.PGE so the CPU will respect the G bit in page tables.
asm volatile(
"mov %cr4, %eax\n"
"orl $0x80, %eax\n"
"mov %eax, %cr4\n");
// Turn on CR4.PAE
asm volatile(
"mov %cr4, %eax\n"
"orl $0x20, %eax\n"
"mov %eax, %cr4\n");
if (m_has_nx_support) {
kprintf("MM: NX support detected; enabling NXE flag\n");
// Turn on IA32_EFER.NXE
asm volatile(
"movl $0xc0000080, %ecx\n"
"rdmsr\n"
"orl $0x800, %eax\n"
"wrmsr\n");
} else {
kprintf("MM: NX support not detected\n");
}
asm volatile("movl %%eax, %%cr3" ::"a"(kernel_page_directory().cr3()));
asm volatile(
"movl %%cr0, %%eax\n"
"orl $0x80010001, %%eax\n"
"movl %%eax, %%cr0\n" ::
: "%eax", "memory");
#ifdef MM_DEBUG
dbgprintf("MM: Paging initialized.\n");
#endif
}
PageTableEntry& MemoryManager::ensure_pte(PageDirectory& page_directory, VirtualAddress vaddr)
{
ASSERT_INTERRUPTS_DISABLED();
u32 page_directory_table_index = (vaddr.get() >> 30) & 0x3;
u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
PageDirectoryEntry& pde = page_directory.table().directory(page_directory_table_index)[page_directory_index];
if (!pde.is_present()) {
#ifdef MM_DEBUG
dbgprintf("MM: PDE %u not present (requested for V%p), allocating\n", page_directory_index, vaddr.get());
#endif
if (page_directory_table_index == 0 && page_directory_index < 4) {
ASSERT(&page_directory == m_kernel_page_directory);
pde.set_page_table_base((u32)m_low_page_tables[page_directory_index]);
pde.set_user_allowed(false);
pde.set_present(true);
pde.set_writable(true);
pde.set_global(true);
} else {
auto page_table = allocate_supervisor_physical_page();
#ifdef MM_DEBUG
dbgprintf("MM: PD K%p (%s) at P%p allocated page table #%u (for V%p) at P%p\n",
&page_directory,
&page_directory == m_kernel_page_directory ? "Kernel" : "User",
page_directory.cr3(),
page_directory_index,
vaddr.get(),
page_table->paddr().get());
#endif
pde.set_page_table_base(page_table->paddr().get());
pde.set_user_allowed(true);
pde.set_present(true);
pde.set_writable(true);
pde.set_global(&page_directory == m_kernel_page_directory.ptr());
page_directory.m_physical_pages.set(page_directory_index, move(page_table));
}
}
return pde.page_table_base()[page_table_index];
}
void MemoryManager::map_protected(VirtualAddress vaddr, size_t length)
{
InterruptDisabler disabler;
ASSERT(vaddr.is_page_aligned());
for (u32 offset = 0; offset < length; offset += PAGE_SIZE) {
auto pte_address = vaddr.offset(offset);
auto& pte = ensure_pte(kernel_page_directory(), pte_address);
pte.set_physical_page_base(pte_address.get());
pte.set_user_allowed(false);
pte.set_present(false);
pte.set_writable(false);
flush_tlb(pte_address);
}
}
void MemoryManager::create_identity_mapping(PageDirectory& page_directory, VirtualAddress vaddr, size_t size)
{
InterruptDisabler disabler;
ASSERT((vaddr.get() & ~PAGE_MASK) == 0);
for (u32 offset = 0; offset < size; offset += PAGE_SIZE) {
auto pte_address = vaddr.offset(offset);
auto& pte = ensure_pte(page_directory, pte_address);
pte.set_physical_page_base(pte_address.get());
pte.set_user_allowed(false);
pte.set_present(true);
pte.set_writable(true);
page_directory.flush(pte_address);
}
}
void MemoryManager::initialize(u32 physical_address_for_kernel_page_tables)
{
s_the = new MemoryManager(physical_address_for_kernel_page_tables);
}
Region* MemoryManager::kernel_region_from_vaddr(VirtualAddress vaddr)
{
if (vaddr.get() < 0xc0000000)
return nullptr;
for (auto& region : MM.m_kernel_regions) {
if (region.contains(vaddr))
return ®ion;
}
return nullptr;
}
Region* MemoryManager::user_region_from_vaddr(Process& process, VirtualAddress vaddr)
{
// FIXME: Use a binary search tree (maybe red/black?) or some other more appropriate data structure!
for (auto& region : process.m_regions) {
if (region.contains(vaddr))
return ®ion;
}
dbg() << process << " Couldn't find user region for " << vaddr;
return nullptr;
}
Region* MemoryManager::region_from_vaddr(Process& process, VirtualAddress vaddr)
{
if (auto* region = kernel_region_from_vaddr(vaddr))
return region;
return user_region_from_vaddr(process, vaddr);
}
const Region* MemoryManager::region_from_vaddr(const Process& process, VirtualAddress vaddr)
{
if (auto* region = kernel_region_from_vaddr(vaddr))
return region;
return user_region_from_vaddr(const_cast<Process&>(process), vaddr);
}
Region* MemoryManager::region_from_vaddr(VirtualAddress vaddr)
{
if (auto* region = kernel_region_from_vaddr(vaddr))
return region;
auto page_directory = PageDirectory::find_by_cr3(cpu_cr3());
if (!page_directory)
return nullptr;
ASSERT(page_directory->process());
return user_region_from_vaddr(*page_directory->process(), vaddr);
}
PageFaultResponse MemoryManager::handle_page_fault(const PageFault& fault)
{
ASSERT_INTERRUPTS_DISABLED();
ASSERT(current);
#ifdef PAGE_FAULT_DEBUG
dbgprintf("MM: handle_page_fault(%w) at V%p\n", fault.code(), fault.vaddr().get());
#endif
ASSERT(fault.vaddr() != m_quickmap_addr);
auto* region = region_from_vaddr(fault.vaddr());
if (!region) {
kprintf("NP(error) fault at invalid address V%p\n", fault.vaddr().get());
return PageFaultResponse::ShouldCrash;
}
return region->handle_fault(fault);
}
OwnPtr<Region> MemoryManager::allocate_kernel_region(size_t size, const StringView& name, u8 access, bool user_accessible, bool should_commit)
{
InterruptDisabler disabler;
ASSERT(!(size % PAGE_SIZE));
auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
ASSERT(range.is_valid());
OwnPtr<Region> region;
if (user_accessible)
region = Region::create_user_accessible(range, name, access);
else
region = Region::create_kernel_only(range, name, access);
region->map(kernel_page_directory());
// FIXME: It would be cool if these could zero-fill on demand instead.
if (should_commit)
region->commit();
return region;
}
OwnPtr<Region> MemoryManager::allocate_user_accessible_kernel_region(size_t size, const StringView& name, u8 access)
{
return allocate_kernel_region(size, name, access, true);
}
OwnPtr<Region> MemoryManager::allocate_kernel_region_with_vmobject(VMObject& vmobject, size_t size, const StringView& name, u8 access)
{
InterruptDisabler disabler;
ASSERT(!(size % PAGE_SIZE));
auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
ASSERT(range.is_valid());
auto region = make<Region>(range, vmobject, 0, name, access);
region->map(kernel_page_directory());
return region;
}
void MemoryManager::deallocate_user_physical_page(PhysicalPage&& page)
{
for (auto& region : m_user_physical_regions) {
if (!region.contains(page)) {
kprintf(
"MM: deallocate_user_physical_page: %p not in %p -> %p\n",
page.paddr().get(), region.lower().get(), region.upper().get());
continue;
}
region.return_page(move(page));
--m_user_physical_pages_used;
return;
}
kprintf("MM: deallocate_user_physical_page couldn't figure out region for user page @ %p\n", page.paddr().get());
ASSERT_NOT_REACHED();
}
RefPtr<PhysicalPage> MemoryManager::find_free_user_physical_page()
{
RefPtr<PhysicalPage> page;
for (auto& region : m_user_physical_regions) {
page = region.take_free_page(false);
if (!page.is_null())
break;
}
return page;
}
RefPtr<PhysicalPage> MemoryManager::allocate_user_physical_page(ShouldZeroFill should_zero_fill)
{
InterruptDisabler disabler;
RefPtr<PhysicalPage> page = find_free_user_physical_page();
if (!page) {
if (m_user_physical_regions.is_empty()) {
kprintf("MM: no user physical regions available (?)\n");
}
for_each_vmobject([&](auto& vmobject) {
if (vmobject.is_purgeable()) {
auto& purgeable_vmobject = static_cast<PurgeableVMObject&>(vmobject);
int purged_page_count = purgeable_vmobject.purge_with_interrupts_disabled({});
if (purged_page_count) {
kprintf("MM: Purge saved the day! Purged %d pages from PurgeableVMObject{%p}\n", purged_page_count, &purgeable_vmobject);
page = find_free_user_physical_page();
ASSERT(page);
return IterationDecision::Break;
}
}
return IterationDecision::Continue;
});
if (!page) {
kprintf("MM: no user physical pages available\n");
ASSERT_NOT_REACHED();
return {};
}
}
#ifdef MM_DEBUG
dbgprintf("MM: allocate_user_physical_page vending P%p\n", page->paddr().get());
#endif
if (should_zero_fill == ShouldZeroFill::Yes) {
auto* ptr = (u32*)quickmap_page(*page);
fast_u32_fill(ptr, 0, PAGE_SIZE / sizeof(u32));
unquickmap_page();
}
++m_user_physical_pages_used;
return page;
}
void MemoryManager::deallocate_supervisor_physical_page(PhysicalPage&& page)
{
for (auto& region : m_super_physical_regions) {
if (!region.contains(page)) {
kprintf(
"MM: deallocate_supervisor_physical_page: %p not in %p -> %p\n",
page.paddr().get(), region.lower().get(), region.upper().get());
continue;
}
region.return_page(move(page));
--m_super_physical_pages_used;
return;
}
kprintf("MM: deallocate_supervisor_physical_page couldn't figure out region for super page @ %p\n", page.paddr().get());
ASSERT_NOT_REACHED();
}
RefPtr<PhysicalPage> MemoryManager::allocate_supervisor_physical_page()
{
InterruptDisabler disabler;
RefPtr<PhysicalPage> page;
for (auto& region : m_super_physical_regions) {
page = region.take_free_page(true);
if (page.is_null())
continue;
}
if (!page) {
if (m_super_physical_regions.is_empty()) {
kprintf("MM: no super physical regions available (?)\n");
}
kprintf("MM: no super physical pages available\n");
ASSERT_NOT_REACHED();
return {};
}
#ifdef MM_DEBUG
dbgprintf("MM: allocate_supervisor_physical_page vending P%p\n", page->paddr().get());
#endif
fast_u32_fill((u32*)page->paddr().as_ptr(), 0, PAGE_SIZE / sizeof(u32));
++m_super_physical_pages_used;
return page;
}
void MemoryManager::enter_process_paging_scope(Process& process)
{
ASSERT(current);
InterruptDisabler disabler;
current->tss().cr3 = process.page_directory().cr3();
asm volatile("movl %%eax, %%cr3" ::"a"(process.page_directory().cr3())
: "memory");
}
void MemoryManager::flush_entire_tlb()
{
asm volatile(
"mov %%cr3, %%eax\n"
"mov %%eax, %%cr3\n" ::
: "%eax", "memory");
}
void MemoryManager::flush_tlb(VirtualAddress vaddr)
{
asm volatile("invlpg %0"
:
: "m"(*(char*)vaddr.get())
: "memory");
}
void MemoryManager::map_for_kernel(VirtualAddress vaddr, PhysicalAddress paddr, bool cache_disabled)
{
auto& pte = ensure_pte(kernel_page_directory(), vaddr);
pte.set_physical_page_base(paddr.get());
pte.set_present(true);
pte.set_writable(true);
pte.set_user_allowed(false);
pte.set_cache_disabled(cache_disabled);
flush_tlb(vaddr);
}
u8* MemoryManager::quickmap_page(PhysicalPage& physical_page)
{
ASSERT_INTERRUPTS_DISABLED();
ASSERT(!m_quickmap_in_use);
m_quickmap_in_use = true;
auto page_vaddr = m_quickmap_addr;
auto& pte = ensure_pte(kernel_page_directory(), page_vaddr);
pte.set_physical_page_base(physical_page.paddr().get());
pte.set_present(true);
pte.set_writable(true);
pte.set_user_allowed(false);
flush_tlb(page_vaddr);
ASSERT((u32)pte.physical_page_base() == physical_page.paddr().get());
#ifdef MM_DEBUG
dbg() << "MM: >> quickmap_page " << page_vaddr << " => " << physical_page.paddr() << " @ PTE=" << (void*)pte.raw() << " {" << &pte << "}";
#endif
return page_vaddr.as_ptr();
}
void MemoryManager::unquickmap_page()
{
ASSERT_INTERRUPTS_DISABLED();
ASSERT(m_quickmap_in_use);
auto page_vaddr = m_quickmap_addr;
auto& pte = ensure_pte(kernel_page_directory(), page_vaddr);
#ifdef MM_DEBUG
auto old_physical_address = pte.physical_page_base();
#endif
pte.set_physical_page_base(0);
pte.set_present(false);
pte.set_writable(false);
flush_tlb(page_vaddr);
#ifdef MM_DEBUG
dbg() << "MM: >> unquickmap_page " << page_vaddr << " =/> " << old_physical_address;
#endif
m_quickmap_in_use = false;
}
bool MemoryManager::validate_user_stack(const Process& process, VirtualAddress vaddr) const
{
auto* region = region_from_vaddr(process, vaddr);
return region && region->is_stack();
}
bool MemoryManager::validate_user_read(const Process& process, VirtualAddress vaddr) const
{
auto* region = region_from_vaddr(process, vaddr);
return region && region->is_readable();
}
bool MemoryManager::validate_user_write(const Process& process, VirtualAddress vaddr) const
{
auto* region = region_from_vaddr(process, vaddr);
return region && region->is_writable();
}
void MemoryManager::register_vmobject(VMObject& vmobject)
{
InterruptDisabler disabler;
m_vmobjects.append(&vmobject);
}
void MemoryManager::unregister_vmobject(VMObject& vmobject)
{
InterruptDisabler disabler;
m_vmobjects.remove(&vmobject);
}
void MemoryManager::register_region(Region& region)
{
InterruptDisabler disabler;
if (region.vaddr().get() >= 0xc0000000)
m_kernel_regions.append(®ion);
else
m_user_regions.append(®ion);
}
void MemoryManager::unregister_region(Region& region)
{
InterruptDisabler disabler;
if (region.vaddr().get() >= 0xc0000000)
m_kernel_regions.remove(®ion);
else
m_user_regions.remove(®ion);
}
ProcessPagingScope::ProcessPagingScope(Process& process)
{
ASSERT(current);
MM.enter_process_paging_scope(process);
}
ProcessPagingScope::~ProcessPagingScope()
{
MM.enter_process_paging_scope(current->process());
}
| ./CrossVul/dataset_final_sorted/CWE-269/cpp/bad_1350_0 |
crossvul-cpp_data_bad_3233_2 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include <signal.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/types.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#ifndef DEDICATED
#ifdef USE_LOCAL_HEADERS
# include "SDL.h"
# include "SDL_cpuinfo.h"
#else
# include <SDL.h>
# include <SDL_cpuinfo.h>
#endif
#endif
#include "sys_local.h"
#include "sys_loadlib.h"
#include "../qcommon/q_shared.h"
#include "../qcommon/qcommon.h"
static char binaryPath[ MAX_OSPATH ] = { 0 };
static char installPath[ MAX_OSPATH ] = { 0 };
/*
=================
Sys_SetBinaryPath
=================
*/
void Sys_SetBinaryPath(const char *path)
{
Q_strncpyz(binaryPath, path, sizeof(binaryPath));
}
/*
=================
Sys_BinaryPath
=================
*/
char *Sys_BinaryPath(void)
{
return binaryPath;
}
/*
=================
Sys_SetDefaultInstallPath
=================
*/
void Sys_SetDefaultInstallPath(const char *path)
{
Q_strncpyz(installPath, path, sizeof(installPath));
}
/*
=================
Sys_DefaultInstallPath
=================
*/
char *Sys_DefaultInstallPath(void)
{
if (*installPath)
return installPath;
else
return Sys_Cwd();
}
/*
=================
Sys_DefaultAppPath
=================
*/
char *Sys_DefaultAppPath(void)
{
return Sys_BinaryPath();
}
/*
=================
Sys_In_Restart_f
Restart the input subsystem
=================
*/
void Sys_In_Restart_f( void )
{
IN_Restart( );
}
/*
=================
Sys_ConsoleInput
Handle new console input
=================
*/
char *Sys_ConsoleInput(void)
{
return CON_Input( );
}
/*
==================
Sys_GetClipboardData
==================
*/
char *Sys_GetClipboardData(void)
{
#ifdef DEDICATED
return NULL;
#else
char *data = NULL;
char *cliptext;
if ( ( cliptext = SDL_GetClipboardText() ) != NULL ) {
if ( cliptext[0] != '\0' ) {
size_t bufsize = strlen( cliptext ) + 1;
data = Z_Malloc( bufsize );
Q_strncpyz( data, cliptext, bufsize );
// find first listed char and set to '\0'
strtok( data, "\n\r\b" );
}
SDL_free( cliptext );
}
return data;
#endif
}
#ifdef DEDICATED
# define PID_FILENAME "iowolfmp_server.pid"
#else
# define PID_FILENAME "iowolfmp.pid"
#endif
/*
=================
Sys_PIDFileName
=================
*/
static char *Sys_PIDFileName( const char *gamedir )
{
const char *homePath = Cvar_VariableString( "fs_homepath" );
if( *homePath != '\0' )
return va( "%s/%s/%s", homePath, gamedir, PID_FILENAME );
return NULL;
}
/*
=================
Sys_RemovePIDFile
=================
*/
void Sys_RemovePIDFile( const char *gamedir )
{
char *pidFile = Sys_PIDFileName( gamedir );
if( pidFile != NULL )
remove( pidFile );
}
/*
=================
Sys_WritePIDFile
Return qtrue if there is an existing stale PID file
=================
*/
static qboolean Sys_WritePIDFile( const char *gamedir )
{
char *pidFile = Sys_PIDFileName( gamedir );
FILE *f;
qboolean stale = qfalse;
if( pidFile == NULL )
return qfalse;
// First, check if the pid file is already there
if( ( f = fopen( pidFile, "r" ) ) != NULL )
{
char pidBuffer[ 64 ] = { 0 };
int pid;
pid = fread( pidBuffer, sizeof( char ), sizeof( pidBuffer ) - 1, f );
fclose( f );
if(pid > 0)
{
pid = atoi( pidBuffer );
if( !Sys_PIDIsRunning( pid ) )
stale = qtrue;
}
else
stale = qtrue;
}
if( FS_CreatePath( pidFile ) ) {
return 0;
}
if( ( f = fopen( pidFile, "w" ) ) != NULL )
{
fprintf( f, "%d", Sys_PID( ) );
fclose( f );
}
else
Com_Printf( S_COLOR_YELLOW "Couldn't write %s.\n", pidFile );
return stale;
}
/*
=================
Sys_InitPIDFile
=================
*/
void Sys_InitPIDFile( const char *gamedir ) {
if( Sys_WritePIDFile( gamedir ) ) {
#ifndef DEDICATED
char message[1024];
char modName[MAX_OSPATH];
FS_GetModDescription( gamedir, modName, sizeof ( modName ) );
Q_CleanStr( modName );
Com_sprintf( message, sizeof (message), "The last time %s ran, "
"it didn't exit properly. This may be due to inappropriate video "
"settings. Would you like to start with \"safe\" video settings?", modName );
if( Sys_Dialog( DT_YES_NO, message, "Abnormal Exit" ) == DR_YES ) {
Cvar_Set( "com_abnormalExit", "1" );
}
#endif
}
}
/*
=================
Sys_Exit
Single exit point (regular exit or in case of error)
=================
*/
static __attribute__ ((noreturn)) void Sys_Exit( int exitCode )
{
CON_Shutdown( );
#ifndef DEDICATED
SDL_Quit( );
#endif
if( exitCode < 2 && com_fullyInitialized )
{
// Normal exit
Sys_RemovePIDFile( FS_GetCurrentGameDir() );
}
NET_Shutdown( );
Sys_PlatformExit( );
exit( exitCode );
}
/*
=================
Sys_Quit
=================
*/
void Sys_Quit( void )
{
Sys_Exit( 0 );
}
/*
=================
Sys_GetProcessorFeatures
=================
*/
cpuFeatures_t Sys_GetProcessorFeatures( void )
{
cpuFeatures_t features = 0;
#ifndef DEDICATED
if( SDL_HasRDTSC( ) ) features |= CF_RDTSC;
if( SDL_Has3DNow( ) ) features |= CF_3DNOW;
if( SDL_HasMMX( ) ) features |= CF_MMX;
if( SDL_HasSSE( ) ) features |= CF_SSE;
if( SDL_HasSSE2( ) ) features |= CF_SSE2;
if( SDL_HasAltiVec( ) ) features |= CF_ALTIVEC;
#endif
return features;
}
/*
=================
Sys_Init
=================
*/
void Sys_Init(void)
{
Cmd_AddCommand( "in_restart", Sys_In_Restart_f );
Cvar_Set( "arch", OS_STRING " " ARCH_STRING );
Cvar_Set( "username", Sys_GetCurrentUser( ) );
}
/*
=================
Sys_AnsiColorPrint
Transform Q3 colour codes to ANSI escape sequences
=================
*/
void Sys_AnsiColorPrint( const char *msg )
{
static char buffer[ MAXPRINTMSG ];
int length = 0;
static int q3ToAnsi[ 8 ] =
{
30, // COLOR_BLACK
31, // COLOR_RED
32, // COLOR_GREEN
33, // COLOR_YELLOW
34, // COLOR_BLUE
36, // COLOR_CYAN
35, // COLOR_MAGENTA
0 // COLOR_WHITE
};
while( *msg )
{
if( Q_IsColorString( msg ) || *msg == '\n' )
{
// First empty the buffer
if( length > 0 )
{
buffer[ length ] = '\0';
fputs( buffer, stderr );
length = 0;
}
if( *msg == '\n' )
{
// Issue a reset and then the newline
fputs( "\033[0m\n", stderr );
msg++;
}
else
{
// Print the color code
Com_sprintf( buffer, sizeof( buffer ), "\033[%dm",
q3ToAnsi[ ColorIndex( *( msg + 1 ) ) ] );
fputs( buffer, stderr );
msg += 2;
}
}
else
{
if( length >= MAXPRINTMSG - 1 )
break;
buffer[ length ] = *msg;
length++;
msg++;
}
}
// Empty anything still left in the buffer
if( length > 0 )
{
buffer[ length ] = '\0';
fputs( buffer, stderr );
}
}
/*
=================
Sys_Print
=================
*/
void Sys_Print( const char *msg )
{
CON_LogWrite( msg );
CON_Print( msg );
}
/*
=================
Sys_Error
=================
*/
void Sys_Error( const char *error, ... )
{
va_list argptr;
char string[1024];
va_start (argptr,error);
Q_vsnprintf (string, sizeof(string), error, argptr);
va_end (argptr);
Sys_ErrorDialog( string );
Sys_Exit( 3 );
}
#if 0
/*
=================
Sys_Warn
=================
*/
static __attribute__ ((format (printf, 1, 2))) void Sys_Warn( char *warning, ... )
{
va_list argptr;
char string[1024];
va_start (argptr,warning);
Q_vsnprintf (string, sizeof(string), warning, argptr);
va_end (argptr);
CON_Print( va( "Warning: %s", string ) );
}
#endif
/*
============
Sys_FileTime
returns -1 if not present
============
*/
int Sys_FileTime( char *path )
{
struct stat buf;
if (stat (path,&buf) == -1)
return -1;
return buf.st_mtime;
}
/*
=================
Sys_UnloadDll
=================
*/
void Sys_UnloadDll( void *dllHandle )
{
if( !dllHandle )
{
Com_Printf("Sys_UnloadDll(NULL)\n");
return;
}
Sys_UnloadLibrary(dllHandle);
}
/*
=================
Sys_LoadDll
First try to load library name from system library path,
from executable path, then fs_basepath.
=================
*/
void *Sys_LoadDll(const char *name, qboolean useSystemLib)
{
void *dllhandle;
if(useSystemLib)
Com_Printf("Trying to load \"%s\"...\n", name);
if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name)))
{
const char *topDir;
char libPath[MAX_OSPATH];
topDir = Sys_BinaryPath();
if(!*topDir)
topDir = ".";
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name);
if(!(dllhandle = Sys_LoadLibrary(libPath)))
{
const char *basePath = Cvar_VariableString("fs_basepath");
if(!basePath || !*basePath)
basePath = ".";
if(FS_FilenameCompare(topDir, basePath))
{
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name);
dllhandle = Sys_LoadLibrary(libPath);
}
if(!dllhandle)
Com_Printf("Loading \"%s\" failed\n", name);
}
}
return dllhandle;
}
/*
=================
Sys_LoadGameDll
Used to load a development dll instead of a virtual machine
=================
*/
void *Sys_LoadGameDll(const char *name,
intptr_t (QDECL **entryPoint)(intptr_t, ...),
intptr_t (*systemcalls)(intptr_t, ...))
{
void *libHandle;
void (*dllEntry)(intptr_t (*syscallptr)(intptr_t, ...));
assert(name);
Com_Printf( "Loading DLL file: %s\n", name);
libHandle = Sys_LoadLibrary(name);
if(!libHandle)
{
Com_Printf("Sys_LoadGameDll(%s) failed:\n\"%s\"\n", name, Sys_LibraryError());
return NULL;
}
dllEntry = Sys_LoadFunction( libHandle, "dllEntry" );
*entryPoint = Sys_LoadFunction( libHandle, "vmMain" );
if ( !*entryPoint || !dllEntry )
{
Com_Printf ( "Sys_LoadGameDll(%s) failed to find vmMain function:\n\"%s\" !\n", name, Sys_LibraryError( ) );
Sys_UnloadLibrary(libHandle);
return NULL;
}
Com_Printf ( "Sys_LoadGameDll(%s) found vmMain function at %p\n", name, *entryPoint );
dllEntry( systemcalls );
return libHandle;
}
/*
=================
Sys_ParseArgs
=================
*/
void Sys_ParseArgs( int argc, char **argv )
{
if( argc == 2 )
{
if( !strcmp( argv[1], "--version" ) ||
!strcmp( argv[1], "-v" ) )
{
const char* date = PRODUCT_DATE;
#ifdef DEDICATED
fprintf( stdout, Q3_VERSION " dedicated server (%s)\n", date );
#else
fprintf( stdout, Q3_VERSION " client (%s)\n", date );
#endif
Sys_Exit( 0 );
}
}
}
#ifndef DEFAULT_BASEDIR
# ifdef __APPLE__
# define DEFAULT_BASEDIR Sys_StripAppBundle(Sys_BinaryPath())
# else
# define DEFAULT_BASEDIR Sys_BinaryPath()
# endif
#endif
/*
=================
Sys_SigHandler
=================
*/
void Sys_SigHandler( int signal )
{
static qboolean signalcaught = qfalse;
if( signalcaught )
{
fprintf( stderr, "DOUBLE SIGNAL FAULT: Received signal %d, exiting...\n",
signal );
}
else
{
signalcaught = qtrue;
VM_Forced_Unload_Start();
#ifndef DEDICATED
CL_Shutdown(va("Received signal %d", signal), qtrue, qtrue);
#endif
SV_Shutdown(va("Received signal %d", signal) );
VM_Forced_Unload_Done();
}
if( signal == SIGTERM || signal == SIGINT )
Sys_Exit( 1 );
else
Sys_Exit( 2 );
}
/*
=================
main
=================
*/
int main( int argc, char **argv )
{
int i;
char commandLine[ MAX_STRING_CHARS ] = { 0 };
#ifndef DEDICATED
// SDL version check
// Compile time
# if !SDL_VERSION_ATLEAST(MINSDL_MAJOR,MINSDL_MINOR,MINSDL_PATCH)
# error A more recent version of SDL is required
# endif
// Run time
SDL_version ver;
SDL_GetVersion( &ver );
#define MINSDL_VERSION \
XSTRING(MINSDL_MAJOR) "." \
XSTRING(MINSDL_MINOR) "." \
XSTRING(MINSDL_PATCH)
if( SDL_VERSIONNUM( ver.major, ver.minor, ver.patch ) <
SDL_VERSIONNUM( MINSDL_MAJOR, MINSDL_MINOR, MINSDL_PATCH ) )
{
Sys_Dialog( DT_ERROR, va( "SDL version " MINSDL_VERSION " or greater is required, "
"but only version %d.%d.%d was found. You may be able to obtain a more recent copy "
"from http://www.libsdl.org/.", ver.major, ver.minor, ver.patch ), "SDL Library Too Old" );
Sys_Exit( 1 );
}
#endif
Sys_PlatformInit( );
// Set the initial time base
Sys_Milliseconds( );
#ifdef __APPLE__
// This is passed if we are launched by double-clicking
if ( argc >= 2 && Q_strncmp ( argv[1], "-psn", 4 ) == 0 )
argc = 1;
#endif
Sys_ParseArgs( argc, argv );
Sys_SetBinaryPath( Sys_Dirname( argv[ 0 ] ) );
Sys_SetDefaultInstallPath( DEFAULT_BASEDIR );
// Concatenate the command line for passing to Com_Init
for( i = 1; i < argc; i++ )
{
const qboolean containsSpaces = strchr(argv[i], ' ') != NULL;
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), argv[ i ] );
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), " " );
}
Com_Init( commandLine );
NET_Init( );
CON_Init( );
signal( SIGILL, Sys_SigHandler );
signal( SIGFPE, Sys_SigHandler );
signal( SIGSEGV, Sys_SigHandler );
signal( SIGTERM, Sys_SigHandler );
signal( SIGINT, Sys_SigHandler );
while( 1 )
{
IN_Frame( );
Com_Frame( );
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3233_2 |
crossvul-cpp_data_bad_4004_0 | /*
* Marvell Wireless LAN device driver: scan ioctl and command handling
*
* Copyright (C) 2011-2014, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
*/
#include "decl.h"
#include "ioctl.h"
#include "util.h"
#include "fw.h"
#include "main.h"
#include "11n.h"
#include "cfg80211.h"
/* The maximum number of channels the firmware can scan per command */
#define MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN 14
#define MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD 4
/* Memory needed to store a max sized Channel List TLV for a firmware scan */
#define CHAN_TLV_MAX_SIZE (sizeof(struct mwifiex_ie_types_header) \
+ (MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN \
*sizeof(struct mwifiex_chan_scan_param_set)))
/* Memory needed to store supported rate */
#define RATE_TLV_MAX_SIZE (sizeof(struct mwifiex_ie_types_rates_param_set) \
+ HOSTCMD_SUPPORTED_RATES)
/* Memory needed to store a max number/size WildCard SSID TLV for a firmware
scan */
#define WILDCARD_SSID_TLV_MAX_SIZE \
(MWIFIEX_MAX_SSID_LIST_LENGTH * \
(sizeof(struct mwifiex_ie_types_wildcard_ssid_params) \
+ IEEE80211_MAX_SSID_LEN))
/* Maximum memory needed for a mwifiex_scan_cmd_config with all TLVs at max */
#define MAX_SCAN_CFG_ALLOC (sizeof(struct mwifiex_scan_cmd_config) \
+ sizeof(struct mwifiex_ie_types_num_probes) \
+ sizeof(struct mwifiex_ie_types_htcap) \
+ CHAN_TLV_MAX_SIZE \
+ RATE_TLV_MAX_SIZE \
+ WILDCARD_SSID_TLV_MAX_SIZE)
union mwifiex_scan_cmd_config_tlv {
/* Scan configuration (variable length) */
struct mwifiex_scan_cmd_config config;
/* Max allocated block */
u8 config_alloc_buf[MAX_SCAN_CFG_ALLOC];
};
enum cipher_suite {
CIPHER_SUITE_TKIP,
CIPHER_SUITE_CCMP,
CIPHER_SUITE_MAX
};
static u8 mwifiex_wpa_oui[CIPHER_SUITE_MAX][4] = {
{ 0x00, 0x50, 0xf2, 0x02 }, /* TKIP */
{ 0x00, 0x50, 0xf2, 0x04 }, /* AES */
};
static u8 mwifiex_rsn_oui[CIPHER_SUITE_MAX][4] = {
{ 0x00, 0x0f, 0xac, 0x02 }, /* TKIP */
{ 0x00, 0x0f, 0xac, 0x04 }, /* AES */
};
static void
_dbg_security_flags(int log_level, const char *func, const char *desc,
struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
_mwifiex_dbg(priv->adapter, log_level,
"info: %s: %s:\twpa_ie=%#x wpa2_ie=%#x WEP=%s WPA=%s WPA2=%s\tEncMode=%#x privacy=%#x\n",
func, desc,
bss_desc->bcn_wpa_ie ?
bss_desc->bcn_wpa_ie->vend_hdr.element_id : 0,
bss_desc->bcn_rsn_ie ?
bss_desc->bcn_rsn_ie->ieee_hdr.element_id : 0,
priv->sec_info.wep_enabled ? "e" : "d",
priv->sec_info.wpa_enabled ? "e" : "d",
priv->sec_info.wpa2_enabled ? "e" : "d",
priv->sec_info.encryption_mode,
bss_desc->privacy);
}
#define dbg_security_flags(mask, desc, priv, bss_desc) \
_dbg_security_flags(MWIFIEX_DBG_##mask, desc, __func__, priv, bss_desc)
static bool
has_ieee_hdr(struct ieee_types_generic *ie, u8 key)
{
return (ie && ie->ieee_hdr.element_id == key);
}
static bool
has_vendor_hdr(struct ieee_types_vendor_specific *ie, u8 key)
{
return (ie && ie->vend_hdr.element_id == key);
}
/*
* This function parses a given IE for a given OUI.
*
* This is used to parse a WPA/RSN IE to find if it has
* a given oui in PTK.
*/
static u8
mwifiex_search_oui_in_ie(struct ie_body *iebody, u8 *oui)
{
u8 count;
count = iebody->ptk_cnt[0];
/* There could be multiple OUIs for PTK hence
1) Take the length.
2) Check all the OUIs for AES.
3) If one of them is AES then pass success. */
while (count) {
if (!memcmp(iebody->ptk_body, oui, sizeof(iebody->ptk_body)))
return MWIFIEX_OUI_PRESENT;
--count;
if (count)
iebody = (struct ie_body *) ((u8 *) iebody +
sizeof(iebody->ptk_body));
}
pr_debug("info: %s: OUI is not found in PTK\n", __func__);
return MWIFIEX_OUI_NOT_PRESENT;
}
/*
* This function checks if a given OUI is present in a RSN IE.
*
* The function first checks if a RSN IE is present or not in the
* BSS descriptor. It tries to locate the OUI only if such an IE is
* present.
*/
static u8
mwifiex_is_rsn_oui_present(struct mwifiex_bssdescriptor *bss_desc, u32 cipher)
{
u8 *oui;
struct ie_body *iebody;
u8 ret = MWIFIEX_OUI_NOT_PRESENT;
if (has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN)) {
iebody = (struct ie_body *)
(((u8 *) bss_desc->bcn_rsn_ie->data) +
RSN_GTK_OUI_OFFSET);
oui = &mwifiex_rsn_oui[cipher][0];
ret = mwifiex_search_oui_in_ie(iebody, oui);
if (ret)
return ret;
}
return ret;
}
/*
* This function checks if a given OUI is present in a WPA IE.
*
* The function first checks if a WPA IE is present or not in the
* BSS descriptor. It tries to locate the OUI only if such an IE is
* present.
*/
static u8
mwifiex_is_wpa_oui_present(struct mwifiex_bssdescriptor *bss_desc, u32 cipher)
{
u8 *oui;
struct ie_body *iebody;
u8 ret = MWIFIEX_OUI_NOT_PRESENT;
if (has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC)) {
iebody = (struct ie_body *)((u8 *)bss_desc->bcn_wpa_ie->data +
WPA_GTK_OUI_OFFSET);
oui = &mwifiex_wpa_oui[cipher][0];
ret = mwifiex_search_oui_in_ie(iebody, oui);
if (ret)
return ret;
}
return ret;
}
/*
* This function compares two SSIDs and checks if they match.
*/
s32
mwifiex_ssid_cmp(struct cfg80211_ssid *ssid1, struct cfg80211_ssid *ssid2)
{
if (!ssid1 || !ssid2 || (ssid1->ssid_len != ssid2->ssid_len))
return -1;
return memcmp(ssid1->ssid, ssid2->ssid, ssid1->ssid_len);
}
/*
* This function checks if wapi is enabled in driver and scanned network is
* compatible with it.
*/
static bool
mwifiex_is_bss_wapi(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (priv->sec_info.wapi_enabled &&
has_ieee_hdr(bss_desc->bcn_wapi_ie, WLAN_EID_BSS_AC_ACCESS_DELAY))
return true;
return false;
}
/*
* This function checks if driver is configured with no security mode and
* scanned network is compatible with it.
*/
static bool
mwifiex_is_bss_no_sec(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled &&
!priv->sec_info.wpa2_enabled &&
!has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) &&
!has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN) &&
!priv->sec_info.encryption_mode && !bss_desc->privacy) {
return true;
}
return false;
}
/*
* This function checks if static WEP is enabled in driver and scanned network
* is compatible with it.
*/
static bool
mwifiex_is_bss_static_wep(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled &&
!priv->sec_info.wpa2_enabled && bss_desc->privacy) {
return true;
}
return false;
}
/*
* This function checks if wpa is enabled in driver and scanned network is
* compatible with it.
*/
static bool
mwifiex_is_bss_wpa(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (!priv->sec_info.wep_enabled && priv->sec_info.wpa_enabled &&
!priv->sec_info.wpa2_enabled &&
has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC)
/*
* Privacy bit may NOT be set in some APs like
* LinkSys WRT54G && bss_desc->privacy
*/
) {
dbg_security_flags(INFO, "WPA", priv, bss_desc);
return true;
}
return false;
}
/*
* This function checks if wpa2 is enabled in driver and scanned network is
* compatible with it.
*/
static bool
mwifiex_is_bss_wpa2(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled &&
priv->sec_info.wpa2_enabled &&
has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN)) {
/*
* Privacy bit may NOT be set in some APs like
* LinkSys WRT54G && bss_desc->privacy
*/
dbg_security_flags(INFO, "WAP2", priv, bss_desc);
return true;
}
return false;
}
/*
* This function checks if adhoc AES is enabled in driver and scanned network is
* compatible with it.
*/
static bool
mwifiex_is_bss_adhoc_aes(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled &&
!priv->sec_info.wpa2_enabled &&
!has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) &&
!has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN) &&
!priv->sec_info.encryption_mode && bss_desc->privacy) {
return true;
}
return false;
}
/*
* This function checks if dynamic WEP is enabled in driver and scanned network
* is compatible with it.
*/
static bool
mwifiex_is_bss_dynamic_wep(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled &&
!priv->sec_info.wpa2_enabled &&
!has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) &&
!has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN) &&
priv->sec_info.encryption_mode && bss_desc->privacy) {
dbg_security_flags(INFO, "dynamic", priv, bss_desc);
return true;
}
return false;
}
/*
* This function checks if a scanned network is compatible with the driver
* settings.
*
* WEP WPA WPA2 ad-hoc encrypt Network
* enabled enabled enabled AES mode Privacy WPA WPA2 Compatible
* 0 0 0 0 NONE 0 0 0 yes No security
* 0 1 0 0 x 1x 1 x yes WPA (disable
* HT if no AES)
* 0 0 1 0 x 1x x 1 yes WPA2 (disable
* HT if no AES)
* 0 0 0 1 NONE 1 0 0 yes Ad-hoc AES
* 1 0 0 0 NONE 1 0 0 yes Static WEP
* (disable HT)
* 0 0 0 0 !=NONE 1 0 0 yes Dynamic WEP
*
* Compatibility is not matched while roaming, except for mode.
*/
static s32
mwifiex_is_network_compatible(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc, u32 mode)
{
struct mwifiex_adapter *adapter = priv->adapter;
bss_desc->disable_11n = false;
/* Don't check for compatibility if roaming */
if (priv->media_connected &&
(priv->bss_mode == NL80211_IFTYPE_STATION) &&
(bss_desc->bss_mode == NL80211_IFTYPE_STATION))
return 0;
if (priv->wps.session_enable) {
mwifiex_dbg(adapter, IOCTL,
"info: return success directly in WPS period\n");
return 0;
}
if (bss_desc->chan_sw_ie_present) {
mwifiex_dbg(adapter, INFO,
"Don't connect to AP with WLAN_EID_CHANNEL_SWITCH\n");
return -1;
}
if (mwifiex_is_bss_wapi(priv, bss_desc)) {
mwifiex_dbg(adapter, INFO,
"info: return success for WAPI AP\n");
return 0;
}
if (bss_desc->bss_mode == mode) {
if (mwifiex_is_bss_no_sec(priv, bss_desc)) {
/* No security */
return 0;
} else if (mwifiex_is_bss_static_wep(priv, bss_desc)) {
/* Static WEP enabled */
mwifiex_dbg(adapter, INFO,
"info: Disable 11n in WEP mode.\n");
bss_desc->disable_11n = true;
return 0;
} else if (mwifiex_is_bss_wpa(priv, bss_desc)) {
/* WPA enabled */
if (((priv->adapter->config_bands & BAND_GN ||
priv->adapter->config_bands & BAND_AN) &&
bss_desc->bcn_ht_cap) &&
!mwifiex_is_wpa_oui_present(bss_desc,
CIPHER_SUITE_CCMP)) {
if (mwifiex_is_wpa_oui_present
(bss_desc, CIPHER_SUITE_TKIP)) {
mwifiex_dbg(adapter, INFO,
"info: Disable 11n if AES\t"
"is not supported by AP\n");
bss_desc->disable_11n = true;
} else {
return -1;
}
}
return 0;
} else if (mwifiex_is_bss_wpa2(priv, bss_desc)) {
/* WPA2 enabled */
if (((priv->adapter->config_bands & BAND_GN ||
priv->adapter->config_bands & BAND_AN) &&
bss_desc->bcn_ht_cap) &&
!mwifiex_is_rsn_oui_present(bss_desc,
CIPHER_SUITE_CCMP)) {
if (mwifiex_is_rsn_oui_present
(bss_desc, CIPHER_SUITE_TKIP)) {
mwifiex_dbg(adapter, INFO,
"info: Disable 11n if AES\t"
"is not supported by AP\n");
bss_desc->disable_11n = true;
} else {
return -1;
}
}
return 0;
} else if (mwifiex_is_bss_adhoc_aes(priv, bss_desc)) {
/* Ad-hoc AES enabled */
return 0;
} else if (mwifiex_is_bss_dynamic_wep(priv, bss_desc)) {
/* Dynamic WEP enabled */
return 0;
}
/* Security doesn't match */
dbg_security_flags(ERROR, "failed", priv, bss_desc);
return -1;
}
/* Mode doesn't match */
return -1;
}
/*
* This function creates a channel list for the driver to scan, based
* on region/band information.
*
* This routine is used for any scan that is not provided with a
* specific channel list to scan.
*/
static int
mwifiex_scan_create_channel_list(struct mwifiex_private *priv,
const struct mwifiex_user_scan_cfg
*user_scan_in,
struct mwifiex_chan_scan_param_set
*scan_chan_list,
u8 filtered_scan)
{
enum nl80211_band band;
struct ieee80211_supported_band *sband;
struct ieee80211_channel *ch;
struct mwifiex_adapter *adapter = priv->adapter;
int chan_idx = 0, i;
for (band = 0; (band < NUM_NL80211_BANDS) ; band++) {
if (!priv->wdev.wiphy->bands[band])
continue;
sband = priv->wdev.wiphy->bands[band];
for (i = 0; (i < sband->n_channels) ; i++) {
ch = &sband->channels[i];
if (ch->flags & IEEE80211_CHAN_DISABLED)
continue;
scan_chan_list[chan_idx].radio_type = band;
if (user_scan_in &&
user_scan_in->chan_list[0].scan_time)
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16((u16) user_scan_in->
chan_list[0].scan_time);
else if ((ch->flags & IEEE80211_CHAN_NO_IR) ||
(ch->flags & IEEE80211_CHAN_RADAR))
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16(adapter->passive_scan_time);
else
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16(adapter->active_scan_time);
if (ch->flags & IEEE80211_CHAN_NO_IR)
scan_chan_list[chan_idx].chan_scan_mode_bitmap
|= (MWIFIEX_PASSIVE_SCAN |
MWIFIEX_HIDDEN_SSID_REPORT);
else
scan_chan_list[chan_idx].chan_scan_mode_bitmap
&= ~MWIFIEX_PASSIVE_SCAN;
scan_chan_list[chan_idx].chan_number =
(u32) ch->hw_value;
scan_chan_list[chan_idx].chan_scan_mode_bitmap
|= MWIFIEX_DISABLE_CHAN_FILT;
if (filtered_scan &&
!((ch->flags & IEEE80211_CHAN_NO_IR) ||
(ch->flags & IEEE80211_CHAN_RADAR)))
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16(adapter->specific_scan_time);
chan_idx++;
}
}
return chan_idx;
}
/* This function creates a channel list tlv for bgscan config, based
* on region/band information.
*/
static int
mwifiex_bgscan_create_channel_list(struct mwifiex_private *priv,
const struct mwifiex_bg_scan_cfg
*bgscan_cfg_in,
struct mwifiex_chan_scan_param_set
*scan_chan_list)
{
enum nl80211_band band;
struct ieee80211_supported_band *sband;
struct ieee80211_channel *ch;
struct mwifiex_adapter *adapter = priv->adapter;
int chan_idx = 0, i;
for (band = 0; (band < NUM_NL80211_BANDS); band++) {
if (!priv->wdev.wiphy->bands[band])
continue;
sband = priv->wdev.wiphy->bands[band];
for (i = 0; (i < sband->n_channels) ; i++) {
ch = &sband->channels[i];
if (ch->flags & IEEE80211_CHAN_DISABLED)
continue;
scan_chan_list[chan_idx].radio_type = band;
if (bgscan_cfg_in->chan_list[0].scan_time)
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16((u16)bgscan_cfg_in->
chan_list[0].scan_time);
else if (ch->flags & IEEE80211_CHAN_NO_IR)
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16(adapter->passive_scan_time);
else
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16(adapter->
specific_scan_time);
if (ch->flags & IEEE80211_CHAN_NO_IR)
scan_chan_list[chan_idx].chan_scan_mode_bitmap
|= MWIFIEX_PASSIVE_SCAN;
else
scan_chan_list[chan_idx].chan_scan_mode_bitmap
&= ~MWIFIEX_PASSIVE_SCAN;
scan_chan_list[chan_idx].chan_number =
(u32)ch->hw_value;
chan_idx++;
}
}
return chan_idx;
}
/* This function appends rate TLV to scan config command. */
static int
mwifiex_append_rate_tlv(struct mwifiex_private *priv,
struct mwifiex_scan_cmd_config *scan_cfg_out,
u8 radio)
{
struct mwifiex_ie_types_rates_param_set *rates_tlv;
u8 rates[MWIFIEX_SUPPORTED_RATES], *tlv_pos;
u32 rates_size;
memset(rates, 0, sizeof(rates));
tlv_pos = (u8 *)scan_cfg_out->tlv_buf + scan_cfg_out->tlv_buf_len;
if (priv->scan_request)
rates_size = mwifiex_get_rates_from_cfg80211(priv, rates,
radio);
else
rates_size = mwifiex_get_supported_rates(priv, rates);
mwifiex_dbg(priv->adapter, CMD,
"info: SCAN_CMD: Rates size = %d\n",
rates_size);
rates_tlv = (struct mwifiex_ie_types_rates_param_set *)tlv_pos;
rates_tlv->header.type = cpu_to_le16(WLAN_EID_SUPP_RATES);
rates_tlv->header.len = cpu_to_le16((u16) rates_size);
memcpy(rates_tlv->rates, rates, rates_size);
scan_cfg_out->tlv_buf_len += sizeof(rates_tlv->header) + rates_size;
return rates_size;
}
/*
* This function constructs and sends multiple scan config commands to
* the firmware.
*
* Previous routines in the code flow have created a scan command configuration
* with any requested TLVs. This function splits the channel TLV into maximum
* channels supported per scan lists and sends the portion of the channel TLV,
* along with the other TLVs, to the firmware.
*/
static int
mwifiex_scan_channel_list(struct mwifiex_private *priv,
u32 max_chan_per_scan, u8 filtered_scan,
struct mwifiex_scan_cmd_config *scan_cfg_out,
struct mwifiex_ie_types_chan_list_param_set
*chan_tlv_out,
struct mwifiex_chan_scan_param_set *scan_chan_list)
{
struct mwifiex_adapter *adapter = priv->adapter;
int ret = 0;
struct mwifiex_chan_scan_param_set *tmp_chan_list;
struct mwifiex_chan_scan_param_set *start_chan;
u32 tlv_idx, rates_size, cmd_no;
u32 total_scan_time;
u32 done_early;
u8 radio_type;
if (!scan_cfg_out || !chan_tlv_out || !scan_chan_list) {
mwifiex_dbg(priv->adapter, ERROR,
"info: Scan: Null detect: %p, %p, %p\n",
scan_cfg_out, chan_tlv_out, scan_chan_list);
return -1;
}
/* Check csa channel expiry before preparing scan list */
mwifiex_11h_get_csa_closed_channel(priv);
chan_tlv_out->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);
/* Set the temp channel struct pointer to the start of the desired
list */
tmp_chan_list = scan_chan_list;
/* Loop through the desired channel list, sending a new firmware scan
commands for each max_chan_per_scan channels (or for 1,6,11
individually if configured accordingly) */
while (tmp_chan_list->chan_number) {
tlv_idx = 0;
total_scan_time = 0;
radio_type = 0;
chan_tlv_out->header.len = 0;
start_chan = tmp_chan_list;
done_early = false;
/*
* Construct the Channel TLV for the scan command. Continue to
* insert channel TLVs until:
* - the tlv_idx hits the maximum configured per scan command
* - the next channel to insert is 0 (end of desired channel
* list)
* - done_early is set (controlling individual scanning of
* 1,6,11)
*/
while (tlv_idx < max_chan_per_scan &&
tmp_chan_list->chan_number && !done_early) {
if (tmp_chan_list->chan_number == priv->csa_chan) {
tmp_chan_list++;
continue;
}
radio_type = tmp_chan_list->radio_type;
mwifiex_dbg(priv->adapter, INFO,
"info: Scan: Chan(%3d), Radio(%d),\t"
"Mode(%d, %d), Dur(%d)\n",
tmp_chan_list->chan_number,
tmp_chan_list->radio_type,
tmp_chan_list->chan_scan_mode_bitmap
& MWIFIEX_PASSIVE_SCAN,
(tmp_chan_list->chan_scan_mode_bitmap
& MWIFIEX_DISABLE_CHAN_FILT) >> 1,
le16_to_cpu(tmp_chan_list->max_scan_time));
/* Copy the current channel TLV to the command being
prepared */
memcpy(chan_tlv_out->chan_scan_param + tlv_idx,
tmp_chan_list,
sizeof(chan_tlv_out->chan_scan_param));
/* Increment the TLV header length by the size
appended */
le16_unaligned_add_cpu(&chan_tlv_out->header.len,
sizeof(
chan_tlv_out->chan_scan_param));
/*
* The tlv buffer length is set to the number of bytes
* of the between the channel tlv pointer and the start
* of the tlv buffer. This compensates for any TLVs
* that were appended before the channel list.
*/
scan_cfg_out->tlv_buf_len = (u32) ((u8 *) chan_tlv_out -
scan_cfg_out->tlv_buf);
/* Add the size of the channel tlv header and the data
length */
scan_cfg_out->tlv_buf_len +=
(sizeof(chan_tlv_out->header)
+ le16_to_cpu(chan_tlv_out->header.len));
/* Increment the index to the channel tlv we are
constructing */
tlv_idx++;
/* Count the total scan time per command */
total_scan_time +=
le16_to_cpu(tmp_chan_list->max_scan_time);
done_early = false;
/* Stop the loop if the *current* channel is in the
1,6,11 set and we are not filtering on a BSSID
or SSID. */
if (!filtered_scan &&
(tmp_chan_list->chan_number == 1 ||
tmp_chan_list->chan_number == 6 ||
tmp_chan_list->chan_number == 11))
done_early = true;
/* Increment the tmp pointer to the next channel to
be scanned */
tmp_chan_list++;
/* Stop the loop if the *next* channel is in the 1,6,11
set. This will cause it to be the only channel
scanned on the next interation */
if (!filtered_scan &&
(tmp_chan_list->chan_number == 1 ||
tmp_chan_list->chan_number == 6 ||
tmp_chan_list->chan_number == 11))
done_early = true;
}
/* The total scan time should be less than scan command timeout
value */
if (total_scan_time > MWIFIEX_MAX_TOTAL_SCAN_TIME) {
mwifiex_dbg(priv->adapter, ERROR,
"total scan time %dms\t"
"is over limit (%dms), scan skipped\n",
total_scan_time,
MWIFIEX_MAX_TOTAL_SCAN_TIME);
ret = -1;
break;
}
rates_size = mwifiex_append_rate_tlv(priv, scan_cfg_out,
radio_type);
priv->adapter->scan_channels = start_chan;
/* Send the scan command to the firmware with the specified
cfg */
if (priv->adapter->ext_scan)
cmd_no = HostCmd_CMD_802_11_SCAN_EXT;
else
cmd_no = HostCmd_CMD_802_11_SCAN;
ret = mwifiex_send_cmd(priv, cmd_no, HostCmd_ACT_GEN_SET,
0, scan_cfg_out, false);
/* rate IE is updated per scan command but same starting
* pointer is used each time so that rate IE from earlier
* scan_cfg_out->buf is overwritten with new one.
*/
scan_cfg_out->tlv_buf_len -=
sizeof(struct mwifiex_ie_types_header) + rates_size;
if (ret) {
mwifiex_cancel_pending_scan_cmd(adapter);
break;
}
}
if (ret)
return -1;
return 0;
}
/*
* This function constructs a scan command configuration structure to use
* in scan commands.
*
* Application layer or other functions can invoke network scanning
* with a scan configuration supplied in a user scan configuration structure.
* This structure is used as the basis of one or many scan command configuration
* commands that are sent to the command processing module and eventually to the
* firmware.
*
* This function creates a scan command configuration structure based on the
* following user supplied parameters (if present):
* - SSID filter
* - BSSID filter
* - Number of Probes to be sent
* - Channel list
*
* If the SSID or BSSID filter is not present, the filter is disabled/cleared.
* If the number of probes is not set, adapter default setting is used.
*/
static void
mwifiex_config_scan(struct mwifiex_private *priv,
const struct mwifiex_user_scan_cfg *user_scan_in,
struct mwifiex_scan_cmd_config *scan_cfg_out,
struct mwifiex_ie_types_chan_list_param_set **chan_list_out,
struct mwifiex_chan_scan_param_set *scan_chan_list,
u8 *max_chan_per_scan, u8 *filtered_scan,
u8 *scan_current_only)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_ie_types_num_probes *num_probes_tlv;
struct mwifiex_ie_types_scan_chan_gap *chan_gap_tlv;
struct mwifiex_ie_types_random_mac *random_mac_tlv;
struct mwifiex_ie_types_wildcard_ssid_params *wildcard_ssid_tlv;
struct mwifiex_ie_types_bssid_list *bssid_tlv;
u8 *tlv_pos;
u32 num_probes;
u32 ssid_len;
u32 chan_idx;
u32 scan_type;
u16 scan_dur;
u8 channel;
u8 radio_type;
int i;
u8 ssid_filter;
struct mwifiex_ie_types_htcap *ht_cap;
struct mwifiex_ie_types_bss_mode *bss_mode;
const u8 zero_mac[6] = {0, 0, 0, 0, 0, 0};
/* The tlv_buf_len is calculated for each scan command. The TLVs added
in this routine will be preserved since the routine that sends the
command will append channelTLVs at *chan_list_out. The difference
between the *chan_list_out and the tlv_buf start will be used to
calculate the size of anything we add in this routine. */
scan_cfg_out->tlv_buf_len = 0;
/* Running tlv pointer. Assigned to chan_list_out at end of function
so later routines know where channels can be added to the command
buf */
tlv_pos = scan_cfg_out->tlv_buf;
/* Initialize the scan as un-filtered; the flag is later set to TRUE
below if a SSID or BSSID filter is sent in the command */
*filtered_scan = false;
/* Initialize the scan as not being only on the current channel. If
the channel list is customized, only contains one channel, and is
the active channel, this is set true and data flow is not halted. */
*scan_current_only = false;
if (user_scan_in) {
u8 tmpaddr[ETH_ALEN];
/* Default the ssid_filter flag to TRUE, set false under
certain wildcard conditions and qualified by the existence
of an SSID list before marking the scan as filtered */
ssid_filter = true;
/* Set the BSS type scan filter, use Adapter setting if
unset */
scan_cfg_out->bss_mode =
(u8)(user_scan_in->bss_mode ?: adapter->scan_mode);
/* Set the number of probes to send, use Adapter setting
if unset */
num_probes = user_scan_in->num_probes ?: adapter->scan_probes;
/*
* Set the BSSID filter to the incoming configuration,
* if non-zero. If not set, it will remain disabled
* (all zeros).
*/
memcpy(scan_cfg_out->specific_bssid,
user_scan_in->specific_bssid,
sizeof(scan_cfg_out->specific_bssid));
memcpy(tmpaddr, scan_cfg_out->specific_bssid, ETH_ALEN);
if (adapter->ext_scan &&
!is_zero_ether_addr(tmpaddr)) {
bssid_tlv =
(struct mwifiex_ie_types_bssid_list *)tlv_pos;
bssid_tlv->header.type = cpu_to_le16(TLV_TYPE_BSSID);
bssid_tlv->header.len = cpu_to_le16(ETH_ALEN);
memcpy(bssid_tlv->bssid, user_scan_in->specific_bssid,
ETH_ALEN);
tlv_pos += sizeof(struct mwifiex_ie_types_bssid_list);
}
for (i = 0; i < user_scan_in->num_ssids; i++) {
ssid_len = user_scan_in->ssid_list[i].ssid_len;
wildcard_ssid_tlv =
(struct mwifiex_ie_types_wildcard_ssid_params *)
tlv_pos;
wildcard_ssid_tlv->header.type =
cpu_to_le16(TLV_TYPE_WILDCARDSSID);
wildcard_ssid_tlv->header.len = cpu_to_le16(
(u16) (ssid_len + sizeof(wildcard_ssid_tlv->
max_ssid_length)));
/*
* max_ssid_length = 0 tells firmware to perform
* specific scan for the SSID filled, whereas
* max_ssid_length = IEEE80211_MAX_SSID_LEN is for
* wildcard scan.
*/
if (ssid_len)
wildcard_ssid_tlv->max_ssid_length = 0;
else
wildcard_ssid_tlv->max_ssid_length =
IEEE80211_MAX_SSID_LEN;
if (!memcmp(user_scan_in->ssid_list[i].ssid,
"DIRECT-", 7))
wildcard_ssid_tlv->max_ssid_length = 0xfe;
memcpy(wildcard_ssid_tlv->ssid,
user_scan_in->ssid_list[i].ssid, ssid_len);
tlv_pos += (sizeof(wildcard_ssid_tlv->header)
+ le16_to_cpu(wildcard_ssid_tlv->header.len));
mwifiex_dbg(adapter, INFO,
"info: scan: ssid[%d]: %s, %d\n",
i, wildcard_ssid_tlv->ssid,
wildcard_ssid_tlv->max_ssid_length);
/* Empty wildcard ssid with a maxlen will match many or
potentially all SSIDs (maxlen == 32), therefore do
not treat the scan as
filtered. */
if (!ssid_len && wildcard_ssid_tlv->max_ssid_length)
ssid_filter = false;
}
/*
* The default number of channels sent in the command is low to
* ensure the response buffer from the firmware does not
* truncate scan results. That is not an issue with an SSID
* or BSSID filter applied to the scan results in the firmware.
*/
memcpy(tmpaddr, scan_cfg_out->specific_bssid, ETH_ALEN);
if ((i && ssid_filter) ||
!is_zero_ether_addr(tmpaddr))
*filtered_scan = true;
if (user_scan_in->scan_chan_gap) {
mwifiex_dbg(adapter, INFO,
"info: scan: channel gap = %d\n",
user_scan_in->scan_chan_gap);
*max_chan_per_scan =
MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN;
chan_gap_tlv = (void *)tlv_pos;
chan_gap_tlv->header.type =
cpu_to_le16(TLV_TYPE_SCAN_CHANNEL_GAP);
chan_gap_tlv->header.len =
cpu_to_le16(sizeof(chan_gap_tlv->chan_gap));
chan_gap_tlv->chan_gap =
cpu_to_le16((user_scan_in->scan_chan_gap));
tlv_pos +=
sizeof(struct mwifiex_ie_types_scan_chan_gap);
}
if (!ether_addr_equal(user_scan_in->random_mac, zero_mac)) {
random_mac_tlv = (void *)tlv_pos;
random_mac_tlv->header.type =
cpu_to_le16(TLV_TYPE_RANDOM_MAC);
random_mac_tlv->header.len =
cpu_to_le16(sizeof(random_mac_tlv->mac));
ether_addr_copy(random_mac_tlv->mac,
user_scan_in->random_mac);
tlv_pos +=
sizeof(struct mwifiex_ie_types_random_mac);
}
} else {
scan_cfg_out->bss_mode = (u8) adapter->scan_mode;
num_probes = adapter->scan_probes;
}
/*
* If a specific BSSID or SSID is used, the number of channels in the
* scan command will be increased to the absolute maximum.
*/
if (*filtered_scan) {
*max_chan_per_scan = MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN;
} else {
if (!priv->media_connected)
*max_chan_per_scan = MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD;
else
*max_chan_per_scan =
MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD / 2;
}
if (adapter->ext_scan) {
bss_mode = (struct mwifiex_ie_types_bss_mode *)tlv_pos;
bss_mode->header.type = cpu_to_le16(TLV_TYPE_BSS_MODE);
bss_mode->header.len = cpu_to_le16(sizeof(bss_mode->bss_mode));
bss_mode->bss_mode = scan_cfg_out->bss_mode;
tlv_pos += sizeof(bss_mode->header) +
le16_to_cpu(bss_mode->header.len);
}
/* If the input config or adapter has the number of Probes set,
add tlv */
if (num_probes) {
mwifiex_dbg(adapter, INFO,
"info: scan: num_probes = %d\n",
num_probes);
num_probes_tlv = (struct mwifiex_ie_types_num_probes *) tlv_pos;
num_probes_tlv->header.type = cpu_to_le16(TLV_TYPE_NUMPROBES);
num_probes_tlv->header.len =
cpu_to_le16(sizeof(num_probes_tlv->num_probes));
num_probes_tlv->num_probes = cpu_to_le16((u16) num_probes);
tlv_pos += sizeof(num_probes_tlv->header) +
le16_to_cpu(num_probes_tlv->header.len);
}
if (ISSUPP_11NENABLED(priv->adapter->fw_cap_info) &&
(priv->adapter->config_bands & BAND_GN ||
priv->adapter->config_bands & BAND_AN)) {
ht_cap = (struct mwifiex_ie_types_htcap *) tlv_pos;
memset(ht_cap, 0, sizeof(struct mwifiex_ie_types_htcap));
ht_cap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY);
ht_cap->header.len =
cpu_to_le16(sizeof(struct ieee80211_ht_cap));
radio_type =
mwifiex_band_to_radio_type(priv->adapter->config_bands);
mwifiex_fill_cap_info(priv, radio_type, &ht_cap->ht_cap);
tlv_pos += sizeof(struct mwifiex_ie_types_htcap);
}
/* Append vendor specific IE TLV */
mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_SCAN, &tlv_pos);
/*
* Set the output for the channel TLV to the address in the tlv buffer
* past any TLVs that were added in this function (SSID, num_probes).
* Channel TLVs will be added past this for each scan command,
* preserving the TLVs that were previously added.
*/
*chan_list_out =
(struct mwifiex_ie_types_chan_list_param_set *) tlv_pos;
if (user_scan_in && user_scan_in->chan_list[0].chan_number) {
mwifiex_dbg(adapter, INFO,
"info: Scan: Using supplied channel list\n");
for (chan_idx = 0;
chan_idx < MWIFIEX_USER_SCAN_CHAN_MAX &&
user_scan_in->chan_list[chan_idx].chan_number;
chan_idx++) {
channel = user_scan_in->chan_list[chan_idx].chan_number;
scan_chan_list[chan_idx].chan_number = channel;
radio_type =
user_scan_in->chan_list[chan_idx].radio_type;
scan_chan_list[chan_idx].radio_type = radio_type;
scan_type = user_scan_in->chan_list[chan_idx].scan_type;
if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE)
scan_chan_list[chan_idx].chan_scan_mode_bitmap
|= (MWIFIEX_PASSIVE_SCAN |
MWIFIEX_HIDDEN_SSID_REPORT);
else
scan_chan_list[chan_idx].chan_scan_mode_bitmap
&= ~MWIFIEX_PASSIVE_SCAN;
scan_chan_list[chan_idx].chan_scan_mode_bitmap
|= MWIFIEX_DISABLE_CHAN_FILT;
if (user_scan_in->chan_list[chan_idx].scan_time) {
scan_dur = (u16) user_scan_in->
chan_list[chan_idx].scan_time;
} else {
if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE)
scan_dur = adapter->passive_scan_time;
else if (*filtered_scan)
scan_dur = adapter->specific_scan_time;
else
scan_dur = adapter->active_scan_time;
}
scan_chan_list[chan_idx].min_scan_time =
cpu_to_le16(scan_dur);
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16(scan_dur);
}
/* Check if we are only scanning the current channel */
if ((chan_idx == 1) &&
(user_scan_in->chan_list[0].chan_number ==
priv->curr_bss_params.bss_descriptor.channel)) {
*scan_current_only = true;
mwifiex_dbg(adapter, INFO,
"info: Scan: Scanning current channel only\n");
}
} else {
mwifiex_dbg(adapter, INFO,
"info: Scan: Creating full region channel list\n");
mwifiex_scan_create_channel_list(priv, user_scan_in,
scan_chan_list,
*filtered_scan);
}
}
/*
* This function inspects the scan response buffer for pointers to
* expected TLVs.
*
* TLVs can be included at the end of the scan response BSS information.
*
* Data in the buffer is parsed pointers to TLVs that can potentially
* be passed back in the response.
*/
static void
mwifiex_ret_802_11_scan_get_tlv_ptrs(struct mwifiex_adapter *adapter,
struct mwifiex_ie_types_data *tlv,
u32 tlv_buf_size, u32 req_tlv_type,
struct mwifiex_ie_types_data **tlv_data)
{
struct mwifiex_ie_types_data *current_tlv;
u32 tlv_buf_left;
u32 tlv_type;
u32 tlv_len;
current_tlv = tlv;
tlv_buf_left = tlv_buf_size;
*tlv_data = NULL;
mwifiex_dbg(adapter, INFO,
"info: SCAN_RESP: tlv_buf_size = %d\n",
tlv_buf_size);
while (tlv_buf_left >= sizeof(struct mwifiex_ie_types_header)) {
tlv_type = le16_to_cpu(current_tlv->header.type);
tlv_len = le16_to_cpu(current_tlv->header.len);
if (sizeof(tlv->header) + tlv_len > tlv_buf_left) {
mwifiex_dbg(adapter, ERROR,
"SCAN_RESP: TLV buffer corrupt\n");
break;
}
if (req_tlv_type == tlv_type) {
switch (tlv_type) {
case TLV_TYPE_TSFTIMESTAMP:
mwifiex_dbg(adapter, INFO,
"info: SCAN_RESP: TSF\t"
"timestamp TLV, len = %d\n",
tlv_len);
*tlv_data = current_tlv;
break;
case TLV_TYPE_CHANNELBANDLIST:
mwifiex_dbg(adapter, INFO,
"info: SCAN_RESP: channel\t"
"band list TLV, len = %d\n",
tlv_len);
*tlv_data = current_tlv;
break;
default:
mwifiex_dbg(adapter, ERROR,
"SCAN_RESP: unhandled TLV = %d\n",
tlv_type);
/* Give up, this seems corrupted */
return;
}
}
if (*tlv_data)
break;
tlv_buf_left -= (sizeof(tlv->header) + tlv_len);
current_tlv =
(struct mwifiex_ie_types_data *) (current_tlv->data +
tlv_len);
} /* while */
}
/*
* This function parses provided beacon buffer and updates
* respective fields in bss descriptor structure.
*/
int mwifiex_update_bss_desc_with_ie(struct mwifiex_adapter *adapter,
struct mwifiex_bssdescriptor *bss_entry)
{
int ret = 0;
u8 element_id;
struct ieee_types_fh_param_set *fh_param_set;
struct ieee_types_ds_param_set *ds_param_set;
struct ieee_types_cf_param_set *cf_param_set;
struct ieee_types_ibss_param_set *ibss_param_set;
u8 *current_ptr;
u8 *rate;
u8 element_len;
u16 total_ie_len;
u8 bytes_to_copy;
u8 rate_size;
u8 found_data_rate_ie;
u32 bytes_left;
struct ieee_types_vendor_specific *vendor_ie;
const u8 wpa_oui[4] = { 0x00, 0x50, 0xf2, 0x01 };
const u8 wmm_oui[4] = { 0x00, 0x50, 0xf2, 0x02 };
found_data_rate_ie = false;
rate_size = 0;
current_ptr = bss_entry->beacon_buf;
bytes_left = bss_entry->beacon_buf_size;
/* Process variable IE */
while (bytes_left >= 2) {
element_id = *current_ptr;
element_len = *(current_ptr + 1);
total_ie_len = element_len + sizeof(struct ieee_types_header);
if (bytes_left < total_ie_len) {
mwifiex_dbg(adapter, ERROR,
"err: InterpretIE: in processing\t"
"IE, bytes left < IE length\n");
return -EINVAL;
}
switch (element_id) {
case WLAN_EID_SSID:
if (element_len > IEEE80211_MAX_SSID_LEN)
return -EINVAL;
bss_entry->ssid.ssid_len = element_len;
memcpy(bss_entry->ssid.ssid, (current_ptr + 2),
element_len);
mwifiex_dbg(adapter, INFO,
"info: InterpretIE: ssid: %-32s\n",
bss_entry->ssid.ssid);
break;
case WLAN_EID_SUPP_RATES:
if (element_len > MWIFIEX_SUPPORTED_RATES)
return -EINVAL;
memcpy(bss_entry->data_rates, current_ptr + 2,
element_len);
memcpy(bss_entry->supported_rates, current_ptr + 2,
element_len);
rate_size = element_len;
found_data_rate_ie = true;
break;
case WLAN_EID_FH_PARAMS:
if (total_ie_len < sizeof(*fh_param_set))
return -EINVAL;
fh_param_set =
(struct ieee_types_fh_param_set *) current_ptr;
memcpy(&bss_entry->phy_param_set.fh_param_set,
fh_param_set,
sizeof(struct ieee_types_fh_param_set));
break;
case WLAN_EID_DS_PARAMS:
if (total_ie_len < sizeof(*ds_param_set))
return -EINVAL;
ds_param_set =
(struct ieee_types_ds_param_set *) current_ptr;
bss_entry->channel = ds_param_set->current_chan;
memcpy(&bss_entry->phy_param_set.ds_param_set,
ds_param_set,
sizeof(struct ieee_types_ds_param_set));
break;
case WLAN_EID_CF_PARAMS:
if (total_ie_len < sizeof(*cf_param_set))
return -EINVAL;
cf_param_set =
(struct ieee_types_cf_param_set *) current_ptr;
memcpy(&bss_entry->ss_param_set.cf_param_set,
cf_param_set,
sizeof(struct ieee_types_cf_param_set));
break;
case WLAN_EID_IBSS_PARAMS:
if (total_ie_len < sizeof(*ibss_param_set))
return -EINVAL;
ibss_param_set =
(struct ieee_types_ibss_param_set *)
current_ptr;
memcpy(&bss_entry->ss_param_set.ibss_param_set,
ibss_param_set,
sizeof(struct ieee_types_ibss_param_set));
break;
case WLAN_EID_ERP_INFO:
if (!element_len)
return -EINVAL;
bss_entry->erp_flags = *(current_ptr + 2);
break;
case WLAN_EID_PWR_CONSTRAINT:
if (!element_len)
return -EINVAL;
bss_entry->local_constraint = *(current_ptr + 2);
bss_entry->sensed_11h = true;
break;
case WLAN_EID_CHANNEL_SWITCH:
bss_entry->chan_sw_ie_present = true;
/* fall through */
case WLAN_EID_PWR_CAPABILITY:
case WLAN_EID_TPC_REPORT:
case WLAN_EID_QUIET:
bss_entry->sensed_11h = true;
break;
case WLAN_EID_EXT_SUPP_RATES:
/*
* Only process extended supported rate
* if data rate is already found.
* Data rate IE should come before
* extended supported rate IE
*/
if (found_data_rate_ie) {
if ((element_len + rate_size) >
MWIFIEX_SUPPORTED_RATES)
bytes_to_copy =
(MWIFIEX_SUPPORTED_RATES -
rate_size);
else
bytes_to_copy = element_len;
rate = (u8 *) bss_entry->data_rates;
rate += rate_size;
memcpy(rate, current_ptr + 2, bytes_to_copy);
rate = (u8 *) bss_entry->supported_rates;
rate += rate_size;
memcpy(rate, current_ptr + 2, bytes_to_copy);
}
break;
case WLAN_EID_VENDOR_SPECIFIC:
vendor_ie = (struct ieee_types_vendor_specific *)
current_ptr;
/* 802.11 requires at least 3-byte OUI. */
if (element_len < sizeof(vendor_ie->vend_hdr.oui.oui))
return -EINVAL;
/* Not long enough for a match? Skip it. */
if (element_len < sizeof(wpa_oui))
break;
if (!memcmp(&vendor_ie->vend_hdr.oui, wpa_oui,
sizeof(wpa_oui))) {
bss_entry->bcn_wpa_ie =
(struct ieee_types_vendor_specific *)
current_ptr;
bss_entry->wpa_offset = (u16)
(current_ptr - bss_entry->beacon_buf);
} else if (!memcmp(&vendor_ie->vend_hdr.oui, wmm_oui,
sizeof(wmm_oui))) {
if (total_ie_len ==
sizeof(struct ieee_types_wmm_parameter) ||
total_ie_len ==
sizeof(struct ieee_types_wmm_info))
/*
* Only accept and copy the WMM IE if
* it matches the size expected for the
* WMM Info IE or the WMM Parameter IE.
*/
memcpy((u8 *) &bss_entry->wmm_ie,
current_ptr, total_ie_len);
}
break;
case WLAN_EID_RSN:
bss_entry->bcn_rsn_ie =
(struct ieee_types_generic *) current_ptr;
bss_entry->rsn_offset = (u16) (current_ptr -
bss_entry->beacon_buf);
break;
case WLAN_EID_BSS_AC_ACCESS_DELAY:
bss_entry->bcn_wapi_ie =
(struct ieee_types_generic *) current_ptr;
bss_entry->wapi_offset = (u16) (current_ptr -
bss_entry->beacon_buf);
break;
case WLAN_EID_HT_CAPABILITY:
bss_entry->bcn_ht_cap = (struct ieee80211_ht_cap *)
(current_ptr +
sizeof(struct ieee_types_header));
bss_entry->ht_cap_offset = (u16) (current_ptr +
sizeof(struct ieee_types_header) -
bss_entry->beacon_buf);
break;
case WLAN_EID_HT_OPERATION:
bss_entry->bcn_ht_oper =
(struct ieee80211_ht_operation *)(current_ptr +
sizeof(struct ieee_types_header));
bss_entry->ht_info_offset = (u16) (current_ptr +
sizeof(struct ieee_types_header) -
bss_entry->beacon_buf);
break;
case WLAN_EID_VHT_CAPABILITY:
bss_entry->disable_11ac = false;
bss_entry->bcn_vht_cap =
(void *)(current_ptr +
sizeof(struct ieee_types_header));
bss_entry->vht_cap_offset =
(u16)((u8 *)bss_entry->bcn_vht_cap -
bss_entry->beacon_buf);
break;
case WLAN_EID_VHT_OPERATION:
bss_entry->bcn_vht_oper =
(void *)(current_ptr +
sizeof(struct ieee_types_header));
bss_entry->vht_info_offset =
(u16)((u8 *)bss_entry->bcn_vht_oper -
bss_entry->beacon_buf);
break;
case WLAN_EID_BSS_COEX_2040:
bss_entry->bcn_bss_co_2040 = current_ptr;
bss_entry->bss_co_2040_offset =
(u16) (current_ptr - bss_entry->beacon_buf);
break;
case WLAN_EID_EXT_CAPABILITY:
bss_entry->bcn_ext_cap = current_ptr;
bss_entry->ext_cap_offset =
(u16) (current_ptr - bss_entry->beacon_buf);
break;
case WLAN_EID_OPMODE_NOTIF:
bss_entry->oper_mode = (void *)current_ptr;
bss_entry->oper_mode_offset =
(u16)((u8 *)bss_entry->oper_mode -
bss_entry->beacon_buf);
break;
default:
break;
}
current_ptr += total_ie_len;
bytes_left -= total_ie_len;
} /* while (bytes_left > 2) */
return ret;
}
/*
* This function converts radio type scan parameter to a band configuration
* to be used in join command.
*/
static u8
mwifiex_radio_type_to_band(u8 radio_type)
{
switch (radio_type) {
case HostCmd_SCAN_RADIO_TYPE_A:
return BAND_A;
case HostCmd_SCAN_RADIO_TYPE_BG:
default:
return BAND_G;
}
}
/*
* This is an internal function used to start a scan based on an input
* configuration.
*
* This uses the input user scan configuration information when provided in
* order to send the appropriate scan commands to firmware to populate or
* update the internal driver scan table.
*/
int mwifiex_scan_networks(struct mwifiex_private *priv,
const struct mwifiex_user_scan_cfg *user_scan_in)
{
int ret;
struct mwifiex_adapter *adapter = priv->adapter;
struct cmd_ctrl_node *cmd_node;
union mwifiex_scan_cmd_config_tlv *scan_cfg_out;
struct mwifiex_ie_types_chan_list_param_set *chan_list_out;
struct mwifiex_chan_scan_param_set *scan_chan_list;
u8 filtered_scan;
u8 scan_current_chan_only;
u8 max_chan_per_scan;
if (adapter->scan_processing) {
mwifiex_dbg(adapter, WARN,
"cmd: Scan already in process...\n");
return -EBUSY;
}
if (priv->scan_block) {
mwifiex_dbg(adapter, WARN,
"cmd: Scan is blocked during association...\n");
return -EBUSY;
}
if (test_bit(MWIFIEX_SURPRISE_REMOVED, &adapter->work_flags) ||
test_bit(MWIFIEX_IS_CMD_TIMEDOUT, &adapter->work_flags)) {
mwifiex_dbg(adapter, ERROR,
"Ignore scan. Card removed or firmware in bad state\n");
return -EFAULT;
}
spin_lock_bh(&adapter->mwifiex_cmd_lock);
adapter->scan_processing = true;
spin_unlock_bh(&adapter->mwifiex_cmd_lock);
scan_cfg_out = kzalloc(sizeof(union mwifiex_scan_cmd_config_tlv),
GFP_KERNEL);
if (!scan_cfg_out) {
ret = -ENOMEM;
goto done;
}
scan_chan_list = kcalloc(MWIFIEX_USER_SCAN_CHAN_MAX,
sizeof(struct mwifiex_chan_scan_param_set),
GFP_KERNEL);
if (!scan_chan_list) {
kfree(scan_cfg_out);
ret = -ENOMEM;
goto done;
}
mwifiex_config_scan(priv, user_scan_in, &scan_cfg_out->config,
&chan_list_out, scan_chan_list, &max_chan_per_scan,
&filtered_scan, &scan_current_chan_only);
ret = mwifiex_scan_channel_list(priv, max_chan_per_scan, filtered_scan,
&scan_cfg_out->config, chan_list_out,
scan_chan_list);
/* Get scan command from scan_pending_q and put to cmd_pending_q */
if (!ret) {
spin_lock_bh(&adapter->scan_pending_q_lock);
if (!list_empty(&adapter->scan_pending_q)) {
cmd_node = list_first_entry(&adapter->scan_pending_q,
struct cmd_ctrl_node, list);
list_del(&cmd_node->list);
spin_unlock_bh(&adapter->scan_pending_q_lock);
mwifiex_insert_cmd_to_pending_q(adapter, cmd_node);
queue_work(adapter->workqueue, &adapter->main_work);
/* Perform internal scan synchronously */
if (!priv->scan_request) {
mwifiex_dbg(adapter, INFO,
"wait internal scan\n");
mwifiex_wait_queue_complete(adapter, cmd_node);
}
} else {
spin_unlock_bh(&adapter->scan_pending_q_lock);
}
}
kfree(scan_cfg_out);
kfree(scan_chan_list);
done:
if (ret) {
spin_lock_bh(&adapter->mwifiex_cmd_lock);
adapter->scan_processing = false;
spin_unlock_bh(&adapter->mwifiex_cmd_lock);
}
return ret;
}
/*
* This function prepares a scan command to be sent to the firmware.
*
* This uses the scan command configuration sent to the command processing
* module in command preparation stage to configure a scan command structure
* to send to firmware.
*
* The fixed fields specifying the BSS type and BSSID filters as well as a
* variable number/length of TLVs are sent in the command to firmware.
*
* Preparation also includes -
* - Setting command ID, and proper size
* - Ensuring correct endian-ness
*/
int mwifiex_cmd_802_11_scan(struct host_cmd_ds_command *cmd,
struct mwifiex_scan_cmd_config *scan_cfg)
{
struct host_cmd_ds_802_11_scan *scan_cmd = &cmd->params.scan;
/* Set fixed field variables in scan command */
scan_cmd->bss_mode = scan_cfg->bss_mode;
memcpy(scan_cmd->bssid, scan_cfg->specific_bssid,
sizeof(scan_cmd->bssid));
memcpy(scan_cmd->tlv_buffer, scan_cfg->tlv_buf, scan_cfg->tlv_buf_len);
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_SCAN);
/* Size is equal to the sizeof(fixed portions) + the TLV len + header */
cmd->size = cpu_to_le16((u16) (sizeof(scan_cmd->bss_mode)
+ sizeof(scan_cmd->bssid)
+ scan_cfg->tlv_buf_len + S_DS_GEN));
return 0;
}
/*
* This function checks compatibility of requested network with current
* driver settings.
*/
int mwifiex_check_network_compatibility(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
int ret = -1;
if (!bss_desc)
return -1;
if ((mwifiex_get_cfp(priv, (u8) bss_desc->bss_band,
(u16) bss_desc->channel, 0))) {
switch (priv->bss_mode) {
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_ADHOC:
ret = mwifiex_is_network_compatible(priv, bss_desc,
priv->bss_mode);
if (ret)
mwifiex_dbg(priv->adapter, ERROR,
"Incompatible network settings\n");
break;
default:
ret = 0;
}
}
return ret;
}
/* This function checks if SSID string contains all zeroes or length is zero */
static bool mwifiex_is_hidden_ssid(struct cfg80211_ssid *ssid)
{
int idx;
for (idx = 0; idx < ssid->ssid_len; idx++) {
if (ssid->ssid[idx])
return false;
}
return true;
}
/* This function checks if any hidden SSID found in passive scan channels
* and save those channels for specific SSID active scan
*/
static int mwifiex_save_hidden_ssid_channels(struct mwifiex_private *priv,
struct cfg80211_bss *bss)
{
struct mwifiex_bssdescriptor *bss_desc;
int ret;
int chid;
/* Allocate and fill new bss descriptor */
bss_desc = kzalloc(sizeof(*bss_desc), GFP_KERNEL);
if (!bss_desc)
return -ENOMEM;
ret = mwifiex_fill_new_bss_desc(priv, bss, bss_desc);
if (ret)
goto done;
if (mwifiex_is_hidden_ssid(&bss_desc->ssid)) {
mwifiex_dbg(priv->adapter, INFO, "found hidden SSID\n");
for (chid = 0 ; chid < MWIFIEX_USER_SCAN_CHAN_MAX; chid++) {
if (priv->hidden_chan[chid].chan_number ==
bss->channel->hw_value)
break;
if (!priv->hidden_chan[chid].chan_number) {
priv->hidden_chan[chid].chan_number =
bss->channel->hw_value;
priv->hidden_chan[chid].radio_type =
bss->channel->band;
priv->hidden_chan[chid].scan_type =
MWIFIEX_SCAN_TYPE_ACTIVE;
break;
}
}
}
done:
/* beacon_ie buffer was allocated in function
* mwifiex_fill_new_bss_desc(). Free it now.
*/
kfree(bss_desc->beacon_buf);
kfree(bss_desc);
return 0;
}
static int mwifiex_update_curr_bss_params(struct mwifiex_private *priv,
struct cfg80211_bss *bss)
{
struct mwifiex_bssdescriptor *bss_desc;
int ret;
/* Allocate and fill new bss descriptor */
bss_desc = kzalloc(sizeof(struct mwifiex_bssdescriptor), GFP_KERNEL);
if (!bss_desc)
return -ENOMEM;
ret = mwifiex_fill_new_bss_desc(priv, bss, bss_desc);
if (ret)
goto done;
ret = mwifiex_check_network_compatibility(priv, bss_desc);
if (ret)
goto done;
spin_lock_bh(&priv->curr_bcn_buf_lock);
/* Make a copy of current BSSID descriptor */
memcpy(&priv->curr_bss_params.bss_descriptor, bss_desc,
sizeof(priv->curr_bss_params.bss_descriptor));
/* The contents of beacon_ie will be copied to its own buffer
* in mwifiex_save_curr_bcn()
*/
mwifiex_save_curr_bcn(priv);
spin_unlock_bh(&priv->curr_bcn_buf_lock);
done:
/* beacon_ie buffer was allocated in function
* mwifiex_fill_new_bss_desc(). Free it now.
*/
kfree(bss_desc->beacon_buf);
kfree(bss_desc);
return 0;
}
static int
mwifiex_parse_single_response_buf(struct mwifiex_private *priv, u8 **bss_info,
u32 *bytes_left, u64 fw_tsf, u8 *radio_type,
bool ext_scan, s32 rssi_val)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_chan_freq_power *cfp;
struct cfg80211_bss *bss;
u8 bssid[ETH_ALEN];
s32 rssi;
const u8 *ie_buf;
size_t ie_len;
u16 channel = 0;
u16 beacon_size = 0;
u32 curr_bcn_bytes;
u32 freq;
u16 beacon_period;
u16 cap_info_bitmap;
u8 *current_ptr;
u64 timestamp;
struct mwifiex_fixed_bcn_param *bcn_param;
struct mwifiex_bss_priv *bss_priv;
if (*bytes_left >= sizeof(beacon_size)) {
/* Extract & convert beacon size from command buffer */
beacon_size = get_unaligned_le16((*bss_info));
*bytes_left -= sizeof(beacon_size);
*bss_info += sizeof(beacon_size);
}
if (!beacon_size || beacon_size > *bytes_left) {
*bss_info += *bytes_left;
*bytes_left = 0;
return -EFAULT;
}
/* Initialize the current working beacon pointer for this BSS
* iteration
*/
current_ptr = *bss_info;
/* Advance the return beacon pointer past the current beacon */
*bss_info += beacon_size;
*bytes_left -= beacon_size;
curr_bcn_bytes = beacon_size;
/* First 5 fields are bssid, RSSI(for legacy scan only),
* time stamp, beacon interval, and capability information
*/
if (curr_bcn_bytes < ETH_ALEN + sizeof(u8) +
sizeof(struct mwifiex_fixed_bcn_param)) {
mwifiex_dbg(adapter, ERROR,
"InterpretIE: not enough bytes left\n");
return -EFAULT;
}
memcpy(bssid, current_ptr, ETH_ALEN);
current_ptr += ETH_ALEN;
curr_bcn_bytes -= ETH_ALEN;
if (!ext_scan) {
rssi = (s32) *current_ptr;
rssi = (-rssi) * 100; /* Convert dBm to mBm */
current_ptr += sizeof(u8);
curr_bcn_bytes -= sizeof(u8);
mwifiex_dbg(adapter, INFO,
"info: InterpretIE: RSSI=%d\n", rssi);
} else {
rssi = rssi_val;
}
bcn_param = (struct mwifiex_fixed_bcn_param *)current_ptr;
current_ptr += sizeof(*bcn_param);
curr_bcn_bytes -= sizeof(*bcn_param);
timestamp = le64_to_cpu(bcn_param->timestamp);
beacon_period = le16_to_cpu(bcn_param->beacon_period);
cap_info_bitmap = le16_to_cpu(bcn_param->cap_info_bitmap);
mwifiex_dbg(adapter, INFO,
"info: InterpretIE: capabilities=0x%X\n",
cap_info_bitmap);
/* Rest of the current buffer are IE's */
ie_buf = current_ptr;
ie_len = curr_bcn_bytes;
mwifiex_dbg(adapter, INFO,
"info: InterpretIE: IELength for this AP = %d\n",
curr_bcn_bytes);
while (curr_bcn_bytes >= sizeof(struct ieee_types_header)) {
u8 element_id, element_len;
element_id = *current_ptr;
element_len = *(current_ptr + 1);
if (curr_bcn_bytes < element_len +
sizeof(struct ieee_types_header)) {
mwifiex_dbg(adapter, ERROR,
"%s: bytes left < IE length\n", __func__);
return -EFAULT;
}
if (element_id == WLAN_EID_DS_PARAMS) {
channel = *(current_ptr +
sizeof(struct ieee_types_header));
break;
}
current_ptr += element_len + sizeof(struct ieee_types_header);
curr_bcn_bytes -= element_len +
sizeof(struct ieee_types_header);
}
if (channel) {
struct ieee80211_channel *chan;
u8 band;
/* Skip entry if on csa closed channel */
if (channel == priv->csa_chan) {
mwifiex_dbg(adapter, WARN,
"Dropping entry on csa closed channel\n");
return 0;
}
band = BAND_G;
if (radio_type)
band = mwifiex_radio_type_to_band(*radio_type &
(BIT(0) | BIT(1)));
cfp = mwifiex_get_cfp(priv, band, channel, 0);
freq = cfp ? cfp->freq : 0;
chan = ieee80211_get_channel(priv->wdev.wiphy, freq);
if (chan && !(chan->flags & IEEE80211_CHAN_DISABLED)) {
bss = cfg80211_inform_bss(priv->wdev.wiphy,
chan, CFG80211_BSS_FTYPE_UNKNOWN,
bssid, timestamp,
cap_info_bitmap, beacon_period,
ie_buf, ie_len, rssi, GFP_KERNEL);
if (bss) {
bss_priv = (struct mwifiex_bss_priv *)bss->priv;
bss_priv->band = band;
bss_priv->fw_tsf = fw_tsf;
if (priv->media_connected &&
!memcmp(bssid, priv->curr_bss_params.
bss_descriptor.mac_address,
ETH_ALEN))
mwifiex_update_curr_bss_params(priv,
bss);
if ((chan->flags & IEEE80211_CHAN_RADAR) ||
(chan->flags & IEEE80211_CHAN_NO_IR)) {
mwifiex_dbg(adapter, INFO,
"radar or passive channel %d\n",
channel);
mwifiex_save_hidden_ssid_channels(priv,
bss);
}
cfg80211_put_bss(priv->wdev.wiphy, bss);
}
}
} else {
mwifiex_dbg(adapter, WARN, "missing BSS channel IE\n");
}
return 0;
}
static void mwifiex_complete_scan(struct mwifiex_private *priv)
{
struct mwifiex_adapter *adapter = priv->adapter;
adapter->survey_idx = 0;
if (adapter->curr_cmd->wait_q_enabled) {
adapter->cmd_wait_q.status = 0;
if (!priv->scan_request) {
mwifiex_dbg(adapter, INFO,
"complete internal scan\n");
mwifiex_complete_cmd(adapter, adapter->curr_cmd);
}
}
}
/* This function checks if any hidden SSID found in passive scan channels
* and do specific SSID active scan for those channels
*/
static int
mwifiex_active_scan_req_for_passive_chan(struct mwifiex_private *priv)
{
int ret;
struct mwifiex_adapter *adapter = priv->adapter;
u8 id = 0;
struct mwifiex_user_scan_cfg *user_scan_cfg;
if (adapter->active_scan_triggered || !priv->scan_request ||
priv->scan_aborting) {
adapter->active_scan_triggered = false;
return 0;
}
if (!priv->hidden_chan[0].chan_number) {
mwifiex_dbg(adapter, INFO, "No BSS with hidden SSID found on DFS channels\n");
return 0;
}
user_scan_cfg = kzalloc(sizeof(*user_scan_cfg), GFP_KERNEL);
if (!user_scan_cfg)
return -ENOMEM;
for (id = 0; id < MWIFIEX_USER_SCAN_CHAN_MAX; id++) {
if (!priv->hidden_chan[id].chan_number)
break;
memcpy(&user_scan_cfg->chan_list[id],
&priv->hidden_chan[id],
sizeof(struct mwifiex_user_scan_chan));
}
adapter->active_scan_triggered = true;
if (priv->scan_request->flags & NL80211_SCAN_FLAG_RANDOM_ADDR)
ether_addr_copy(user_scan_cfg->random_mac,
priv->scan_request->mac_addr);
user_scan_cfg->num_ssids = priv->scan_request->n_ssids;
user_scan_cfg->ssid_list = priv->scan_request->ssids;
ret = mwifiex_scan_networks(priv, user_scan_cfg);
kfree(user_scan_cfg);
memset(&priv->hidden_chan, 0, sizeof(priv->hidden_chan));
if (ret) {
dev_err(priv->adapter->dev, "scan failed: %d\n", ret);
return ret;
}
return 0;
}
static void mwifiex_check_next_scan_command(struct mwifiex_private *priv)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct cmd_ctrl_node *cmd_node;
spin_lock_bh(&adapter->scan_pending_q_lock);
if (list_empty(&adapter->scan_pending_q)) {
spin_unlock_bh(&adapter->scan_pending_q_lock);
spin_lock_bh(&adapter->mwifiex_cmd_lock);
adapter->scan_processing = false;
spin_unlock_bh(&adapter->mwifiex_cmd_lock);
mwifiex_active_scan_req_for_passive_chan(priv);
if (!adapter->ext_scan)
mwifiex_complete_scan(priv);
if (priv->scan_request) {
struct cfg80211_scan_info info = {
.aborted = false,
};
mwifiex_dbg(adapter, INFO,
"info: notifying scan done\n");
cfg80211_scan_done(priv->scan_request, &info);
priv->scan_request = NULL;
priv->scan_aborting = false;
} else {
priv->scan_aborting = false;
mwifiex_dbg(adapter, INFO,
"info: scan already aborted\n");
}
} else if ((priv->scan_aborting && !priv->scan_request) ||
priv->scan_block) {
spin_unlock_bh(&adapter->scan_pending_q_lock);
mwifiex_cancel_pending_scan_cmd(adapter);
spin_lock_bh(&adapter->mwifiex_cmd_lock);
adapter->scan_processing = false;
spin_unlock_bh(&adapter->mwifiex_cmd_lock);
if (!adapter->active_scan_triggered) {
if (priv->scan_request) {
struct cfg80211_scan_info info = {
.aborted = true,
};
mwifiex_dbg(adapter, INFO,
"info: aborting scan\n");
cfg80211_scan_done(priv->scan_request, &info);
priv->scan_request = NULL;
priv->scan_aborting = false;
} else {
priv->scan_aborting = false;
mwifiex_dbg(adapter, INFO,
"info: scan already aborted\n");
}
}
} else {
/* Get scan command from scan_pending_q and put to
* cmd_pending_q
*/
cmd_node = list_first_entry(&adapter->scan_pending_q,
struct cmd_ctrl_node, list);
list_del(&cmd_node->list);
spin_unlock_bh(&adapter->scan_pending_q_lock);
mwifiex_insert_cmd_to_pending_q(adapter, cmd_node);
}
return;
}
void mwifiex_cancel_scan(struct mwifiex_adapter *adapter)
{
struct mwifiex_private *priv;
int i;
mwifiex_cancel_pending_scan_cmd(adapter);
if (adapter->scan_processing) {
spin_lock_bh(&adapter->mwifiex_cmd_lock);
adapter->scan_processing = false;
spin_unlock_bh(&adapter->mwifiex_cmd_lock);
for (i = 0; i < adapter->priv_num; i++) {
priv = adapter->priv[i];
if (!priv)
continue;
if (priv->scan_request) {
struct cfg80211_scan_info info = {
.aborted = true,
};
mwifiex_dbg(adapter, INFO,
"info: aborting scan\n");
cfg80211_scan_done(priv->scan_request, &info);
priv->scan_request = NULL;
priv->scan_aborting = false;
}
}
}
}
/*
* This function handles the command response of scan.
*
* The response buffer for the scan command has the following
* memory layout:
*
* .-------------------------------------------------------------.
* | Header (4 * sizeof(t_u16)): Standard command response hdr |
* .-------------------------------------------------------------.
* | BufSize (t_u16) : sizeof the BSS Description data |
* .-------------------------------------------------------------.
* | NumOfSet (t_u8) : Number of BSS Descs returned |
* .-------------------------------------------------------------.
* | BSSDescription data (variable, size given in BufSize) |
* .-------------------------------------------------------------.
* | TLV data (variable, size calculated using Header->Size, |
* | BufSize and sizeof the fixed fields above) |
* .-------------------------------------------------------------.
*/
int mwifiex_ret_802_11_scan(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
int ret = 0;
struct mwifiex_adapter *adapter = priv->adapter;
struct host_cmd_ds_802_11_scan_rsp *scan_rsp;
struct mwifiex_ie_types_data *tlv_data;
struct mwifiex_ie_types_tsf_timestamp *tsf_tlv;
u8 *bss_info;
u32 scan_resp_size;
u32 bytes_left;
u32 idx;
u32 tlv_buf_size;
struct mwifiex_ie_types_chan_band_list_param_set *chan_band_tlv;
struct chan_band_param_set *chan_band;
u8 is_bgscan_resp;
__le64 fw_tsf = 0;
u8 *radio_type;
struct cfg80211_wowlan_nd_match *pmatch;
struct cfg80211_sched_scan_request *nd_config = NULL;
is_bgscan_resp = (le16_to_cpu(resp->command)
== HostCmd_CMD_802_11_BG_SCAN_QUERY);
if (is_bgscan_resp)
scan_rsp = &resp->params.bg_scan_query_resp.scan_resp;
else
scan_rsp = &resp->params.scan_resp;
if (scan_rsp->number_of_sets > MWIFIEX_MAX_AP) {
mwifiex_dbg(adapter, ERROR,
"SCAN_RESP: too many AP returned (%d)\n",
scan_rsp->number_of_sets);
ret = -1;
goto check_next_scan;
}
/* Check csa channel expiry before parsing scan response */
mwifiex_11h_get_csa_closed_channel(priv);
bytes_left = le16_to_cpu(scan_rsp->bss_descript_size);
mwifiex_dbg(adapter, INFO,
"info: SCAN_RESP: bss_descript_size %d\n",
bytes_left);
scan_resp_size = le16_to_cpu(resp->size);
mwifiex_dbg(adapter, INFO,
"info: SCAN_RESP: returned %d APs before parsing\n",
scan_rsp->number_of_sets);
bss_info = scan_rsp->bss_desc_and_tlv_buffer;
/*
* The size of the TLV buffer is equal to the entire command response
* size (scan_resp_size) minus the fixed fields (sizeof()'s), the
* BSS Descriptions (bss_descript_size as bytesLef) and the command
* response header (S_DS_GEN)
*/
tlv_buf_size = scan_resp_size - (bytes_left
+ sizeof(scan_rsp->bss_descript_size)
+ sizeof(scan_rsp->number_of_sets)
+ S_DS_GEN);
tlv_data = (struct mwifiex_ie_types_data *) (scan_rsp->
bss_desc_and_tlv_buffer +
bytes_left);
/* Search the TLV buffer space in the scan response for any valid
TLVs */
mwifiex_ret_802_11_scan_get_tlv_ptrs(adapter, tlv_data, tlv_buf_size,
TLV_TYPE_TSFTIMESTAMP,
(struct mwifiex_ie_types_data **)
&tsf_tlv);
/* Search the TLV buffer space in the scan response for any valid
TLVs */
mwifiex_ret_802_11_scan_get_tlv_ptrs(adapter, tlv_data, tlv_buf_size,
TLV_TYPE_CHANNELBANDLIST,
(struct mwifiex_ie_types_data **)
&chan_band_tlv);
#ifdef CONFIG_PM
if (priv->wdev.wiphy->wowlan_config)
nd_config = priv->wdev.wiphy->wowlan_config->nd_config;
#endif
if (nd_config) {
adapter->nd_info =
kzalloc(sizeof(struct cfg80211_wowlan_nd_match) +
sizeof(struct cfg80211_wowlan_nd_match *) *
scan_rsp->number_of_sets, GFP_ATOMIC);
if (adapter->nd_info)
adapter->nd_info->n_matches = scan_rsp->number_of_sets;
}
for (idx = 0; idx < scan_rsp->number_of_sets && bytes_left; idx++) {
/*
* If the TSF TLV was appended to the scan results, save this
* entry's TSF value in the fw_tsf field. It is the firmware's
* TSF value at the time the beacon or probe response was
* received.
*/
if (tsf_tlv)
memcpy(&fw_tsf, &tsf_tlv->tsf_data[idx * TSF_DATA_SIZE],
sizeof(fw_tsf));
if (chan_band_tlv) {
chan_band = &chan_band_tlv->chan_band_param[idx];
radio_type = &chan_band->radio_type;
} else {
radio_type = NULL;
}
if (chan_band_tlv && adapter->nd_info) {
adapter->nd_info->matches[idx] =
kzalloc(sizeof(*pmatch) + sizeof(u32),
GFP_ATOMIC);
pmatch = adapter->nd_info->matches[idx];
if (pmatch) {
pmatch->n_channels = 1;
pmatch->channels[0] = chan_band->chan_number;
}
}
ret = mwifiex_parse_single_response_buf(priv, &bss_info,
&bytes_left,
le64_to_cpu(fw_tsf),
radio_type, false, 0);
if (ret)
goto check_next_scan;
}
check_next_scan:
mwifiex_check_next_scan_command(priv);
return ret;
}
/*
* This function prepares an extended scan command to be sent to the firmware
*
* This uses the scan command configuration sent to the command processing
* module in command preparation stage to configure a extended scan command
* structure to send to firmware.
*/
int mwifiex_cmd_802_11_scan_ext(struct mwifiex_private *priv,
struct host_cmd_ds_command *cmd,
void *data_buf)
{
struct host_cmd_ds_802_11_scan_ext *ext_scan = &cmd->params.ext_scan;
struct mwifiex_scan_cmd_config *scan_cfg = data_buf;
memcpy(ext_scan->tlv_buffer, scan_cfg->tlv_buf, scan_cfg->tlv_buf_len);
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_SCAN_EXT);
/* Size is equal to the sizeof(fixed portions) + the TLV len + header */
cmd->size = cpu_to_le16((u16)(sizeof(ext_scan->reserved)
+ scan_cfg->tlv_buf_len + S_DS_GEN));
return 0;
}
/* This function prepares an background scan config command to be sent
* to the firmware
*/
int mwifiex_cmd_802_11_bg_scan_config(struct mwifiex_private *priv,
struct host_cmd_ds_command *cmd,
void *data_buf)
{
struct host_cmd_ds_802_11_bg_scan_config *bgscan_config =
&cmd->params.bg_scan_config;
struct mwifiex_bg_scan_cfg *bgscan_cfg_in = data_buf;
u8 *tlv_pos = bgscan_config->tlv;
u8 num_probes;
u32 ssid_len, chan_idx, scan_type, scan_dur, chan_num;
int i;
struct mwifiex_ie_types_num_probes *num_probes_tlv;
struct mwifiex_ie_types_repeat_count *repeat_count_tlv;
struct mwifiex_ie_types_min_rssi_threshold *rssi_threshold_tlv;
struct mwifiex_ie_types_bgscan_start_later *start_later_tlv;
struct mwifiex_ie_types_wildcard_ssid_params *wildcard_ssid_tlv;
struct mwifiex_ie_types_chan_list_param_set *chan_list_tlv;
struct mwifiex_chan_scan_param_set *temp_chan;
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_BG_SCAN_CONFIG);
cmd->size = cpu_to_le16(sizeof(*bgscan_config) + S_DS_GEN);
bgscan_config->action = cpu_to_le16(bgscan_cfg_in->action);
bgscan_config->enable = bgscan_cfg_in->enable;
bgscan_config->bss_type = bgscan_cfg_in->bss_type;
bgscan_config->scan_interval =
cpu_to_le32(bgscan_cfg_in->scan_interval);
bgscan_config->report_condition =
cpu_to_le32(bgscan_cfg_in->report_condition);
/* stop sched scan */
if (!bgscan_config->enable)
return 0;
bgscan_config->chan_per_scan = bgscan_cfg_in->chan_per_scan;
num_probes = (bgscan_cfg_in->num_probes ? bgscan_cfg_in->
num_probes : priv->adapter->scan_probes);
if (num_probes) {
num_probes_tlv = (struct mwifiex_ie_types_num_probes *)tlv_pos;
num_probes_tlv->header.type = cpu_to_le16(TLV_TYPE_NUMPROBES);
num_probes_tlv->header.len =
cpu_to_le16(sizeof(num_probes_tlv->num_probes));
num_probes_tlv->num_probes = cpu_to_le16((u16)num_probes);
tlv_pos += sizeof(num_probes_tlv->header) +
le16_to_cpu(num_probes_tlv->header.len);
}
if (bgscan_cfg_in->repeat_count) {
repeat_count_tlv =
(struct mwifiex_ie_types_repeat_count *)tlv_pos;
repeat_count_tlv->header.type =
cpu_to_le16(TLV_TYPE_REPEAT_COUNT);
repeat_count_tlv->header.len =
cpu_to_le16(sizeof(repeat_count_tlv->repeat_count));
repeat_count_tlv->repeat_count =
cpu_to_le16(bgscan_cfg_in->repeat_count);
tlv_pos += sizeof(repeat_count_tlv->header) +
le16_to_cpu(repeat_count_tlv->header.len);
}
if (bgscan_cfg_in->rssi_threshold) {
rssi_threshold_tlv =
(struct mwifiex_ie_types_min_rssi_threshold *)tlv_pos;
rssi_threshold_tlv->header.type =
cpu_to_le16(TLV_TYPE_RSSI_LOW);
rssi_threshold_tlv->header.len =
cpu_to_le16(sizeof(rssi_threshold_tlv->rssi_threshold));
rssi_threshold_tlv->rssi_threshold =
cpu_to_le16(bgscan_cfg_in->rssi_threshold);
tlv_pos += sizeof(rssi_threshold_tlv->header) +
le16_to_cpu(rssi_threshold_tlv->header.len);
}
for (i = 0; i < bgscan_cfg_in->num_ssids; i++) {
ssid_len = bgscan_cfg_in->ssid_list[i].ssid.ssid_len;
wildcard_ssid_tlv =
(struct mwifiex_ie_types_wildcard_ssid_params *)tlv_pos;
wildcard_ssid_tlv->header.type =
cpu_to_le16(TLV_TYPE_WILDCARDSSID);
wildcard_ssid_tlv->header.len = cpu_to_le16(
(u16)(ssid_len + sizeof(wildcard_ssid_tlv->
max_ssid_length)));
/* max_ssid_length = 0 tells firmware to perform
* specific scan for the SSID filled, whereas
* max_ssid_length = IEEE80211_MAX_SSID_LEN is for
* wildcard scan.
*/
if (ssid_len)
wildcard_ssid_tlv->max_ssid_length = 0;
else
wildcard_ssid_tlv->max_ssid_length =
IEEE80211_MAX_SSID_LEN;
memcpy(wildcard_ssid_tlv->ssid,
bgscan_cfg_in->ssid_list[i].ssid.ssid, ssid_len);
tlv_pos += (sizeof(wildcard_ssid_tlv->header)
+ le16_to_cpu(wildcard_ssid_tlv->header.len));
}
chan_list_tlv = (struct mwifiex_ie_types_chan_list_param_set *)tlv_pos;
if (bgscan_cfg_in->chan_list[0].chan_number) {
dev_dbg(priv->adapter->dev, "info: bgscan: Using supplied channel list\n");
chan_list_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);
for (chan_idx = 0;
chan_idx < MWIFIEX_BG_SCAN_CHAN_MAX &&
bgscan_cfg_in->chan_list[chan_idx].chan_number;
chan_idx++) {
temp_chan = chan_list_tlv->chan_scan_param + chan_idx;
/* Increment the TLV header length by size appended */
le16_unaligned_add_cpu(&chan_list_tlv->header.len,
sizeof(
chan_list_tlv->chan_scan_param));
temp_chan->chan_number =
bgscan_cfg_in->chan_list[chan_idx].chan_number;
temp_chan->radio_type =
bgscan_cfg_in->chan_list[chan_idx].radio_type;
scan_type =
bgscan_cfg_in->chan_list[chan_idx].scan_type;
if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE)
temp_chan->chan_scan_mode_bitmap
|= MWIFIEX_PASSIVE_SCAN;
else
temp_chan->chan_scan_mode_bitmap
&= ~MWIFIEX_PASSIVE_SCAN;
if (bgscan_cfg_in->chan_list[chan_idx].scan_time) {
scan_dur = (u16)bgscan_cfg_in->
chan_list[chan_idx].scan_time;
} else {
scan_dur = (scan_type ==
MWIFIEX_SCAN_TYPE_PASSIVE) ?
priv->adapter->passive_scan_time :
priv->adapter->specific_scan_time;
}
temp_chan->min_scan_time = cpu_to_le16(scan_dur);
temp_chan->max_scan_time = cpu_to_le16(scan_dur);
}
} else {
dev_dbg(priv->adapter->dev,
"info: bgscan: Creating full region channel list\n");
chan_num =
mwifiex_bgscan_create_channel_list(priv, bgscan_cfg_in,
chan_list_tlv->
chan_scan_param);
le16_unaligned_add_cpu(&chan_list_tlv->header.len,
chan_num *
sizeof(chan_list_tlv->chan_scan_param[0]));
}
tlv_pos += (sizeof(chan_list_tlv->header)
+ le16_to_cpu(chan_list_tlv->header.len));
if (bgscan_cfg_in->start_later) {
start_later_tlv =
(struct mwifiex_ie_types_bgscan_start_later *)tlv_pos;
start_later_tlv->header.type =
cpu_to_le16(TLV_TYPE_BGSCAN_START_LATER);
start_later_tlv->header.len =
cpu_to_le16(sizeof(start_later_tlv->start_later));
start_later_tlv->start_later =
cpu_to_le16(bgscan_cfg_in->start_later);
tlv_pos += sizeof(start_later_tlv->header) +
le16_to_cpu(start_later_tlv->header.len);
}
/* Append vendor specific IE TLV */
mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_BGSCAN, &tlv_pos);
le16_unaligned_add_cpu(&cmd->size, tlv_pos - bgscan_config->tlv);
return 0;
}
int mwifiex_stop_bg_scan(struct mwifiex_private *priv)
{
struct mwifiex_bg_scan_cfg *bgscan_cfg;
if (!priv->sched_scanning) {
dev_dbg(priv->adapter->dev, "bgscan already stopped!\n");
return 0;
}
bgscan_cfg = kzalloc(sizeof(*bgscan_cfg), GFP_KERNEL);
if (!bgscan_cfg)
return -ENOMEM;
bgscan_cfg->bss_type = MWIFIEX_BSS_MODE_INFRA;
bgscan_cfg->action = MWIFIEX_BGSCAN_ACT_SET;
bgscan_cfg->enable = false;
if (mwifiex_send_cmd(priv, HostCmd_CMD_802_11_BG_SCAN_CONFIG,
HostCmd_ACT_GEN_SET, 0, bgscan_cfg, true)) {
kfree(bgscan_cfg);
return -EFAULT;
}
kfree(bgscan_cfg);
priv->sched_scanning = false;
return 0;
}
static void
mwifiex_update_chan_statistics(struct mwifiex_private *priv,
struct mwifiex_ietypes_chanstats *tlv_stat)
{
struct mwifiex_adapter *adapter = priv->adapter;
u8 i, num_chan;
struct mwifiex_fw_chan_stats *fw_chan_stats;
struct mwifiex_chan_stats chan_stats;
fw_chan_stats = (void *)((u8 *)tlv_stat +
sizeof(struct mwifiex_ie_types_header));
num_chan = le16_to_cpu(tlv_stat->header.len) /
sizeof(struct mwifiex_chan_stats);
for (i = 0 ; i < num_chan; i++) {
if (adapter->survey_idx >= adapter->num_in_chan_stats) {
mwifiex_dbg(adapter, WARN,
"FW reported too many channel results (max %d)\n",
adapter->num_in_chan_stats);
return;
}
chan_stats.chan_num = fw_chan_stats->chan_num;
chan_stats.bandcfg = fw_chan_stats->bandcfg;
chan_stats.flags = fw_chan_stats->flags;
chan_stats.noise = fw_chan_stats->noise;
chan_stats.total_bss = le16_to_cpu(fw_chan_stats->total_bss);
chan_stats.cca_scan_dur =
le16_to_cpu(fw_chan_stats->cca_scan_dur);
chan_stats.cca_busy_dur =
le16_to_cpu(fw_chan_stats->cca_busy_dur);
mwifiex_dbg(adapter, INFO,
"chan=%d, noise=%d, total_network=%d scan_duration=%d, busy_duration=%d\n",
chan_stats.chan_num,
chan_stats.noise,
chan_stats.total_bss,
chan_stats.cca_scan_dur,
chan_stats.cca_busy_dur);
memcpy(&adapter->chan_stats[adapter->survey_idx++], &chan_stats,
sizeof(struct mwifiex_chan_stats));
fw_chan_stats++;
}
}
/* This function handles the command response of extended scan */
int mwifiex_ret_802_11_scan_ext(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct host_cmd_ds_802_11_scan_ext *ext_scan_resp;
struct mwifiex_ie_types_header *tlv;
struct mwifiex_ietypes_chanstats *tlv_stat;
u16 buf_left, type, len;
struct host_cmd_ds_command *cmd_ptr;
struct cmd_ctrl_node *cmd_node;
bool complete_scan = false;
mwifiex_dbg(adapter, INFO, "info: EXT scan returns successfully\n");
ext_scan_resp = &resp->params.ext_scan;
tlv = (void *)ext_scan_resp->tlv_buffer;
buf_left = le16_to_cpu(resp->size) - (sizeof(*ext_scan_resp) + S_DS_GEN
- 1);
while (buf_left >= sizeof(struct mwifiex_ie_types_header)) {
type = le16_to_cpu(tlv->type);
len = le16_to_cpu(tlv->len);
if (buf_left < (sizeof(struct mwifiex_ie_types_header) + len)) {
mwifiex_dbg(adapter, ERROR,
"error processing scan response TLVs");
break;
}
switch (type) {
case TLV_TYPE_CHANNEL_STATS:
tlv_stat = (void *)tlv;
mwifiex_update_chan_statistics(priv, tlv_stat);
break;
default:
break;
}
buf_left -= len + sizeof(struct mwifiex_ie_types_header);
tlv = (void *)((u8 *)tlv + len +
sizeof(struct mwifiex_ie_types_header));
}
spin_lock_bh(&adapter->cmd_pending_q_lock);
spin_lock_bh(&adapter->scan_pending_q_lock);
if (list_empty(&adapter->scan_pending_q)) {
complete_scan = true;
list_for_each_entry(cmd_node, &adapter->cmd_pending_q, list) {
cmd_ptr = (void *)cmd_node->cmd_skb->data;
if (le16_to_cpu(cmd_ptr->command) ==
HostCmd_CMD_802_11_SCAN_EXT) {
mwifiex_dbg(adapter, INFO,
"Scan pending in command pending list");
complete_scan = false;
break;
}
}
}
spin_unlock_bh(&adapter->scan_pending_q_lock);
spin_unlock_bh(&adapter->cmd_pending_q_lock);
if (complete_scan)
mwifiex_complete_scan(priv);
return 0;
}
/* This function This function handles the event extended scan report. It
* parses extended scan results and informs to cfg80211 stack.
*/
int mwifiex_handle_event_ext_scan_report(struct mwifiex_private *priv,
void *buf)
{
int ret = 0;
struct mwifiex_adapter *adapter = priv->adapter;
u8 *bss_info;
u32 bytes_left, bytes_left_for_tlv, idx;
u16 type, len;
struct mwifiex_ie_types_data *tlv;
struct mwifiex_ie_types_bss_scan_rsp *scan_rsp_tlv;
struct mwifiex_ie_types_bss_scan_info *scan_info_tlv;
u8 *radio_type;
u64 fw_tsf = 0;
s32 rssi = 0;
struct mwifiex_event_scan_result *event_scan = buf;
u8 num_of_set = event_scan->num_of_set;
u8 *scan_resp = buf + sizeof(struct mwifiex_event_scan_result);
u16 scan_resp_size = le16_to_cpu(event_scan->buf_size);
if (num_of_set > MWIFIEX_MAX_AP) {
mwifiex_dbg(adapter, ERROR,
"EXT_SCAN: Invalid number of AP returned (%d)!!\n",
num_of_set);
ret = -1;
goto check_next_scan;
}
bytes_left = scan_resp_size;
mwifiex_dbg(adapter, INFO,
"EXT_SCAN: size %d, returned %d APs...",
scan_resp_size, num_of_set);
mwifiex_dbg_dump(adapter, CMD_D, "EXT_SCAN buffer:", buf,
scan_resp_size +
sizeof(struct mwifiex_event_scan_result));
tlv = (struct mwifiex_ie_types_data *)scan_resp;
for (idx = 0; idx < num_of_set && bytes_left; idx++) {
type = le16_to_cpu(tlv->header.type);
len = le16_to_cpu(tlv->header.len);
if (bytes_left < sizeof(struct mwifiex_ie_types_header) + len) {
mwifiex_dbg(adapter, ERROR,
"EXT_SCAN: Error bytes left < TLV length\n");
break;
}
scan_rsp_tlv = NULL;
scan_info_tlv = NULL;
bytes_left_for_tlv = bytes_left;
/* BSS response TLV with beacon or probe response buffer
* at the initial position of each descriptor
*/
if (type != TLV_TYPE_BSS_SCAN_RSP)
break;
bss_info = (u8 *)tlv;
scan_rsp_tlv = (struct mwifiex_ie_types_bss_scan_rsp *)tlv;
tlv = (struct mwifiex_ie_types_data *)(tlv->data + len);
bytes_left_for_tlv -=
(len + sizeof(struct mwifiex_ie_types_header));
while (bytes_left_for_tlv >=
sizeof(struct mwifiex_ie_types_header) &&
le16_to_cpu(tlv->header.type) != TLV_TYPE_BSS_SCAN_RSP) {
type = le16_to_cpu(tlv->header.type);
len = le16_to_cpu(tlv->header.len);
if (bytes_left_for_tlv <
sizeof(struct mwifiex_ie_types_header) + len) {
mwifiex_dbg(adapter, ERROR,
"EXT_SCAN: Error in processing TLV,\t"
"bytes left < TLV length\n");
scan_rsp_tlv = NULL;
bytes_left_for_tlv = 0;
continue;
}
switch (type) {
case TLV_TYPE_BSS_SCAN_INFO:
scan_info_tlv =
(struct mwifiex_ie_types_bss_scan_info *)tlv;
if (len !=
sizeof(struct mwifiex_ie_types_bss_scan_info) -
sizeof(struct mwifiex_ie_types_header)) {
bytes_left_for_tlv = 0;
continue;
}
break;
default:
break;
}
tlv = (struct mwifiex_ie_types_data *)(tlv->data + len);
bytes_left -=
(len + sizeof(struct mwifiex_ie_types_header));
bytes_left_for_tlv -=
(len + sizeof(struct mwifiex_ie_types_header));
}
if (!scan_rsp_tlv)
break;
/* Advance pointer to the beacon buffer length and
* update the bytes count so that the function
* wlan_interpret_bss_desc_with_ie() can handle the
* scan buffer withut any change
*/
bss_info += sizeof(u16);
bytes_left -= sizeof(u16);
if (scan_info_tlv) {
rssi = (s32)(s16)(le16_to_cpu(scan_info_tlv->rssi));
rssi *= 100; /* Convert dBm to mBm */
mwifiex_dbg(adapter, INFO,
"info: InterpretIE: RSSI=%d\n", rssi);
fw_tsf = le64_to_cpu(scan_info_tlv->tsf);
radio_type = &scan_info_tlv->radio_type;
} else {
radio_type = NULL;
}
ret = mwifiex_parse_single_response_buf(priv, &bss_info,
&bytes_left, fw_tsf,
radio_type, true, rssi);
if (ret)
goto check_next_scan;
}
check_next_scan:
if (!event_scan->more_event)
mwifiex_check_next_scan_command(priv);
return ret;
}
/*
* This function prepares command for background scan query.
*
* Preparation includes -
* - Setting command ID and proper size
* - Setting background scan flush parameter
* - Ensuring correct endian-ness
*/
int mwifiex_cmd_802_11_bg_scan_query(struct host_cmd_ds_command *cmd)
{
struct host_cmd_ds_802_11_bg_scan_query *bg_query =
&cmd->params.bg_scan_query;
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_BG_SCAN_QUERY);
cmd->size = cpu_to_le16(sizeof(struct host_cmd_ds_802_11_bg_scan_query)
+ S_DS_GEN);
bg_query->flush = 1;
return 0;
}
/*
* This function inserts scan command node to the scan pending queue.
*/
void
mwifiex_queue_scan_cmd(struct mwifiex_private *priv,
struct cmd_ctrl_node *cmd_node)
{
struct mwifiex_adapter *adapter = priv->adapter;
cmd_node->wait_q_enabled = true;
cmd_node->condition = &adapter->scan_wait_q_woken;
spin_lock_bh(&adapter->scan_pending_q_lock);
list_add_tail(&cmd_node->list, &adapter->scan_pending_q);
spin_unlock_bh(&adapter->scan_pending_q_lock);
}
/*
* This function sends a scan command for all available channels to the
* firmware, filtered on a specific SSID.
*/
static int mwifiex_scan_specific_ssid(struct mwifiex_private *priv,
struct cfg80211_ssid *req_ssid)
{
struct mwifiex_adapter *adapter = priv->adapter;
int ret;
struct mwifiex_user_scan_cfg *scan_cfg;
if (adapter->scan_processing) {
mwifiex_dbg(adapter, WARN,
"cmd: Scan already in process...\n");
return -EBUSY;
}
if (priv->scan_block) {
mwifiex_dbg(adapter, WARN,
"cmd: Scan is blocked during association...\n");
return -EBUSY;
}
scan_cfg = kzalloc(sizeof(struct mwifiex_user_scan_cfg), GFP_KERNEL);
if (!scan_cfg)
return -ENOMEM;
scan_cfg->ssid_list = req_ssid;
scan_cfg->num_ssids = 1;
ret = mwifiex_scan_networks(priv, scan_cfg);
kfree(scan_cfg);
return ret;
}
/*
* Sends IOCTL request to start a scan.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*
* Scan command can be issued for both normal scan and specific SSID
* scan, depending upon whether an SSID is provided or not.
*/
int mwifiex_request_scan(struct mwifiex_private *priv,
struct cfg80211_ssid *req_ssid)
{
int ret;
if (mutex_lock_interruptible(&priv->async_mutex)) {
mwifiex_dbg(priv->adapter, ERROR,
"%s: acquire semaphore fail\n",
__func__);
return -1;
}
priv->adapter->scan_wait_q_woken = false;
if (req_ssid && req_ssid->ssid_len != 0)
/* Specific SSID scan */
ret = mwifiex_scan_specific_ssid(priv, req_ssid);
else
/* Normal scan */
ret = mwifiex_scan_networks(priv, NULL);
mutex_unlock(&priv->async_mutex);
return ret;
}
/*
* This function appends the vendor specific IE TLV to a buffer.
*/
int
mwifiex_cmd_append_vsie_tlv(struct mwifiex_private *priv,
u16 vsie_mask, u8 **buffer)
{
int id, ret_len = 0;
struct mwifiex_ie_types_vendor_param_set *vs_param_set;
if (!buffer)
return 0;
if (!(*buffer))
return 0;
/*
* Traverse through the saved vendor specific IE array and append
* the selected(scan/assoc/adhoc) IE as TLV to the command
*/
for (id = 0; id < MWIFIEX_MAX_VSIE_NUM; id++) {
if (priv->vs_ie[id].mask & vsie_mask) {
vs_param_set =
(struct mwifiex_ie_types_vendor_param_set *)
*buffer;
vs_param_set->header.type =
cpu_to_le16(TLV_TYPE_PASSTHROUGH);
vs_param_set->header.len =
cpu_to_le16((((u16) priv->vs_ie[id].ie[1])
& 0x00FF) + 2);
memcpy(vs_param_set->ie, priv->vs_ie[id].ie,
le16_to_cpu(vs_param_set->header.len));
*buffer += le16_to_cpu(vs_param_set->header.len) +
sizeof(struct mwifiex_ie_types_header);
ret_len += le16_to_cpu(vs_param_set->header.len) +
sizeof(struct mwifiex_ie_types_header);
}
}
return ret_len;
}
/*
* This function saves a beacon buffer of the current BSS descriptor.
*
* The current beacon buffer is saved so that it can be restored in the
* following cases that makes the beacon buffer not to contain the current
* ssid's beacon buffer.
* - The current ssid was not found somehow in the last scan.
* - The current ssid was the last entry of the scan table and overloaded.
*/
void
mwifiex_save_curr_bcn(struct mwifiex_private *priv)
{
struct mwifiex_bssdescriptor *curr_bss =
&priv->curr_bss_params.bss_descriptor;
if (!curr_bss->beacon_buf_size)
return;
/* allocate beacon buffer at 1st time; or if it's size has changed */
if (!priv->curr_bcn_buf ||
priv->curr_bcn_size != curr_bss->beacon_buf_size) {
priv->curr_bcn_size = curr_bss->beacon_buf_size;
kfree(priv->curr_bcn_buf);
priv->curr_bcn_buf = kmalloc(curr_bss->beacon_buf_size,
GFP_ATOMIC);
if (!priv->curr_bcn_buf)
return;
}
memcpy(priv->curr_bcn_buf, curr_bss->beacon_buf,
curr_bss->beacon_buf_size);
mwifiex_dbg(priv->adapter, INFO,
"info: current beacon saved %d\n",
priv->curr_bcn_size);
curr_bss->beacon_buf = priv->curr_bcn_buf;
/* adjust the pointers in the current BSS descriptor */
if (curr_bss->bcn_wpa_ie)
curr_bss->bcn_wpa_ie =
(struct ieee_types_vendor_specific *)
(curr_bss->beacon_buf +
curr_bss->wpa_offset);
if (curr_bss->bcn_rsn_ie)
curr_bss->bcn_rsn_ie = (struct ieee_types_generic *)
(curr_bss->beacon_buf +
curr_bss->rsn_offset);
if (curr_bss->bcn_ht_cap)
curr_bss->bcn_ht_cap = (struct ieee80211_ht_cap *)
(curr_bss->beacon_buf +
curr_bss->ht_cap_offset);
if (curr_bss->bcn_ht_oper)
curr_bss->bcn_ht_oper = (struct ieee80211_ht_operation *)
(curr_bss->beacon_buf +
curr_bss->ht_info_offset);
if (curr_bss->bcn_vht_cap)
curr_bss->bcn_vht_cap = (void *)(curr_bss->beacon_buf +
curr_bss->vht_cap_offset);
if (curr_bss->bcn_vht_oper)
curr_bss->bcn_vht_oper = (void *)(curr_bss->beacon_buf +
curr_bss->vht_info_offset);
if (curr_bss->bcn_bss_co_2040)
curr_bss->bcn_bss_co_2040 =
(curr_bss->beacon_buf + curr_bss->bss_co_2040_offset);
if (curr_bss->bcn_ext_cap)
curr_bss->bcn_ext_cap = curr_bss->beacon_buf +
curr_bss->ext_cap_offset;
if (curr_bss->oper_mode)
curr_bss->oper_mode = (void *)(curr_bss->beacon_buf +
curr_bss->oper_mode_offset);
}
/*
* This function frees the current BSS descriptor beacon buffer.
*/
void
mwifiex_free_curr_bcn(struct mwifiex_private *priv)
{
kfree(priv->curr_bcn_buf);
priv->curr_bcn_buf = NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_4004_0 |
crossvul-cpp_data_good_3086_1 | /*
* Copyright (C) 2014-2016 Firejail Authors
*
* This file is part of firejail 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <net/if.h>
#include "firejail.h"
//***********************************
// interface bandwidth linked list
//***********************************
typedef struct ifbw_t {
struct ifbw_t *next;
char *txt;
} IFBW;
IFBW *ifbw = NULL;
#if 0
static void ifbw_print(void) {
IFBW *ptr = ifbw;
while (ptr) {
printf("#%s#\n", ptr->txt);
ptr = ptr->next;
}
}
#endif
static void ifbw_add(IFBW *ptr) {
assert(ptr);
if (ifbw != NULL)
ptr->next = ifbw;
ifbw = ptr;
}
IFBW *ifbw_find(const char *dev) {
assert(dev);
int len = strlen(dev);
assert(len);
if (ifbw == NULL)
return NULL;
IFBW *ptr = ifbw;
while (ptr) {
if (strncmp(ptr->txt, dev, len) == 0 && ptr->txt[len] == ':')
return ptr;
ptr = ptr->next;
}
return NULL;
}
void ifbw_remove(IFBW *r) {
if (ifbw == NULL)
return;
// remove the first element
if (ifbw == r) {
ifbw = ifbw->next;
return;
}
// walk the list
IFBW *ptr = ifbw->next;
IFBW *prev = ifbw;
while (ptr) {
if (ptr == r) {
prev->next = ptr->next;
return;
}
prev = ptr;
ptr = ptr->next;
}
return;
}
int fibw_count(void) {
int rv = 0;
IFBW *ptr = ifbw;
while (ptr) {
rv++;
ptr = ptr->next;
}
return rv;
}
//***********************************
// run file handling
//***********************************
static void bandwidth_create_run_file(pid_t pid) {
char *fname;
if (asprintf(&fname, "%s/%d-bandwidth", RUN_FIREJAIL_BANDWIDTH_DIR, (int) pid) == -1)
errExit("asprintf");
// if the file already exists, do nothing
struct stat s;
if (stat(fname, &s) == 0) {
free(fname);
return;
}
// create an empty file and set mod and ownership
/* coverity[toctou] */
FILE *fp = fopen(fname, "w");
if (fp) {
SET_PERMS_STREAM(fp, 0, 0, 0644);
fclose(fp);
}
else {
fprintf(stderr, "Error: cannot create bandwidth file\n");
exit(1);
}
free(fname);
}
// delete bandwidth file
void bandwidth_del_run_file(pid_t pid) {
char *fname;
if (asprintf(&fname, "%s/%d-bandwidth", RUN_FIREJAIL_BANDWIDTH_DIR, (int) pid) == -1)
errExit("asprintf");
unlink(fname);
free(fname);
}
void network_del_run_file(pid_t pid) {
char *fname;
if (asprintf(&fname, "%s/%d-netmap", RUN_FIREJAIL_NETWORK_DIR, (int) pid) == -1)
errExit("asprintf");
unlink(fname);
free(fname);
}
void network_set_run_file(pid_t pid) {
char *fname;
if (asprintf(&fname, "%s/%d-netmap", RUN_FIREJAIL_NETWORK_DIR, (int) pid) == -1)
errExit("asprintf");
// create an empty file and set mod and ownership
FILE *fp = fopen(fname, "w");
if (fp) {
if (cfg.bridge0.configured)
fprintf(fp, "%s:%s\n", cfg.bridge0.dev, cfg.bridge0.devsandbox);
if (cfg.bridge1.configured)
fprintf(fp, "%s:%s\n", cfg.bridge1.dev, cfg.bridge1.devsandbox);
if (cfg.bridge2.configured)
fprintf(fp, "%s:%s\n", cfg.bridge2.dev, cfg.bridge2.devsandbox);
if (cfg.bridge3.configured)
fprintf(fp, "%s:%s\n", cfg.bridge3.dev, cfg.bridge3.devsandbox);
SET_PERMS_STREAM(fp, 0, 0, 0644);
fclose(fp);
}
else {
fprintf(stderr, "Error: cannot create network map file\n");
exit(1);
}
free(fname);
}
static void read_bandwidth_file(pid_t pid) {
assert(ifbw == NULL);
char *fname;
if (asprintf(&fname, "%s/%d-bandwidth", RUN_FIREJAIL_BANDWIDTH_DIR, (int) pid) == -1)
errExit("asprintf");
FILE *fp = fopen(fname, "r");
if (fp) {
char buf[1024];
while (fgets(buf, 1024,fp)) {
// remove '\n'
char *ptr = strchr(buf, '\n');
if (ptr)
*ptr = '\0';
if (strlen(buf) == 0)
continue;
// create a new IFBW entry
IFBW *ifbw_new = malloc(sizeof(IFBW));
if (!ifbw_new)
errExit("malloc");
memset(ifbw_new, 0, sizeof(IFBW));
ifbw_new->txt = strdup(buf);
if (!ifbw_new->txt)
errExit("strdup");
// add it to the linked list
ifbw_add(ifbw_new);
}
fclose(fp);
}
}
static void write_bandwidth_file(pid_t pid) {
if (ifbw == NULL)
return; // nothing to do
char *fname;
if (asprintf(&fname, "%s/%d-bandwidth", RUN_FIREJAIL_BANDWIDTH_DIR, (int) pid) == -1)
errExit("asprintf");
FILE *fp = fopen(fname, "w");
if (fp) {
IFBW *ptr = ifbw;
while (ptr) {
if (fprintf(fp, "%s\n", ptr->txt) < 0)
goto errout;
ptr = ptr->next;
}
fclose(fp);
}
else
goto errout;
return;
errout:
fprintf(stderr, "Error: cannot write bandwidth file %s\n", fname);
exit(1);
}
//***********************************
// add or remove interfaces
//***********************************
// remove interface from run file
void bandwidth_remove(pid_t pid, const char *dev) {
bandwidth_create_run_file(pid);
// read bandwidth file
read_bandwidth_file(pid);
// find the element and remove it
IFBW *elem = ifbw_find(dev);
if (elem) {
ifbw_remove(elem);
write_bandwidth_file(pid) ;
}
// remove the file if there are no entries in the list
if (ifbw == NULL) {
bandwidth_del_run_file(pid);
}
}
// add interface to run file
void bandwidth_set(pid_t pid, const char *dev, int down, int up) {
// create bandwidth directory & file in case they are not in the filesystem yet
bandwidth_create_run_file(pid);
// create the new text entry
char *txt;
if (asprintf(&txt, "%s: RX %dKB/s, TX %dKB/s", dev, down, up) == -1)
errExit("asprintf");
// read bandwidth file
read_bandwidth_file(pid);
// look for an existing entry and replace the text
IFBW *ptr = ifbw_find(dev);
if (ptr) {
assert(ptr->txt);
free(ptr->txt);
ptr->txt = txt;
}
// ... or add a new entry
else {
IFBW *ifbw_new = malloc(sizeof(IFBW));
if (!ifbw_new)
errExit("malloc");
memset(ifbw_new, 0, sizeof(IFBW));
ifbw_new->txt = txt;
// add it to the linked list
ifbw_add(ifbw_new);
}
write_bandwidth_file(pid) ;
}
//***********************************
// command execution
//***********************************
void bandwidth_pid(pid_t pid, const char *command, const char *dev, int down, int up) {
EUID_ASSERT();
//************************
// verify sandbox
//************************
EUID_ROOT();
char *comm = pid_proc_comm(pid);
EUID_USER();
if (!comm) {
fprintf(stderr, "Error: cannot find sandbox\n");
exit(1);
}
// check for firejail sandbox
if (strcmp(comm, "firejail") != 0) {
fprintf(stderr, "Error: cannot find sandbox\n");
exit(1);
}
free(comm);
// check network namespace
char *name;
if (asprintf(&name, "/run/firejail/network/%d-netmap", pid) == -1)
errExit("asprintf");
struct stat s;
if (stat(name, &s) == -1) {
fprintf(stderr, "Error: the sandbox doesn't use a new network namespace\n");
exit(1);
}
//************************
// join the network namespace
//************************
pid_t child;
if (find_child(pid, &child) == -1) {
fprintf(stderr, "Error: cannot join the network namespace\n");
exit(1);
}
EUID_ROOT();
if (join_namespace(child, "net")) {
fprintf(stderr, "Error: cannot join the network namespace\n");
exit(1);
}
// set run file
if (strcmp(command, "set") == 0)
bandwidth_set(pid, dev, down, up);
else if (strcmp(command, "clear") == 0)
bandwidth_remove(pid, dev);
//************************
// build command
//************************
char *devname = NULL;
if (dev) {
// read network map file
char *fname;
if (asprintf(&fname, "%s/%d-netmap", RUN_FIREJAIL_NETWORK_DIR, (int) pid) == -1)
errExit("asprintf");
FILE *fp = fopen(fname, "r");
if (!fp) {
fprintf(stderr, "Error: cannot read network map file %s\n", fname);
exit(1);
}
char buf[1024];
int len = strlen(dev);
while (fgets(buf, 1024, fp)) {
// remove '\n'
char *ptr = strchr(buf, '\n');
if (ptr)
*ptr = '\0';
if (*buf == '\0')
break;
if (strncmp(buf, dev, len) == 0 && buf[len] == ':') {
devname = strdup(buf + len + 1);
if (!devname)
errExit("strdup");
// check device in namespace
if (if_nametoindex(devname) == 0) {
fprintf(stderr, "Error: cannot find network device %s\n", devname);
exit(1);
}
break;
}
}
free(fname);
fclose(fp);
}
// build fshaper.sh command
char *cmd = NULL;
if (devname) {
if (strcmp(command, "set") == 0) {
if (asprintf(&cmd, "%s/firejail/fshaper.sh --%s %s %d %d",
LIBDIR, command, devname, down, up) == -1)
errExit("asprintf");
}
else {
if (asprintf(&cmd, "%s/firejail/fshaper.sh --%s %s",
LIBDIR, command, devname) == -1)
errExit("asprintf");
}
}
else {
if (asprintf(&cmd, "%s/firejail/fshaper.sh --%s", LIBDIR, command) == -1)
errExit("asprintf");
}
assert(cmd);
// wipe out environment variables
environ = NULL;
//************************
// build command
//************************
// elevate privileges
if (setreuid(0, 0))
errExit("setreuid");
if (setregid(0, 0))
errExit("setregid");
char *arg[4];
arg[0] = "/bin/sh";
arg[1] = "-c";
arg[2] = cmd;
arg[3] = NULL;
clearenv();
execvp(arg[0], arg);
// it will never get here
errExit("execvp");
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3086_1 |
crossvul-cpp_data_bad_3228_1 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3228_1 |
crossvul-cpp_data_bad_221_0 | /*
* (C) 1997 Linus Torvalds
* (C) 1999 Andrea Arcangeli <andrea@suse.de> (dynamic inode allocation)
*/
#include <linux/export.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/backing-dev.h>
#include <linux/hash.h>
#include <linux/swap.h>
#include <linux/security.h>
#include <linux/cdev.h>
#include <linux/bootmem.h>
#include <linux/fsnotify.h>
#include <linux/mount.h>
#include <linux/posix_acl.h>
#include <linux/prefetch.h>
#include <linux/buffer_head.h> /* for inode_has_buffers */
#include <linux/ratelimit.h>
#include <linux/list_lru.h>
#include <linux/iversion.h>
#include <trace/events/writeback.h>
#include "internal.h"
/*
* Inode locking rules:
*
* inode->i_lock protects:
* inode->i_state, inode->i_hash, __iget()
* Inode LRU list locks protect:
* inode->i_sb->s_inode_lru, inode->i_lru
* inode->i_sb->s_inode_list_lock protects:
* inode->i_sb->s_inodes, inode->i_sb_list
* bdi->wb.list_lock protects:
* bdi->wb.b_{dirty,io,more_io,dirty_time}, inode->i_io_list
* inode_hash_lock protects:
* inode_hashtable, inode->i_hash
*
* Lock ordering:
*
* inode->i_sb->s_inode_list_lock
* inode->i_lock
* Inode LRU list locks
*
* bdi->wb.list_lock
* inode->i_lock
*
* inode_hash_lock
* inode->i_sb->s_inode_list_lock
* inode->i_lock
*
* iunique_lock
* inode_hash_lock
*/
static unsigned int i_hash_mask __read_mostly;
static unsigned int i_hash_shift __read_mostly;
static struct hlist_head *inode_hashtable __read_mostly;
static __cacheline_aligned_in_smp DEFINE_SPINLOCK(inode_hash_lock);
/*
* Empty aops. Can be used for the cases where the user does not
* define any of the address_space operations.
*/
const struct address_space_operations empty_aops = {
};
EXPORT_SYMBOL(empty_aops);
/*
* Statistics gathering..
*/
struct inodes_stat_t inodes_stat;
static DEFINE_PER_CPU(unsigned long, nr_inodes);
static DEFINE_PER_CPU(unsigned long, nr_unused);
static struct kmem_cache *inode_cachep __read_mostly;
static long get_nr_inodes(void)
{
int i;
long sum = 0;
for_each_possible_cpu(i)
sum += per_cpu(nr_inodes, i);
return sum < 0 ? 0 : sum;
}
static inline long get_nr_inodes_unused(void)
{
int i;
long sum = 0;
for_each_possible_cpu(i)
sum += per_cpu(nr_unused, i);
return sum < 0 ? 0 : sum;
}
long get_nr_dirty_inodes(void)
{
/* not actually dirty inodes, but a wild approximation */
long nr_dirty = get_nr_inodes() - get_nr_inodes_unused();
return nr_dirty > 0 ? nr_dirty : 0;
}
/*
* Handle nr_inode sysctl
*/
#ifdef CONFIG_SYSCTL
int proc_nr_inodes(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
inodes_stat.nr_inodes = get_nr_inodes();
inodes_stat.nr_unused = get_nr_inodes_unused();
return proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
}
#endif
static int no_open(struct inode *inode, struct file *file)
{
return -ENXIO;
}
/**
* inode_init_always - perform inode structure initialisation
* @sb: superblock inode belongs to
* @inode: inode to initialise
*
* These are initializations that need to be done on every inode
* allocation as the fields are not initialised by slab allocation.
*/
int inode_init_always(struct super_block *sb, struct inode *inode)
{
static const struct inode_operations empty_iops;
static const struct file_operations no_open_fops = {.open = no_open};
struct address_space *const mapping = &inode->i_data;
inode->i_sb = sb;
inode->i_blkbits = sb->s_blocksize_bits;
inode->i_flags = 0;
atomic_set(&inode->i_count, 1);
inode->i_op = &empty_iops;
inode->i_fop = &no_open_fops;
inode->__i_nlink = 1;
inode->i_opflags = 0;
if (sb->s_xattr)
inode->i_opflags |= IOP_XATTR;
i_uid_write(inode, 0);
i_gid_write(inode, 0);
atomic_set(&inode->i_writecount, 0);
inode->i_size = 0;
inode->i_write_hint = WRITE_LIFE_NOT_SET;
inode->i_blocks = 0;
inode->i_bytes = 0;
inode->i_generation = 0;
inode->i_pipe = NULL;
inode->i_bdev = NULL;
inode->i_cdev = NULL;
inode->i_link = NULL;
inode->i_dir_seq = 0;
inode->i_rdev = 0;
inode->dirtied_when = 0;
#ifdef CONFIG_CGROUP_WRITEBACK
inode->i_wb_frn_winner = 0;
inode->i_wb_frn_avg_time = 0;
inode->i_wb_frn_history = 0;
#endif
if (security_inode_alloc(inode))
goto out;
spin_lock_init(&inode->i_lock);
lockdep_set_class(&inode->i_lock, &sb->s_type->i_lock_key);
init_rwsem(&inode->i_rwsem);
lockdep_set_class(&inode->i_rwsem, &sb->s_type->i_mutex_key);
atomic_set(&inode->i_dio_count, 0);
mapping->a_ops = &empty_aops;
mapping->host = inode;
mapping->flags = 0;
mapping->wb_err = 0;
atomic_set(&mapping->i_mmap_writable, 0);
mapping_set_gfp_mask(mapping, GFP_HIGHUSER_MOVABLE);
mapping->private_data = NULL;
mapping->writeback_index = 0;
inode->i_private = NULL;
inode->i_mapping = mapping;
INIT_HLIST_HEAD(&inode->i_dentry); /* buggered by rcu freeing */
#ifdef CONFIG_FS_POSIX_ACL
inode->i_acl = inode->i_default_acl = ACL_NOT_CACHED;
#endif
#ifdef CONFIG_FSNOTIFY
inode->i_fsnotify_mask = 0;
#endif
inode->i_flctx = NULL;
this_cpu_inc(nr_inodes);
return 0;
out:
return -ENOMEM;
}
EXPORT_SYMBOL(inode_init_always);
static struct inode *alloc_inode(struct super_block *sb)
{
struct inode *inode;
if (sb->s_op->alloc_inode)
inode = sb->s_op->alloc_inode(sb);
else
inode = kmem_cache_alloc(inode_cachep, GFP_KERNEL);
if (!inode)
return NULL;
if (unlikely(inode_init_always(sb, inode))) {
if (inode->i_sb->s_op->destroy_inode)
inode->i_sb->s_op->destroy_inode(inode);
else
kmem_cache_free(inode_cachep, inode);
return NULL;
}
return inode;
}
void free_inode_nonrcu(struct inode *inode)
{
kmem_cache_free(inode_cachep, inode);
}
EXPORT_SYMBOL(free_inode_nonrcu);
void __destroy_inode(struct inode *inode)
{
BUG_ON(inode_has_buffers(inode));
inode_detach_wb(inode);
security_inode_free(inode);
fsnotify_inode_delete(inode);
locks_free_lock_context(inode);
if (!inode->i_nlink) {
WARN_ON(atomic_long_read(&inode->i_sb->s_remove_count) == 0);
atomic_long_dec(&inode->i_sb->s_remove_count);
}
#ifdef CONFIG_FS_POSIX_ACL
if (inode->i_acl && !is_uncached_acl(inode->i_acl))
posix_acl_release(inode->i_acl);
if (inode->i_default_acl && !is_uncached_acl(inode->i_default_acl))
posix_acl_release(inode->i_default_acl);
#endif
this_cpu_dec(nr_inodes);
}
EXPORT_SYMBOL(__destroy_inode);
static void i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(inode_cachep, inode);
}
static void destroy_inode(struct inode *inode)
{
BUG_ON(!list_empty(&inode->i_lru));
__destroy_inode(inode);
if (inode->i_sb->s_op->destroy_inode)
inode->i_sb->s_op->destroy_inode(inode);
else
call_rcu(&inode->i_rcu, i_callback);
}
/**
* drop_nlink - directly drop an inode's link count
* @inode: inode
*
* This is a low-level filesystem helper to replace any
* direct filesystem manipulation of i_nlink. In cases
* where we are attempting to track writes to the
* filesystem, a decrement to zero means an imminent
* write when the file is truncated and actually unlinked
* on the filesystem.
*/
void drop_nlink(struct inode *inode)
{
WARN_ON(inode->i_nlink == 0);
inode->__i_nlink--;
if (!inode->i_nlink)
atomic_long_inc(&inode->i_sb->s_remove_count);
}
EXPORT_SYMBOL(drop_nlink);
/**
* clear_nlink - directly zero an inode's link count
* @inode: inode
*
* This is a low-level filesystem helper to replace any
* direct filesystem manipulation of i_nlink. See
* drop_nlink() for why we care about i_nlink hitting zero.
*/
void clear_nlink(struct inode *inode)
{
if (inode->i_nlink) {
inode->__i_nlink = 0;
atomic_long_inc(&inode->i_sb->s_remove_count);
}
}
EXPORT_SYMBOL(clear_nlink);
/**
* set_nlink - directly set an inode's link count
* @inode: inode
* @nlink: new nlink (should be non-zero)
*
* This is a low-level filesystem helper to replace any
* direct filesystem manipulation of i_nlink.
*/
void set_nlink(struct inode *inode, unsigned int nlink)
{
if (!nlink) {
clear_nlink(inode);
} else {
/* Yes, some filesystems do change nlink from zero to one */
if (inode->i_nlink == 0)
atomic_long_dec(&inode->i_sb->s_remove_count);
inode->__i_nlink = nlink;
}
}
EXPORT_SYMBOL(set_nlink);
/**
* inc_nlink - directly increment an inode's link count
* @inode: inode
*
* This is a low-level filesystem helper to replace any
* direct filesystem manipulation of i_nlink. Currently,
* it is only here for parity with dec_nlink().
*/
void inc_nlink(struct inode *inode)
{
if (unlikely(inode->i_nlink == 0)) {
WARN_ON(!(inode->i_state & I_LINKABLE));
atomic_long_dec(&inode->i_sb->s_remove_count);
}
inode->__i_nlink++;
}
EXPORT_SYMBOL(inc_nlink);
static void __address_space_init_once(struct address_space *mapping)
{
INIT_RADIX_TREE(&mapping->i_pages, GFP_ATOMIC | __GFP_ACCOUNT);
init_rwsem(&mapping->i_mmap_rwsem);
INIT_LIST_HEAD(&mapping->private_list);
spin_lock_init(&mapping->private_lock);
mapping->i_mmap = RB_ROOT_CACHED;
}
void address_space_init_once(struct address_space *mapping)
{
memset(mapping, 0, sizeof(*mapping));
__address_space_init_once(mapping);
}
EXPORT_SYMBOL(address_space_init_once);
/*
* These are initializations that only need to be done
* once, because the fields are idempotent across use
* of the inode, so let the slab aware of that.
*/
void inode_init_once(struct inode *inode)
{
memset(inode, 0, sizeof(*inode));
INIT_HLIST_NODE(&inode->i_hash);
INIT_LIST_HEAD(&inode->i_devices);
INIT_LIST_HEAD(&inode->i_io_list);
INIT_LIST_HEAD(&inode->i_wb_list);
INIT_LIST_HEAD(&inode->i_lru);
__address_space_init_once(&inode->i_data);
i_size_ordered_init(inode);
}
EXPORT_SYMBOL(inode_init_once);
static void init_once(void *foo)
{
struct inode *inode = (struct inode *) foo;
inode_init_once(inode);
}
/*
* inode->i_lock must be held
*/
void __iget(struct inode *inode)
{
atomic_inc(&inode->i_count);
}
/*
* get additional reference to inode; caller must already hold one.
*/
void ihold(struct inode *inode)
{
WARN_ON(atomic_inc_return(&inode->i_count) < 2);
}
EXPORT_SYMBOL(ihold);
static void inode_lru_list_add(struct inode *inode)
{
if (list_lru_add(&inode->i_sb->s_inode_lru, &inode->i_lru))
this_cpu_inc(nr_unused);
else
inode->i_state |= I_REFERENCED;
}
/*
* Add inode to LRU if needed (inode is unused and clean).
*
* Needs inode->i_lock held.
*/
void inode_add_lru(struct inode *inode)
{
if (!(inode->i_state & (I_DIRTY_ALL | I_SYNC |
I_FREEING | I_WILL_FREE)) &&
!atomic_read(&inode->i_count) && inode->i_sb->s_flags & SB_ACTIVE)
inode_lru_list_add(inode);
}
static void inode_lru_list_del(struct inode *inode)
{
if (list_lru_del(&inode->i_sb->s_inode_lru, &inode->i_lru))
this_cpu_dec(nr_unused);
}
/**
* inode_sb_list_add - add inode to the superblock list of inodes
* @inode: inode to add
*/
void inode_sb_list_add(struct inode *inode)
{
spin_lock(&inode->i_sb->s_inode_list_lock);
list_add(&inode->i_sb_list, &inode->i_sb->s_inodes);
spin_unlock(&inode->i_sb->s_inode_list_lock);
}
EXPORT_SYMBOL_GPL(inode_sb_list_add);
static inline void inode_sb_list_del(struct inode *inode)
{
if (!list_empty(&inode->i_sb_list)) {
spin_lock(&inode->i_sb->s_inode_list_lock);
list_del_init(&inode->i_sb_list);
spin_unlock(&inode->i_sb->s_inode_list_lock);
}
}
static unsigned long hash(struct super_block *sb, unsigned long hashval)
{
unsigned long tmp;
tmp = (hashval * (unsigned long)sb) ^ (GOLDEN_RATIO_PRIME + hashval) /
L1_CACHE_BYTES;
tmp = tmp ^ ((tmp ^ GOLDEN_RATIO_PRIME) >> i_hash_shift);
return tmp & i_hash_mask;
}
/**
* __insert_inode_hash - hash an inode
* @inode: unhashed inode
* @hashval: unsigned long value used to locate this object in the
* inode_hashtable.
*
* Add an inode to the inode hash for this superblock.
*/
void __insert_inode_hash(struct inode *inode, unsigned long hashval)
{
struct hlist_head *b = inode_hashtable + hash(inode->i_sb, hashval);
spin_lock(&inode_hash_lock);
spin_lock(&inode->i_lock);
hlist_add_head(&inode->i_hash, b);
spin_unlock(&inode->i_lock);
spin_unlock(&inode_hash_lock);
}
EXPORT_SYMBOL(__insert_inode_hash);
/**
* __remove_inode_hash - remove an inode from the hash
* @inode: inode to unhash
*
* Remove an inode from the superblock.
*/
void __remove_inode_hash(struct inode *inode)
{
spin_lock(&inode_hash_lock);
spin_lock(&inode->i_lock);
hlist_del_init(&inode->i_hash);
spin_unlock(&inode->i_lock);
spin_unlock(&inode_hash_lock);
}
EXPORT_SYMBOL(__remove_inode_hash);
void clear_inode(struct inode *inode)
{
/*
* We have to cycle the i_pages lock here because reclaim can be in the
* process of removing the last page (in __delete_from_page_cache())
* and we must not free the mapping under it.
*/
xa_lock_irq(&inode->i_data.i_pages);
BUG_ON(inode->i_data.nrpages);
BUG_ON(inode->i_data.nrexceptional);
xa_unlock_irq(&inode->i_data.i_pages);
BUG_ON(!list_empty(&inode->i_data.private_list));
BUG_ON(!(inode->i_state & I_FREEING));
BUG_ON(inode->i_state & I_CLEAR);
BUG_ON(!list_empty(&inode->i_wb_list));
/* don't need i_lock here, no concurrent mods to i_state */
inode->i_state = I_FREEING | I_CLEAR;
}
EXPORT_SYMBOL(clear_inode);
/*
* Free the inode passed in, removing it from the lists it is still connected
* to. We remove any pages still attached to the inode and wait for any IO that
* is still in progress before finally destroying the inode.
*
* An inode must already be marked I_FREEING so that we avoid the inode being
* moved back onto lists if we race with other code that manipulates the lists
* (e.g. writeback_single_inode). The caller is responsible for setting this.
*
* An inode must already be removed from the LRU list before being evicted from
* the cache. This should occur atomically with setting the I_FREEING state
* flag, so no inodes here should ever be on the LRU when being evicted.
*/
static void evict(struct inode *inode)
{
const struct super_operations *op = inode->i_sb->s_op;
BUG_ON(!(inode->i_state & I_FREEING));
BUG_ON(!list_empty(&inode->i_lru));
if (!list_empty(&inode->i_io_list))
inode_io_list_del(inode);
inode_sb_list_del(inode);
/*
* Wait for flusher thread to be done with the inode so that filesystem
* does not start destroying it while writeback is still running. Since
* the inode has I_FREEING set, flusher thread won't start new work on
* the inode. We just have to wait for running writeback to finish.
*/
inode_wait_for_writeback(inode);
if (op->evict_inode) {
op->evict_inode(inode);
} else {
truncate_inode_pages_final(&inode->i_data);
clear_inode(inode);
}
if (S_ISBLK(inode->i_mode) && inode->i_bdev)
bd_forget(inode);
if (S_ISCHR(inode->i_mode) && inode->i_cdev)
cd_forget(inode);
remove_inode_hash(inode);
spin_lock(&inode->i_lock);
wake_up_bit(&inode->i_state, __I_NEW);
BUG_ON(inode->i_state != (I_FREEING | I_CLEAR));
spin_unlock(&inode->i_lock);
destroy_inode(inode);
}
/*
* dispose_list - dispose of the contents of a local list
* @head: the head of the list to free
*
* Dispose-list gets a local list with local inodes in it, so it doesn't
* need to worry about list corruption and SMP locks.
*/
static void dispose_list(struct list_head *head)
{
while (!list_empty(head)) {
struct inode *inode;
inode = list_first_entry(head, struct inode, i_lru);
list_del_init(&inode->i_lru);
evict(inode);
cond_resched();
}
}
/**
* evict_inodes - evict all evictable inodes for a superblock
* @sb: superblock to operate on
*
* Make sure that no inodes with zero refcount are retained. This is
* called by superblock shutdown after having SB_ACTIVE flag removed,
* so any inode reaching zero refcount during or after that call will
* be immediately evicted.
*/
void evict_inodes(struct super_block *sb)
{
struct inode *inode, *next;
LIST_HEAD(dispose);
again:
spin_lock(&sb->s_inode_list_lock);
list_for_each_entry_safe(inode, next, &sb->s_inodes, i_sb_list) {
if (atomic_read(&inode->i_count))
continue;
spin_lock(&inode->i_lock);
if (inode->i_state & (I_NEW | I_FREEING | I_WILL_FREE)) {
spin_unlock(&inode->i_lock);
continue;
}
inode->i_state |= I_FREEING;
inode_lru_list_del(inode);
spin_unlock(&inode->i_lock);
list_add(&inode->i_lru, &dispose);
/*
* We can have a ton of inodes to evict at unmount time given
* enough memory, check to see if we need to go to sleep for a
* bit so we don't livelock.
*/
if (need_resched()) {
spin_unlock(&sb->s_inode_list_lock);
cond_resched();
dispose_list(&dispose);
goto again;
}
}
spin_unlock(&sb->s_inode_list_lock);
dispose_list(&dispose);
}
EXPORT_SYMBOL_GPL(evict_inodes);
/**
* invalidate_inodes - attempt to free all inodes on a superblock
* @sb: superblock to operate on
* @kill_dirty: flag to guide handling of dirty inodes
*
* Attempts to free all inodes for a given superblock. If there were any
* busy inodes return a non-zero value, else zero.
* If @kill_dirty is set, discard dirty inodes too, otherwise treat
* them as busy.
*/
int invalidate_inodes(struct super_block *sb, bool kill_dirty)
{
int busy = 0;
struct inode *inode, *next;
LIST_HEAD(dispose);
spin_lock(&sb->s_inode_list_lock);
list_for_each_entry_safe(inode, next, &sb->s_inodes, i_sb_list) {
spin_lock(&inode->i_lock);
if (inode->i_state & (I_NEW | I_FREEING | I_WILL_FREE)) {
spin_unlock(&inode->i_lock);
continue;
}
if (inode->i_state & I_DIRTY_ALL && !kill_dirty) {
spin_unlock(&inode->i_lock);
busy = 1;
continue;
}
if (atomic_read(&inode->i_count)) {
spin_unlock(&inode->i_lock);
busy = 1;
continue;
}
inode->i_state |= I_FREEING;
inode_lru_list_del(inode);
spin_unlock(&inode->i_lock);
list_add(&inode->i_lru, &dispose);
}
spin_unlock(&sb->s_inode_list_lock);
dispose_list(&dispose);
return busy;
}
/*
* Isolate the inode from the LRU in preparation for freeing it.
*
* Any inodes which are pinned purely because of attached pagecache have their
* pagecache removed. If the inode has metadata buffers attached to
* mapping->private_list then try to remove them.
*
* If the inode has the I_REFERENCED flag set, then it means that it has been
* used recently - the flag is set in iput_final(). When we encounter such an
* inode, clear the flag and move it to the back of the LRU so it gets another
* pass through the LRU before it gets reclaimed. This is necessary because of
* the fact we are doing lazy LRU updates to minimise lock contention so the
* LRU does not have strict ordering. Hence we don't want to reclaim inodes
* with this flag set because they are the inodes that are out of order.
*/
static enum lru_status inode_lru_isolate(struct list_head *item,
struct list_lru_one *lru, spinlock_t *lru_lock, void *arg)
{
struct list_head *freeable = arg;
struct inode *inode = container_of(item, struct inode, i_lru);
/*
* we are inverting the lru lock/inode->i_lock here, so use a trylock.
* If we fail to get the lock, just skip it.
*/
if (!spin_trylock(&inode->i_lock))
return LRU_SKIP;
/*
* Referenced or dirty inodes are still in use. Give them another pass
* through the LRU as we canot reclaim them now.
*/
if (atomic_read(&inode->i_count) ||
(inode->i_state & ~I_REFERENCED)) {
list_lru_isolate(lru, &inode->i_lru);
spin_unlock(&inode->i_lock);
this_cpu_dec(nr_unused);
return LRU_REMOVED;
}
/* recently referenced inodes get one more pass */
if (inode->i_state & I_REFERENCED) {
inode->i_state &= ~I_REFERENCED;
spin_unlock(&inode->i_lock);
return LRU_ROTATE;
}
if (inode_has_buffers(inode) || inode->i_data.nrpages) {
__iget(inode);
spin_unlock(&inode->i_lock);
spin_unlock(lru_lock);
if (remove_inode_buffers(inode)) {
unsigned long reap;
reap = invalidate_mapping_pages(&inode->i_data, 0, -1);
if (current_is_kswapd())
__count_vm_events(KSWAPD_INODESTEAL, reap);
else
__count_vm_events(PGINODESTEAL, reap);
if (current->reclaim_state)
current->reclaim_state->reclaimed_slab += reap;
}
iput(inode);
spin_lock(lru_lock);
return LRU_RETRY;
}
WARN_ON(inode->i_state & I_NEW);
inode->i_state |= I_FREEING;
list_lru_isolate_move(lru, &inode->i_lru, freeable);
spin_unlock(&inode->i_lock);
this_cpu_dec(nr_unused);
return LRU_REMOVED;
}
/*
* Walk the superblock inode LRU for freeable inodes and attempt to free them.
* This is called from the superblock shrinker function with a number of inodes
* to trim from the LRU. Inodes to be freed are moved to a temporary list and
* then are freed outside inode_lock by dispose_list().
*/
long prune_icache_sb(struct super_block *sb, struct shrink_control *sc)
{
LIST_HEAD(freeable);
long freed;
freed = list_lru_shrink_walk(&sb->s_inode_lru, sc,
inode_lru_isolate, &freeable);
dispose_list(&freeable);
return freed;
}
static void __wait_on_freeing_inode(struct inode *inode);
/*
* Called with the inode lock held.
*/
static struct inode *find_inode(struct super_block *sb,
struct hlist_head *head,
int (*test)(struct inode *, void *),
void *data)
{
struct inode *inode = NULL;
repeat:
hlist_for_each_entry(inode, head, i_hash) {
if (inode->i_sb != sb)
continue;
if (!test(inode, data))
continue;
spin_lock(&inode->i_lock);
if (inode->i_state & (I_FREEING|I_WILL_FREE)) {
__wait_on_freeing_inode(inode);
goto repeat;
}
__iget(inode);
spin_unlock(&inode->i_lock);
return inode;
}
return NULL;
}
/*
* find_inode_fast is the fast path version of find_inode, see the comment at
* iget_locked for details.
*/
static struct inode *find_inode_fast(struct super_block *sb,
struct hlist_head *head, unsigned long ino)
{
struct inode *inode = NULL;
repeat:
hlist_for_each_entry(inode, head, i_hash) {
if (inode->i_ino != ino)
continue;
if (inode->i_sb != sb)
continue;
spin_lock(&inode->i_lock);
if (inode->i_state & (I_FREEING|I_WILL_FREE)) {
__wait_on_freeing_inode(inode);
goto repeat;
}
__iget(inode);
spin_unlock(&inode->i_lock);
return inode;
}
return NULL;
}
/*
* Each cpu owns a range of LAST_INO_BATCH numbers.
* 'shared_last_ino' is dirtied only once out of LAST_INO_BATCH allocations,
* to renew the exhausted range.
*
* This does not significantly increase overflow rate because every CPU can
* consume at most LAST_INO_BATCH-1 unused inode numbers. So there is
* NR_CPUS*(LAST_INO_BATCH-1) wastage. At 4096 and 1024, this is ~0.1% of the
* 2^32 range, and is a worst-case. Even a 50% wastage would only increase
* overflow rate by 2x, which does not seem too significant.
*
* On a 32bit, non LFS stat() call, glibc will generate an EOVERFLOW
* error if st_ino won't fit in target struct field. Use 32bit counter
* here to attempt to avoid that.
*/
#define LAST_INO_BATCH 1024
static DEFINE_PER_CPU(unsigned int, last_ino);
unsigned int get_next_ino(void)
{
unsigned int *p = &get_cpu_var(last_ino);
unsigned int res = *p;
#ifdef CONFIG_SMP
if (unlikely((res & (LAST_INO_BATCH-1)) == 0)) {
static atomic_t shared_last_ino;
int next = atomic_add_return(LAST_INO_BATCH, &shared_last_ino);
res = next - LAST_INO_BATCH;
}
#endif
res++;
/* get_next_ino should not provide a 0 inode number */
if (unlikely(!res))
res++;
*p = res;
put_cpu_var(last_ino);
return res;
}
EXPORT_SYMBOL(get_next_ino);
/**
* new_inode_pseudo - obtain an inode
* @sb: superblock
*
* Allocates a new inode for given superblock.
* Inode wont be chained in superblock s_inodes list
* This means :
* - fs can't be unmount
* - quotas, fsnotify, writeback can't work
*/
struct inode *new_inode_pseudo(struct super_block *sb)
{
struct inode *inode = alloc_inode(sb);
if (inode) {
spin_lock(&inode->i_lock);
inode->i_state = 0;
spin_unlock(&inode->i_lock);
INIT_LIST_HEAD(&inode->i_sb_list);
}
return inode;
}
/**
* new_inode - obtain an inode
* @sb: superblock
*
* Allocates a new inode for given superblock. The default gfp_mask
* for allocations related to inode->i_mapping is GFP_HIGHUSER_MOVABLE.
* If HIGHMEM pages are unsuitable or it is known that pages allocated
* for the page cache are not reclaimable or migratable,
* mapping_set_gfp_mask() must be called with suitable flags on the
* newly created inode's mapping
*
*/
struct inode *new_inode(struct super_block *sb)
{
struct inode *inode;
spin_lock_prefetch(&sb->s_inode_list_lock);
inode = new_inode_pseudo(sb);
if (inode)
inode_sb_list_add(inode);
return inode;
}
EXPORT_SYMBOL(new_inode);
#ifdef CONFIG_DEBUG_LOCK_ALLOC
void lockdep_annotate_inode_mutex_key(struct inode *inode)
{
if (S_ISDIR(inode->i_mode)) {
struct file_system_type *type = inode->i_sb->s_type;
/* Set new key only if filesystem hasn't already changed it */
if (lockdep_match_class(&inode->i_rwsem, &type->i_mutex_key)) {
/*
* ensure nobody is actually holding i_mutex
*/
// mutex_destroy(&inode->i_mutex);
init_rwsem(&inode->i_rwsem);
lockdep_set_class(&inode->i_rwsem,
&type->i_mutex_dir_key);
}
}
}
EXPORT_SYMBOL(lockdep_annotate_inode_mutex_key);
#endif
/**
* unlock_new_inode - clear the I_NEW state and wake up any waiters
* @inode: new inode to unlock
*
* Called when the inode is fully initialised to clear the new state of the
* inode and wake up anyone waiting for the inode to finish initialisation.
*/
void unlock_new_inode(struct inode *inode)
{
lockdep_annotate_inode_mutex_key(inode);
spin_lock(&inode->i_lock);
WARN_ON(!(inode->i_state & I_NEW));
inode->i_state &= ~I_NEW;
smp_mb();
wake_up_bit(&inode->i_state, __I_NEW);
spin_unlock(&inode->i_lock);
}
EXPORT_SYMBOL(unlock_new_inode);
/**
* lock_two_nondirectories - take two i_mutexes on non-directory objects
*
* Lock any non-NULL argument that is not a directory.
* Zero, one or two objects may be locked by this function.
*
* @inode1: first inode to lock
* @inode2: second inode to lock
*/
void lock_two_nondirectories(struct inode *inode1, struct inode *inode2)
{
if (inode1 > inode2)
swap(inode1, inode2);
if (inode1 && !S_ISDIR(inode1->i_mode))
inode_lock(inode1);
if (inode2 && !S_ISDIR(inode2->i_mode) && inode2 != inode1)
inode_lock_nested(inode2, I_MUTEX_NONDIR2);
}
EXPORT_SYMBOL(lock_two_nondirectories);
/**
* unlock_two_nondirectories - release locks from lock_two_nondirectories()
* @inode1: first inode to unlock
* @inode2: second inode to unlock
*/
void unlock_two_nondirectories(struct inode *inode1, struct inode *inode2)
{
if (inode1 && !S_ISDIR(inode1->i_mode))
inode_unlock(inode1);
if (inode2 && !S_ISDIR(inode2->i_mode) && inode2 != inode1)
inode_unlock(inode2);
}
EXPORT_SYMBOL(unlock_two_nondirectories);
/**
* inode_insert5 - obtain an inode from a mounted file system
* @inode: pre-allocated inode to use for insert to cache
* @hashval: hash value (usually inode number) to get
* @test: callback used for comparisons between inodes
* @set: callback used to initialize a new struct inode
* @data: opaque data pointer to pass to @test and @set
*
* Search for the inode specified by @hashval and @data in the inode cache,
* and if present it is return it with an increased reference count. This is
* a variant of iget5_locked() for callers that don't want to fail on memory
* allocation of inode.
*
* If the inode is not in cache, insert the pre-allocated inode to cache and
* return it locked, hashed, and with the I_NEW flag set. The file system gets
* to fill it in before unlocking it via unlock_new_inode().
*
* Note both @test and @set are called with the inode_hash_lock held, so can't
* sleep.
*/
struct inode *inode_insert5(struct inode *inode, unsigned long hashval,
int (*test)(struct inode *, void *),
int (*set)(struct inode *, void *), void *data)
{
struct hlist_head *head = inode_hashtable + hash(inode->i_sb, hashval);
struct inode *old;
again:
spin_lock(&inode_hash_lock);
old = find_inode(inode->i_sb, head, test, data);
if (unlikely(old)) {
/*
* Uhhuh, somebody else created the same inode under us.
* Use the old inode instead of the preallocated one.
*/
spin_unlock(&inode_hash_lock);
wait_on_inode(old);
if (unlikely(inode_unhashed(old))) {
iput(old);
goto again;
}
return old;
}
if (set && unlikely(set(inode, data))) {
inode = NULL;
goto unlock;
}
/*
* Return the locked inode with I_NEW set, the
* caller is responsible for filling in the contents
*/
spin_lock(&inode->i_lock);
inode->i_state |= I_NEW;
hlist_add_head(&inode->i_hash, head);
spin_unlock(&inode->i_lock);
unlock:
spin_unlock(&inode_hash_lock);
return inode;
}
EXPORT_SYMBOL(inode_insert5);
/**
* iget5_locked - obtain an inode from a mounted file system
* @sb: super block of file system
* @hashval: hash value (usually inode number) to get
* @test: callback used for comparisons between inodes
* @set: callback used to initialize a new struct inode
* @data: opaque data pointer to pass to @test and @set
*
* Search for the inode specified by @hashval and @data in the inode cache,
* and if present it is return it with an increased reference count. This is
* a generalized version of iget_locked() for file systems where the inode
* number is not sufficient for unique identification of an inode.
*
* If the inode is not in cache, allocate a new inode and return it locked,
* hashed, and with the I_NEW flag set. The file system gets to fill it in
* before unlocking it via unlock_new_inode().
*
* Note both @test and @set are called with the inode_hash_lock held, so can't
* sleep.
*/
struct inode *iget5_locked(struct super_block *sb, unsigned long hashval,
int (*test)(struct inode *, void *),
int (*set)(struct inode *, void *), void *data)
{
struct inode *inode = ilookup5(sb, hashval, test, data);
if (!inode) {
struct inode *new = new_inode(sb);
if (new) {
inode = inode_insert5(new, hashval, test, set, data);
if (unlikely(inode != new))
iput(new);
}
}
return inode;
}
EXPORT_SYMBOL(iget5_locked);
/**
* iget_locked - obtain an inode from a mounted file system
* @sb: super block of file system
* @ino: inode number to get
*
* Search for the inode specified by @ino in the inode cache and if present
* return it with an increased reference count. This is for file systems
* where the inode number is sufficient for unique identification of an inode.
*
* If the inode is not in cache, allocate a new inode and return it locked,
* hashed, and with the I_NEW flag set. The file system gets to fill it in
* before unlocking it via unlock_new_inode().
*/
struct inode *iget_locked(struct super_block *sb, unsigned long ino)
{
struct hlist_head *head = inode_hashtable + hash(sb, ino);
struct inode *inode;
again:
spin_lock(&inode_hash_lock);
inode = find_inode_fast(sb, head, ino);
spin_unlock(&inode_hash_lock);
if (inode) {
wait_on_inode(inode);
if (unlikely(inode_unhashed(inode))) {
iput(inode);
goto again;
}
return inode;
}
inode = alloc_inode(sb);
if (inode) {
struct inode *old;
spin_lock(&inode_hash_lock);
/* We released the lock, so.. */
old = find_inode_fast(sb, head, ino);
if (!old) {
inode->i_ino = ino;
spin_lock(&inode->i_lock);
inode->i_state = I_NEW;
hlist_add_head(&inode->i_hash, head);
spin_unlock(&inode->i_lock);
inode_sb_list_add(inode);
spin_unlock(&inode_hash_lock);
/* Return the locked inode with I_NEW set, the
* caller is responsible for filling in the contents
*/
return inode;
}
/*
* Uhhuh, somebody else created the same inode under
* us. Use the old inode instead of the one we just
* allocated.
*/
spin_unlock(&inode_hash_lock);
destroy_inode(inode);
inode = old;
wait_on_inode(inode);
if (unlikely(inode_unhashed(inode))) {
iput(inode);
goto again;
}
}
return inode;
}
EXPORT_SYMBOL(iget_locked);
/*
* search the inode cache for a matching inode number.
* If we find one, then the inode number we are trying to
* allocate is not unique and so we should not use it.
*
* Returns 1 if the inode number is unique, 0 if it is not.
*/
static int test_inode_iunique(struct super_block *sb, unsigned long ino)
{
struct hlist_head *b = inode_hashtable + hash(sb, ino);
struct inode *inode;
spin_lock(&inode_hash_lock);
hlist_for_each_entry(inode, b, i_hash) {
if (inode->i_ino == ino && inode->i_sb == sb) {
spin_unlock(&inode_hash_lock);
return 0;
}
}
spin_unlock(&inode_hash_lock);
return 1;
}
/**
* iunique - get a unique inode number
* @sb: superblock
* @max_reserved: highest reserved inode number
*
* Obtain an inode number that is unique on the system for a given
* superblock. This is used by file systems that have no natural
* permanent inode numbering system. An inode number is returned that
* is higher than the reserved limit but unique.
*
* BUGS:
* With a large number of inodes live on the file system this function
* currently becomes quite slow.
*/
ino_t iunique(struct super_block *sb, ino_t max_reserved)
{
/*
* On a 32bit, non LFS stat() call, glibc will generate an EOVERFLOW
* error if st_ino won't fit in target struct field. Use 32bit counter
* here to attempt to avoid that.
*/
static DEFINE_SPINLOCK(iunique_lock);
static unsigned int counter;
ino_t res;
spin_lock(&iunique_lock);
do {
if (counter <= max_reserved)
counter = max_reserved + 1;
res = counter++;
} while (!test_inode_iunique(sb, res));
spin_unlock(&iunique_lock);
return res;
}
EXPORT_SYMBOL(iunique);
struct inode *igrab(struct inode *inode)
{
spin_lock(&inode->i_lock);
if (!(inode->i_state & (I_FREEING|I_WILL_FREE))) {
__iget(inode);
spin_unlock(&inode->i_lock);
} else {
spin_unlock(&inode->i_lock);
/*
* Handle the case where s_op->clear_inode is not been
* called yet, and somebody is calling igrab
* while the inode is getting freed.
*/
inode = NULL;
}
return inode;
}
EXPORT_SYMBOL(igrab);
/**
* ilookup5_nowait - search for an inode in the inode cache
* @sb: super block of file system to search
* @hashval: hash value (usually inode number) to search for
* @test: callback used for comparisons between inodes
* @data: opaque data pointer to pass to @test
*
* Search for the inode specified by @hashval and @data in the inode cache.
* If the inode is in the cache, the inode is returned with an incremented
* reference count.
*
* Note: I_NEW is not waited upon so you have to be very careful what you do
* with the returned inode. You probably should be using ilookup5() instead.
*
* Note2: @test is called with the inode_hash_lock held, so can't sleep.
*/
struct inode *ilookup5_nowait(struct super_block *sb, unsigned long hashval,
int (*test)(struct inode *, void *), void *data)
{
struct hlist_head *head = inode_hashtable + hash(sb, hashval);
struct inode *inode;
spin_lock(&inode_hash_lock);
inode = find_inode(sb, head, test, data);
spin_unlock(&inode_hash_lock);
return inode;
}
EXPORT_SYMBOL(ilookup5_nowait);
/**
* ilookup5 - search for an inode in the inode cache
* @sb: super block of file system to search
* @hashval: hash value (usually inode number) to search for
* @test: callback used for comparisons between inodes
* @data: opaque data pointer to pass to @test
*
* Search for the inode specified by @hashval and @data in the inode cache,
* and if the inode is in the cache, return the inode with an incremented
* reference count. Waits on I_NEW before returning the inode.
* returned with an incremented reference count.
*
* This is a generalized version of ilookup() for file systems where the
* inode number is not sufficient for unique identification of an inode.
*
* Note: @test is called with the inode_hash_lock held, so can't sleep.
*/
struct inode *ilookup5(struct super_block *sb, unsigned long hashval,
int (*test)(struct inode *, void *), void *data)
{
struct inode *inode;
again:
inode = ilookup5_nowait(sb, hashval, test, data);
if (inode) {
wait_on_inode(inode);
if (unlikely(inode_unhashed(inode))) {
iput(inode);
goto again;
}
}
return inode;
}
EXPORT_SYMBOL(ilookup5);
/**
* ilookup - search for an inode in the inode cache
* @sb: super block of file system to search
* @ino: inode number to search for
*
* Search for the inode @ino in the inode cache, and if the inode is in the
* cache, the inode is returned with an incremented reference count.
*/
struct inode *ilookup(struct super_block *sb, unsigned long ino)
{
struct hlist_head *head = inode_hashtable + hash(sb, ino);
struct inode *inode;
again:
spin_lock(&inode_hash_lock);
inode = find_inode_fast(sb, head, ino);
spin_unlock(&inode_hash_lock);
if (inode) {
wait_on_inode(inode);
if (unlikely(inode_unhashed(inode))) {
iput(inode);
goto again;
}
}
return inode;
}
EXPORT_SYMBOL(ilookup);
/**
* find_inode_nowait - find an inode in the inode cache
* @sb: super block of file system to search
* @hashval: hash value (usually inode number) to search for
* @match: callback used for comparisons between inodes
* @data: opaque data pointer to pass to @match
*
* Search for the inode specified by @hashval and @data in the inode
* cache, where the helper function @match will return 0 if the inode
* does not match, 1 if the inode does match, and -1 if the search
* should be stopped. The @match function must be responsible for
* taking the i_lock spin_lock and checking i_state for an inode being
* freed or being initialized, and incrementing the reference count
* before returning 1. It also must not sleep, since it is called with
* the inode_hash_lock spinlock held.
*
* This is a even more generalized version of ilookup5() when the
* function must never block --- find_inode() can block in
* __wait_on_freeing_inode() --- or when the caller can not increment
* the reference count because the resulting iput() might cause an
* inode eviction. The tradeoff is that the @match funtion must be
* very carefully implemented.
*/
struct inode *find_inode_nowait(struct super_block *sb,
unsigned long hashval,
int (*match)(struct inode *, unsigned long,
void *),
void *data)
{
struct hlist_head *head = inode_hashtable + hash(sb, hashval);
struct inode *inode, *ret_inode = NULL;
int mval;
spin_lock(&inode_hash_lock);
hlist_for_each_entry(inode, head, i_hash) {
if (inode->i_sb != sb)
continue;
mval = match(inode, hashval, data);
if (mval == 0)
continue;
if (mval == 1)
ret_inode = inode;
goto out;
}
out:
spin_unlock(&inode_hash_lock);
return ret_inode;
}
EXPORT_SYMBOL(find_inode_nowait);
int insert_inode_locked(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
ino_t ino = inode->i_ino;
struct hlist_head *head = inode_hashtable + hash(sb, ino);
while (1) {
struct inode *old = NULL;
spin_lock(&inode_hash_lock);
hlist_for_each_entry(old, head, i_hash) {
if (old->i_ino != ino)
continue;
if (old->i_sb != sb)
continue;
spin_lock(&old->i_lock);
if (old->i_state & (I_FREEING|I_WILL_FREE)) {
spin_unlock(&old->i_lock);
continue;
}
break;
}
if (likely(!old)) {
spin_lock(&inode->i_lock);
inode->i_state |= I_NEW;
hlist_add_head(&inode->i_hash, head);
spin_unlock(&inode->i_lock);
spin_unlock(&inode_hash_lock);
return 0;
}
__iget(old);
spin_unlock(&old->i_lock);
spin_unlock(&inode_hash_lock);
wait_on_inode(old);
if (unlikely(!inode_unhashed(old))) {
iput(old);
return -EBUSY;
}
iput(old);
}
}
EXPORT_SYMBOL(insert_inode_locked);
int insert_inode_locked4(struct inode *inode, unsigned long hashval,
int (*test)(struct inode *, void *), void *data)
{
struct inode *old = inode_insert5(inode, hashval, test, NULL, data);
if (old != inode) {
iput(old);
return -EBUSY;
}
return 0;
}
EXPORT_SYMBOL(insert_inode_locked4);
int generic_delete_inode(struct inode *inode)
{
return 1;
}
EXPORT_SYMBOL(generic_delete_inode);
/*
* Called when we're dropping the last reference
* to an inode.
*
* Call the FS "drop_inode()" function, defaulting to
* the legacy UNIX filesystem behaviour. If it tells
* us to evict inode, do so. Otherwise, retain inode
* in cache if fs is alive, sync and evict if fs is
* shutting down.
*/
static void iput_final(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
const struct super_operations *op = inode->i_sb->s_op;
int drop;
WARN_ON(inode->i_state & I_NEW);
if (op->drop_inode)
drop = op->drop_inode(inode);
else
drop = generic_drop_inode(inode);
if (!drop && (sb->s_flags & SB_ACTIVE)) {
inode_add_lru(inode);
spin_unlock(&inode->i_lock);
return;
}
if (!drop) {
inode->i_state |= I_WILL_FREE;
spin_unlock(&inode->i_lock);
write_inode_now(inode, 1);
spin_lock(&inode->i_lock);
WARN_ON(inode->i_state & I_NEW);
inode->i_state &= ~I_WILL_FREE;
}
inode->i_state |= I_FREEING;
if (!list_empty(&inode->i_lru))
inode_lru_list_del(inode);
spin_unlock(&inode->i_lock);
evict(inode);
}
/**
* iput - put an inode
* @inode: inode to put
*
* Puts an inode, dropping its usage count. If the inode use count hits
* zero, the inode is then freed and may also be destroyed.
*
* Consequently, iput() can sleep.
*/
void iput(struct inode *inode)
{
if (!inode)
return;
BUG_ON(inode->i_state & I_CLEAR);
retry:
if (atomic_dec_and_lock(&inode->i_count, &inode->i_lock)) {
if (inode->i_nlink && (inode->i_state & I_DIRTY_TIME)) {
atomic_inc(&inode->i_count);
spin_unlock(&inode->i_lock);
trace_writeback_lazytime_iput(inode);
mark_inode_dirty_sync(inode);
goto retry;
}
iput_final(inode);
}
}
EXPORT_SYMBOL(iput);
/**
* bmap - find a block number in a file
* @inode: inode of file
* @block: block to find
*
* Returns the block number on the device holding the inode that
* is the disk block number for the block of the file requested.
* That is, asked for block 4 of inode 1 the function will return the
* disk block relative to the disk start that holds that block of the
* file.
*/
sector_t bmap(struct inode *inode, sector_t block)
{
sector_t res = 0;
if (inode->i_mapping->a_ops->bmap)
res = inode->i_mapping->a_ops->bmap(inode->i_mapping, block);
return res;
}
EXPORT_SYMBOL(bmap);
/*
* Update times in overlayed inode from underlying real inode
*/
static void update_ovl_inode_times(struct dentry *dentry, struct inode *inode,
bool rcu)
{
struct dentry *upperdentry;
/*
* Nothing to do if in rcu or if non-overlayfs
*/
if (rcu || likely(!(dentry->d_flags & DCACHE_OP_REAL)))
return;
upperdentry = d_real(dentry, NULL, 0, D_REAL_UPPER);
/*
* If file is on lower then we can't update atime, so no worries about
* stale mtime/ctime.
*/
if (upperdentry) {
struct inode *realinode = d_inode(upperdentry);
if ((!timespec64_equal(&inode->i_mtime, &realinode->i_mtime) ||
!timespec64_equal(&inode->i_ctime, &realinode->i_ctime))) {
inode->i_mtime = realinode->i_mtime;
inode->i_ctime = realinode->i_ctime;
}
}
}
/*
* With relative atime, only update atime if the previous atime is
* earlier than either the ctime or mtime or if at least a day has
* passed since the last atime update.
*/
static int relatime_need_update(const struct path *path, struct inode *inode,
struct timespec now, bool rcu)
{
if (!(path->mnt->mnt_flags & MNT_RELATIME))
return 1;
update_ovl_inode_times(path->dentry, inode, rcu);
/*
* Is mtime younger than atime? If yes, update atime:
*/
if (timespec64_compare(&inode->i_mtime, &inode->i_atime) >= 0)
return 1;
/*
* Is ctime younger than atime? If yes, update atime:
*/
if (timespec64_compare(&inode->i_ctime, &inode->i_atime) >= 0)
return 1;
/*
* Is the previous atime value older than a day? If yes,
* update atime:
*/
if ((long)(now.tv_sec - inode->i_atime.tv_sec) >= 24*60*60)
return 1;
/*
* Good, we can skip the atime update:
*/
return 0;
}
int generic_update_time(struct inode *inode, struct timespec64 *time, int flags)
{
int iflags = I_DIRTY_TIME;
bool dirty = false;
if (flags & S_ATIME)
inode->i_atime = *time;
if (flags & S_VERSION)
dirty = inode_maybe_inc_iversion(inode, false);
if (flags & S_CTIME)
inode->i_ctime = *time;
if (flags & S_MTIME)
inode->i_mtime = *time;
if ((flags & (S_ATIME | S_CTIME | S_MTIME)) &&
!(inode->i_sb->s_flags & SB_LAZYTIME))
dirty = true;
if (dirty)
iflags |= I_DIRTY_SYNC;
__mark_inode_dirty(inode, iflags);
return 0;
}
EXPORT_SYMBOL(generic_update_time);
/*
* This does the actual work of updating an inodes time or version. Must have
* had called mnt_want_write() before calling this.
*/
static int update_time(struct inode *inode, struct timespec64 *time, int flags)
{
int (*update_time)(struct inode *, struct timespec64 *, int);
update_time = inode->i_op->update_time ? inode->i_op->update_time :
generic_update_time;
return update_time(inode, time, flags);
}
/**
* touch_atime - update the access time
* @path: the &struct path to update
* @inode: inode to update
*
* Update the accessed time on an inode and mark it for writeback.
* This function automatically handles read only file systems and media,
* as well as the "noatime" flag and inode specific "noatime" markers.
*/
bool __atime_needs_update(const struct path *path, struct inode *inode,
bool rcu)
{
struct vfsmount *mnt = path->mnt;
struct timespec64 now;
if (inode->i_flags & S_NOATIME)
return false;
/* Atime updates will likely cause i_uid and i_gid to be written
* back improprely if their true value is unknown to the vfs.
*/
if (HAS_UNMAPPED_ID(inode))
return false;
if (IS_NOATIME(inode))
return false;
if ((inode->i_sb->s_flags & SB_NODIRATIME) && S_ISDIR(inode->i_mode))
return false;
if (mnt->mnt_flags & MNT_NOATIME)
return false;
if ((mnt->mnt_flags & MNT_NODIRATIME) && S_ISDIR(inode->i_mode))
return false;
now = current_time(inode);
if (!relatime_need_update(path, inode, timespec64_to_timespec(now), rcu))
return false;
if (timespec64_equal(&inode->i_atime, &now))
return false;
return true;
}
void touch_atime(const struct path *path)
{
struct vfsmount *mnt = path->mnt;
struct inode *inode = d_inode(path->dentry);
struct timespec64 now;
if (!__atime_needs_update(path, inode, false))
return;
if (!sb_start_write_trylock(inode->i_sb))
return;
if (__mnt_want_write(mnt) != 0)
goto skip_update;
/*
* File systems can error out when updating inodes if they need to
* allocate new space to modify an inode (such is the case for
* Btrfs), but since we touch atime while walking down the path we
* really don't care if we failed to update the atime of the file,
* so just ignore the return value.
* We may also fail on filesystems that have the ability to make parts
* of the fs read only, e.g. subvolumes in Btrfs.
*/
now = current_time(inode);
update_time(inode, &now, S_ATIME);
__mnt_drop_write(mnt);
skip_update:
sb_end_write(inode->i_sb);
}
EXPORT_SYMBOL(touch_atime);
/*
* The logic we want is
*
* if suid or (sgid and xgrp)
* remove privs
*/
int should_remove_suid(struct dentry *dentry)
{
umode_t mode = d_inode(dentry)->i_mode;
int kill = 0;
/* suid always must be killed */
if (unlikely(mode & S_ISUID))
kill = ATTR_KILL_SUID;
/*
* sgid without any exec bits is just a mandatory locking mark; leave
* it alone. If some exec bits are set, it's a real sgid; kill it.
*/
if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
kill |= ATTR_KILL_SGID;
if (unlikely(kill && !capable(CAP_FSETID) && S_ISREG(mode)))
return kill;
return 0;
}
EXPORT_SYMBOL(should_remove_suid);
/*
* Return mask of changes for notify_change() that need to be done as a
* response to write or truncate. Return 0 if nothing has to be changed.
* Negative value on error (change should be denied).
*/
int dentry_needs_remove_privs(struct dentry *dentry)
{
struct inode *inode = d_inode(dentry);
int mask = 0;
int ret;
if (IS_NOSEC(inode))
return 0;
mask = should_remove_suid(dentry);
ret = security_inode_need_killpriv(dentry);
if (ret < 0)
return ret;
if (ret)
mask |= ATTR_KILL_PRIV;
return mask;
}
static int __remove_privs(struct dentry *dentry, int kill)
{
struct iattr newattrs;
newattrs.ia_valid = ATTR_FORCE | kill;
/*
* Note we call this on write, so notify_change will not
* encounter any conflicting delegations:
*/
return notify_change(dentry, &newattrs, NULL);
}
/*
* Remove special file priviledges (suid, capabilities) when file is written
* to or truncated.
*/
int file_remove_privs(struct file *file)
{
struct dentry *dentry = file_dentry(file);
struct inode *inode = file_inode(file);
int kill;
int error = 0;
/* Fast path for nothing security related */
if (IS_NOSEC(inode))
return 0;
kill = dentry_needs_remove_privs(dentry);
if (kill < 0)
return kill;
if (kill)
error = __remove_privs(dentry, kill);
if (!error)
inode_has_no_xattr(inode);
return error;
}
EXPORT_SYMBOL(file_remove_privs);
/**
* file_update_time - update mtime and ctime time
* @file: file accessed
*
* Update the mtime and ctime members of an inode and mark the inode
* for writeback. Note that this function is meant exclusively for
* usage in the file write path of filesystems, and filesystems may
* choose to explicitly ignore update via this function with the
* S_NOCMTIME inode flag, e.g. for network filesystem where these
* timestamps are handled by the server. This can return an error for
* file systems who need to allocate space in order to update an inode.
*/
int file_update_time(struct file *file)
{
struct inode *inode = file_inode(file);
struct timespec64 now;
int sync_it = 0;
int ret;
/* First try to exhaust all avenues to not sync */
if (IS_NOCMTIME(inode))
return 0;
now = current_time(inode);
if (!timespec64_equal(&inode->i_mtime, &now))
sync_it = S_MTIME;
if (!timespec64_equal(&inode->i_ctime, &now))
sync_it |= S_CTIME;
if (IS_I_VERSION(inode) && inode_iversion_need_inc(inode))
sync_it |= S_VERSION;
if (!sync_it)
return 0;
/* Finally allowed to write? Takes lock. */
if (__mnt_want_write_file(file))
return 0;
ret = update_time(inode, &now, sync_it);
__mnt_drop_write_file(file);
return ret;
}
EXPORT_SYMBOL(file_update_time);
int inode_needs_sync(struct inode *inode)
{
if (IS_SYNC(inode))
return 1;
if (S_ISDIR(inode->i_mode) && IS_DIRSYNC(inode))
return 1;
return 0;
}
EXPORT_SYMBOL(inode_needs_sync);
/*
* If we try to find an inode in the inode hash while it is being
* deleted, we have to wait until the filesystem completes its
* deletion before reporting that it isn't found. This function waits
* until the deletion _might_ have completed. Callers are responsible
* to recheck inode state.
*
* It doesn't matter if I_NEW is not set initially, a call to
* wake_up_bit(&inode->i_state, __I_NEW) after removing from the hash list
* will DTRT.
*/
static void __wait_on_freeing_inode(struct inode *inode)
{
wait_queue_head_t *wq;
DEFINE_WAIT_BIT(wait, &inode->i_state, __I_NEW);
wq = bit_waitqueue(&inode->i_state, __I_NEW);
prepare_to_wait(wq, &wait.wq_entry, TASK_UNINTERRUPTIBLE);
spin_unlock(&inode->i_lock);
spin_unlock(&inode_hash_lock);
schedule();
finish_wait(wq, &wait.wq_entry);
spin_lock(&inode_hash_lock);
}
static __initdata unsigned long ihash_entries;
static int __init set_ihash_entries(char *str)
{
if (!str)
return 0;
ihash_entries = simple_strtoul(str, &str, 0);
return 1;
}
__setup("ihash_entries=", set_ihash_entries);
/*
* Initialize the waitqueues and inode hash table.
*/
void __init inode_init_early(void)
{
/* If hashes are distributed across NUMA nodes, defer
* hash allocation until vmalloc space is available.
*/
if (hashdist)
return;
inode_hashtable =
alloc_large_system_hash("Inode-cache",
sizeof(struct hlist_head),
ihash_entries,
14,
HASH_EARLY | HASH_ZERO,
&i_hash_shift,
&i_hash_mask,
0,
0);
}
void __init inode_init(void)
{
/* inode slab cache */
inode_cachep = kmem_cache_create("inode_cache",
sizeof(struct inode),
0,
(SLAB_RECLAIM_ACCOUNT|SLAB_PANIC|
SLAB_MEM_SPREAD|SLAB_ACCOUNT),
init_once);
/* Hash may have been set up in inode_init_early */
if (!hashdist)
return;
inode_hashtable =
alloc_large_system_hash("Inode-cache",
sizeof(struct hlist_head),
ihash_entries,
14,
HASH_ZERO,
&i_hash_shift,
&i_hash_mask,
0,
0);
}
void init_special_inode(struct inode *inode, umode_t mode, dev_t rdev)
{
inode->i_mode = mode;
if (S_ISCHR(mode)) {
inode->i_fop = &def_chr_fops;
inode->i_rdev = rdev;
} else if (S_ISBLK(mode)) {
inode->i_fop = &def_blk_fops;
inode->i_rdev = rdev;
} else if (S_ISFIFO(mode))
inode->i_fop = &pipefifo_fops;
else if (S_ISSOCK(mode))
; /* leave it no_open_fops */
else
printk(KERN_DEBUG "init_special_inode: bogus i_mode (%o) for"
" inode %s:%lu\n", mode, inode->i_sb->s_id,
inode->i_ino);
}
EXPORT_SYMBOL(init_special_inode);
/**
* inode_init_owner - Init uid,gid,mode for new inode according to posix standards
* @inode: New inode
* @dir: Directory inode
* @mode: mode of the new inode
*/
void inode_init_owner(struct inode *inode, const struct inode *dir,
umode_t mode)
{
inode->i_uid = current_fsuid();
if (dir && dir->i_mode & S_ISGID) {
inode->i_gid = dir->i_gid;
if (S_ISDIR(mode))
mode |= S_ISGID;
} else
inode->i_gid = current_fsgid();
inode->i_mode = mode;
}
EXPORT_SYMBOL(inode_init_owner);
/**
* inode_owner_or_capable - check current task permissions to inode
* @inode: inode being checked
*
* Return true if current either has CAP_FOWNER in a namespace with the
* inode owner uid mapped, or owns the file.
*/
bool inode_owner_or_capable(const struct inode *inode)
{
struct user_namespace *ns;
if (uid_eq(current_fsuid(), inode->i_uid))
return true;
ns = current_user_ns();
if (kuid_has_mapping(ns, inode->i_uid) && ns_capable(ns, CAP_FOWNER))
return true;
return false;
}
EXPORT_SYMBOL(inode_owner_or_capable);
/*
* Direct i/o helper functions
*/
static void __inode_dio_wait(struct inode *inode)
{
wait_queue_head_t *wq = bit_waitqueue(&inode->i_state, __I_DIO_WAKEUP);
DEFINE_WAIT_BIT(q, &inode->i_state, __I_DIO_WAKEUP);
do {
prepare_to_wait(wq, &q.wq_entry, TASK_UNINTERRUPTIBLE);
if (atomic_read(&inode->i_dio_count))
schedule();
} while (atomic_read(&inode->i_dio_count));
finish_wait(wq, &q.wq_entry);
}
/**
* inode_dio_wait - wait for outstanding DIO requests to finish
* @inode: inode to wait for
*
* Waits for all pending direct I/O requests to finish so that we can
* proceed with a truncate or equivalent operation.
*
* Must be called under a lock that serializes taking new references
* to i_dio_count, usually by inode->i_mutex.
*/
void inode_dio_wait(struct inode *inode)
{
if (atomic_read(&inode->i_dio_count))
__inode_dio_wait(inode);
}
EXPORT_SYMBOL(inode_dio_wait);
/*
* inode_set_flags - atomically set some inode flags
*
* Note: the caller should be holding i_mutex, or else be sure that
* they have exclusive access to the inode structure (i.e., while the
* inode is being instantiated). The reason for the cmpxchg() loop
* --- which wouldn't be necessary if all code paths which modify
* i_flags actually followed this rule, is that there is at least one
* code path which doesn't today so we use cmpxchg() out of an abundance
* of caution.
*
* In the long run, i_mutex is overkill, and we should probably look
* at using the i_lock spinlock to protect i_flags, and then make sure
* it is so documented in include/linux/fs.h and that all code follows
* the locking convention!!
*/
void inode_set_flags(struct inode *inode, unsigned int flags,
unsigned int mask)
{
unsigned int old_flags, new_flags;
WARN_ON_ONCE(flags & ~mask);
do {
old_flags = READ_ONCE(inode->i_flags);
new_flags = (old_flags & ~mask) | flags;
} while (unlikely(cmpxchg(&inode->i_flags, old_flags,
new_flags) != old_flags));
}
EXPORT_SYMBOL(inode_set_flags);
void inode_nohighmem(struct inode *inode)
{
mapping_set_gfp_mask(inode->i_mapping, GFP_USER);
}
EXPORT_SYMBOL(inode_nohighmem);
/**
* timespec64_trunc - Truncate timespec64 to a granularity
* @t: Timespec64
* @gran: Granularity in ns.
*
* Truncate a timespec64 to a granularity. Always rounds down. gran must
* not be 0 nor greater than a second (NSEC_PER_SEC, or 10^9 ns).
*/
struct timespec64 timespec64_trunc(struct timespec64 t, unsigned gran)
{
/* Avoid division in the common cases 1 ns and 1 s. */
if (gran == 1) {
/* nothing */
} else if (gran == NSEC_PER_SEC) {
t.tv_nsec = 0;
} else if (gran > 1 && gran < NSEC_PER_SEC) {
t.tv_nsec -= t.tv_nsec % gran;
} else {
WARN(1, "illegal file time granularity: %u", gran);
}
return t;
}
EXPORT_SYMBOL(timespec64_trunc);
/**
* current_time - Return FS time
* @inode: inode.
*
* Return the current time truncated to the time granularity supported by
* the fs.
*
* Note that inode and inode->sb cannot be NULL.
* Otherwise, the function warns and returns time without truncation.
*/
struct timespec64 current_time(struct inode *inode)
{
struct timespec64 now = current_kernel_time64();
if (unlikely(!inode->i_sb)) {
WARN(1, "current_time() called with uninitialized super_block in the inode");
return now;
}
return timespec64_trunc(now, inode->i_sb->s_time_gran);
}
EXPORT_SYMBOL(current_time);
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_221_0 |
crossvul-cpp_data_bad_3150_0 | /*
* Copyright (C) 2014-2016 Firejail Authors
*
* This file is part of firejail 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "firejail.h"
#include <sys/mount.h>
#include <linux/limits.h>
#include <glob.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <grp.h>
#include <ftw.h>
static void skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
// zsh
if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) {
// copy skel files
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.zshrc", &s) == 0) {
copy_file("/etc/skel/.zshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.zshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
// csh
else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) {
// copy skel files
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.cshrc", &s) == 0) {
copy_file("/etc/skel/.cshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.cshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
// bash etc.
else {
// copy skel files
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.bashrc", &s) == 0) {
copy_file("/etc/skel/.bashrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.bashrc");
}
free(fname);
}
}
static int store_xauthority(void) {
// put a copy of .Xauthority in XAUTHORITY_FILE
fs_build_mnt_dir();
char *src;
char *dest = RUN_XAUTHORITY_FILE;
// create an empty file
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0600);
fclose(fp);
}
if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Warning: invalid .Xauthority file\n");
return 0;
}
copy_file_as_user(src, dest, getuid(), getgid(), 0600);
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
static int store_asoundrc(void) {
// put a copy of .Xauthority in XAUTHORITY_FILE
fs_build_mnt_dir();
char *src;
char *dest = RUN_ASOUNDRC_FILE;
// create an empty file
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0644);
fclose(fp);
}
if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
// make sure the real path of the file is inside the home directory
/* coverity[toctou] */
char* rp = realpath(src, NULL);
if (!rp) {
fprintf(stderr, "Error: Cannot access %s\n", src);
exit(1);
}
if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n");
exit(1);
}
free(rp);
}
copy_file_as_user(src, dest, getuid(), getgid(), 0644);
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
static void copy_xauthority(void) {
// copy XAUTHORITY_FILE in the new home directory
char *src = RUN_XAUTHORITY_FILE ;
char *dest;
if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
// if destination is a symbolic link, exit the sandbox!!!
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR);
fs_logger2("clone", dest);
// delete the temporary file
unlink(src);
}
static void copy_asoundrc(void) {
// copy XAUTHORITY_FILE in the new home directory
char *src = RUN_ASOUNDRC_FILE ;
char *dest;
if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
// if destination is a symbolic link, exit the sandbox!!!
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR);
fs_logger2("clone", dest);
// delete the temporary file
unlink(src);
}
// private mode (--private=homedir):
// mount homedir on top of /home/user,
// tmpfs on top of /root in nonroot mode,
// set skel files,
// restore .Xauthority
void fs_private_homedir(void) {
char *homedir = cfg.homedir;
char *private_homedir = cfg.home_private;
assert(homedir);
assert(private_homedir);
int xflag = store_xauthority();
int aflag = store_asoundrc();
uid_t u = getuid();
gid_t g = getgid();
struct stat s;
if (stat(homedir, &s) == -1) {
fprintf(stderr, "Error: cannot find user home directory\n");
exit(1);
}
// mount bind private_homedir on top of homedir
if (arg_debug)
printf("Mount-bind %s on top of %s\n", private_homedir, homedir);
if (mount(private_homedir, homedir, NULL, MS_NOSUID | MS_NODEV | MS_BIND | MS_REC, NULL) < 0)
errExit("mount bind");
fs_logger3("mount-bind", private_homedir, cfg.homedir);
fs_logger2("whitelist", cfg.homedir);
// preserve mode and ownership
// if (chown(homedir, s.st_uid, s.st_gid) == -1)
// errExit("mount-bind chown");
// if (chmod(homedir, s.st_mode) == -1)
// errExit("mount-bind chmod");
if (u != 0) {
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting home directory");
fs_logger("tmpfs /root");
}
else {
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
fs_logger("tmpfs /home");
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
// private mode (--private):
// mount tmpfs over /home/user,
// tmpfs on top of /root in nonroot mode,
// set skel files,
// restore .Xauthority
void fs_private(void) {
char *homedir = cfg.homedir;
assert(homedir);
uid_t u = getuid();
gid_t g = getgid();
int xflag = store_xauthority();
int aflag = store_asoundrc();
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
fs_logger("tmpfs /home");
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting root directory");
fs_logger("tmpfs /root");
if (u != 0) {
// create /home/user
if (arg_debug)
printf("Create a new user directory\n");
if (mkdir(homedir, S_IRWXU) == -1) {
if (mkpath_as_root(homedir) == -1)
errExit("mkpath");
if (mkdir(homedir, S_IRWXU) == -1)
errExit("mkdir");
}
if (chown(homedir, u, g) < 0)
errExit("chown");
fs_logger2("mkdir", homedir);
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
// check new private home directory (--private= option) - exit if it fails
void fs_check_private_dir(void) {
EUID_ASSERT();
invalid_filename(cfg.home_private);
// Expand the home directory
char *tmp = expand_home(cfg.home_private, cfg.homedir);
cfg.home_private = realpath(tmp, NULL);
free(tmp);
if (!cfg.home_private
|| !is_dir(cfg.home_private)
|| is_link(cfg.home_private)
|| strstr(cfg.home_private, "..")) {
fprintf(stderr, "Error: invalid private directory\n");
exit(1);
}
// check home directory and chroot home directory have the same owner
struct stat s2;
int rv = stat(cfg.home_private, &s2);
if (rv < 0) {
fprintf(stderr, "Error: cannot find %s directory\n", cfg.home_private);
exit(1);
}
struct stat s1;
rv = stat(cfg.homedir, &s1);
if (rv < 0) {
fprintf(stderr, "Error: cannot find %s directory, full path name required\n", cfg.homedir);
exit(1);
}
if (s1.st_uid != s2.st_uid) {
printf("Error: --private directory should be owned by the current user\n");
exit(1);
}
}
//***********************************************************************************
// --private-home
//***********************************************************************************
#define PRIVATE_COPY_LIMIT (500 * 1024 *1024)
static int size_limit_reached = 0;
static unsigned file_cnt = 0;
static unsigned size_cnt = 0;
static char *check_dir_or_file(const char *name);
int fs_copydir(const char *path, const struct stat *st, int ftype, struct FTW *sftw) {
(void) st;
(void) sftw;
if (size_limit_reached)
return 0;
struct stat s;
char *dest;
if (asprintf(&dest, "%s%s", RUN_HOME_DIR, path + strlen(cfg.homedir)) == -1)
errExit("asprintf");
// don't copy it if we already have the file
if (stat(dest, &s) == 0) {
free(dest);
return 0;
}
// extract mode and ownership
if (stat(path, &s) != 0) {
free(dest);
return 0;
}
// check uid
if (s.st_uid != firejail_uid || s.st_gid != firejail_gid) {
free(dest);
return 0;
}
if ((s.st_size + size_cnt) > PRIVATE_COPY_LIMIT) {
size_limit_reached = 1;
free(dest);
return 0;
}
file_cnt++;
size_cnt += s.st_size;
if(ftype == FTW_F)
copy_file(path, dest, firejail_uid, firejail_gid, s.st_mode);
else if (ftype == FTW_D) {
if (mkdir(dest, s.st_mode) == -1)
errExit("mkdir");
if (chmod(dest, s.st_mode) < 0) {
fprintf(stderr, "Error: cannot change mode for %s\n", path);
exit(1);
}
if (chown(dest, firejail_uid, firejail_gid) < 0) {
fprintf(stderr, "Error: cannot change ownership for %s\n", path);
exit(1);
}
#if 0
struct stat s2;
if (stat(dest, &s2) == 0) {
printf("%s\t", dest);
printf((S_ISDIR(s.st_mode)) ? "d" : "-");
printf((s.st_mode & S_IRUSR) ? "r" : "-");
printf((s.st_mode & S_IWUSR) ? "w" : "-");
printf((s.st_mode & S_IXUSR) ? "x" : "-");
printf((s.st_mode & S_IRGRP) ? "r" : "-");
printf((s.st_mode & S_IWGRP) ? "w" : "-");
printf((s.st_mode & S_IXGRP) ? "x" : "-");
printf((s.st_mode & S_IROTH) ? "r" : "-");
printf((s.st_mode & S_IWOTH) ? "w" : "-");
printf((s.st_mode & S_IXOTH) ? "x" : "-");
printf("\n");
}
#endif
fs_logger2("clone", path);
}
free(dest);
return(0);
}
static void duplicate(char *name) {
char *fname = check_dir_or_file(name);
if (arg_debug)
printf("Private home: duplicating %s\n", fname);
assert(strncmp(fname, cfg.homedir, strlen(cfg.homedir)) == 0);
struct stat s;
if (stat(fname, &s) == -1) {
free(fname);
return;
}
if(nftw(fname, fs_copydir, 1, FTW_PHYS) != 0) {
fprintf(stderr, "Error: unable to copy template dir\n");
exit(1);
}
fs_logger_print(); // save the current log
free(fname);
}
static char *check_dir_or_file(const char *name) {
assert(name);
struct stat s;
// basic checks
invalid_filename(name);
if (arg_debug)
printf("Private home: checking %s\n", name);
// expand home directory
char *fname = expand_home(name, cfg.homedir);
if (!fname) {
fprintf(stderr, "Error: file %s not found.\n", name);
exit(1);
}
// If it doesn't start with '/', it must be relative to homedir
if (fname[0] != '/') {
char* tmp;
if (asprintf(&tmp, "%s/%s", cfg.homedir, fname) == -1)
errExit("asprintf");
free(fname);
fname = tmp;
}
// check the file is in user home directory
char *rname = realpath(fname, NULL);
if (!rname) {
fprintf(stderr, "Error: invalid file %s\n", name);
exit(1);
}
if (strncmp(rname, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: file %s is not in user home directory\n", name);
exit(1);
}
// a full home directory is not allowed
if (strcmp(rname, cfg.homedir) == 0) {
fprintf(stderr, "Error: invalid directory %s\n", rname);
exit(1);
}
// only top files and directories in user home are allowed
char *ptr = rname + strlen(cfg.homedir);
if (*ptr == '\0') {
fprintf(stderr, "Error: invalid file %s\n", name);
exit(1);
}
ptr++;
ptr = strchr(ptr, '/');
if (ptr) {
if (*ptr != '\0') {
fprintf(stderr, "Error: only top files and directories in user home are allowed\n");
exit(1);
}
}
if (stat(fname, &s) == -1) {
fprintf(stderr, "Error: file %s not found.\n", fname);
exit(1);
}
// check uid
uid_t uid = getuid();
gid_t gid = getgid();
if (s.st_uid != uid || s.st_gid != gid) {
fprintf(stderr, "Error: only files or directories created by the current user are allowed.\n");
exit(1);
}
// dir or regular file
if (S_ISDIR(s.st_mode) || S_ISREG(s.st_mode)) {
free(fname);
return rname; // regular exit from the function
}
fprintf(stderr, "Error: invalid file type, %s.\n", fname);
exit(1);
}
// check directory list specified by user (--private-home option) - exit if it fails
void fs_check_home_list(void) {
if (strstr(cfg.home_private_keep, "..")) {
fprintf(stderr, "Error: invalid private-home list\n");
exit(1);
}
char *dlist = strdup(cfg.home_private_keep);
if (!dlist)
errExit("strdup");
char *ptr = strtok(dlist, ",");
char *tmp = check_dir_or_file(ptr);
free(tmp);
while ((ptr = strtok(NULL, ",")) != NULL) {
tmp = check_dir_or_file(ptr);
free(tmp);
}
free(dlist);
}
// private mode (--private-home=list):
// mount homedir on top of /home/user,
// tmpfs on top of /root in nonroot mode,
// tmpfs on top of /tmp in root mode,
// set skel files,
// restore .Xauthority
void fs_private_home_list(void) {
char *homedir = cfg.homedir;
char *private_list = cfg.home_private_keep;
assert(homedir);
assert(private_list);
int xflag = store_xauthority();
int aflag = store_asoundrc();
uid_t u = firejail_uid;
gid_t g = firejail_gid;
struct stat s;
if (stat(homedir, &s) == -1) {
fprintf(stderr, "Error: cannot find user home directory\n");
exit(1);
}
// create /run/firejail/mnt/home directory
fs_build_mnt_dir();
int rv = mkdir(RUN_HOME_DIR, 0755);
if (rv == -1)
errExit("mkdir");
if (chown(RUN_HOME_DIR, u, g) < 0)
errExit("chown");
if (chmod(RUN_HOME_DIR, 0755) < 0)
errExit("chmod");
ASSERT_PERMS(RUN_HOME_DIR, u, g, 0755);
fs_logger_print(); // save the current log
// copy the list of files in the new home directory
// using a new child process without root privileges
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
if (arg_debug)
printf("Copying files in the new home:\n");
// drop privileges
if (setgroups(0, NULL) < 0)
errExit("setgroups");
if (setgid(getgid()) < 0)
errExit("setgid/getgid");
if (setuid(getuid()) < 0)
errExit("setuid/getuid");
// copy the list of files in the new home directory
char *dlist = strdup(cfg.home_private_keep);
if (!dlist)
errExit("strdup");
char *ptr = strtok(dlist, ",");
duplicate(ptr);
while ((ptr = strtok(NULL, ",")) != NULL)
duplicate(ptr);
if (!arg_quiet) {
if (size_limit_reached)
fprintf(stderr, "Warning: private-home copy limit of %u MB reached, not all the files were copied\n",
PRIVATE_COPY_LIMIT / (1024 *1024));
else
printf("Private home: %u files, total size %u bytes\n", file_cnt, size_cnt);
}
fs_logger_print(); // save the current log
free(dlist);
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
if (arg_debug)
printf("Mount-bind %s on top of %s\n", RUN_HOME_DIR, homedir);
if (mount(RUN_HOME_DIR, homedir, NULL, MS_BIND|MS_REC, NULL) < 0)
errExit("mount bind");
if (u != 0) {
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting home directory");
}
else {
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3150_0 |
crossvul-cpp_data_good_4227_0 |
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-features.h>
#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/agent/net-snmp-agent-includes.h>
#include <net-snmp/agent/watcher.h>
#include <net-snmp/agent/agent_callbacks.h>
#include "agent/extend.h"
#include "utilities/execute.h"
#include "struct.h"
#ifndef USING_UCD_SNMP_EXTENSIBLE_MODULE
#include "util_funcs/header_simple_table.h"
#include "mibdefs.h"
#define SHELLCOMMAND 3
#endif
/* This mib is potentially dangerous to turn on by default, since it
* allows arbitrary commands to be set by anyone with SNMP WRITE
* access to the MIB table. If all of your users are "root" level
* users, then it may be safe to turn on. */
#define ENABLE_EXTEND_WRITE_ACCESS 0
netsnmp_feature_require(extract_table_row_data);
netsnmp_feature_require(table_data_delete_table);
#ifndef NETSNMP_NO_WRITE_SUPPORT
netsnmp_feature_require(insert_table_row);
#endif /* NETSNMP_NO_WRITE_SUPPORT */
oid ns_extend_oid[] = { 1, 3, 6, 1, 4, 1, 8072, 1, 3, 2 };
typedef struct extend_registration_block_s {
netsnmp_table_data *dinfo;
oid *root_oid;
size_t oid_len;
long num_entries;
netsnmp_extend *ehead;
netsnmp_handler_registration *reg[4];
struct extend_registration_block_s *next;
} extend_registration_block;
extend_registration_block *ereg_head = NULL;
#ifndef USING_UCD_SNMP_EXTENSIBLE_MODULE
typedef struct netsnmp_old_extend_s {
unsigned int idx;
netsnmp_extend *exec_entry;
netsnmp_extend *efix_entry;
} netsnmp_old_extend;
unsigned int num_compatability_entries = 0;
unsigned int max_compatability_entries = 50;
netsnmp_old_extend *compatability_entries;
char *cmdlinebuf;
size_t cmdlinesize;
WriteMethod fixExec2Error;
FindVarMethod var_extensible_old;
oid old_extensible_variables_oid[] = { NETSNMP_UCDAVIS_MIB, NETSNMP_SHELLMIBNUM, 1 };
#ifndef NETSNMP_NO_WRITE_SUPPORT
struct variable2 old_extensible_variables[] = {
{MIBINDEX, ASN_INTEGER, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {MIBINDEX}},
{ERRORNAME, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORNAME}},
{SHELLCOMMAND, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {SHELLCOMMAND}},
{ERRORFLAG, ASN_INTEGER, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORFLAG}},
{ERRORMSG, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORMSG}},
{ERRORFIX, ASN_INTEGER, NETSNMP_OLDAPI_RWRITE,
var_extensible_old, 1, {ERRORFIX}},
{ERRORFIXCMD, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORFIXCMD}}
};
#else /* !NETSNMP_NO_WRITE_SUPPORT */
struct variable2 old_extensible_variables[] = {
{MIBINDEX, ASN_INTEGER, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {MIBINDEX}},
{ERRORNAME, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORNAME}},
{SHELLCOMMAND, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {SHELLCOMMAND}},
{ERRORFLAG, ASN_INTEGER, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORFLAG}},
{ERRORMSG, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORMSG}},
{ERRORFIX, ASN_INTEGER, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORFIX}},
{ERRORFIXCMD, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORFIXCMD}}
};
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
#endif
/*************************
*
* Main initialisation routine
*
*************************/
extend_registration_block *
_find_extension_block( oid *name, size_t name_len )
{
extend_registration_block *eptr;
size_t len;
for ( eptr=ereg_head; eptr; eptr=eptr->next ) {
len = SNMP_MIN(name_len, eptr->oid_len);
if (!snmp_oid_compare( name, len, eptr->root_oid, eptr->oid_len))
return eptr;
}
return NULL;
}
extend_registration_block *
_register_extend( oid *base, size_t len )
{
extend_registration_block *eptr;
oid oid_buf[MAX_OID_LEN];
netsnmp_table_data *dinfo;
netsnmp_table_registration_info *tinfo;
netsnmp_watcher_info *winfo;
netsnmp_handler_registration *reg = NULL;
int rc;
for ( eptr=ereg_head; eptr; eptr=eptr->next ) {
if (!snmp_oid_compare( base, len, eptr->root_oid, eptr->oid_len))
return eptr;
}
if (!eptr) {
eptr = SNMP_MALLOC_TYPEDEF( extend_registration_block );
if (!eptr)
return NULL;
eptr->root_oid = snmp_duplicate_objid( base, len );
eptr->oid_len = len;
eptr->num_entries = 0;
eptr->ehead = NULL;
eptr->dinfo = netsnmp_create_table_data( "nsExtendTable" );
eptr->next = ereg_head;
ereg_head = eptr;
}
dinfo = eptr->dinfo;
memcpy( oid_buf, base, len*sizeof(oid) );
/*
* Register the configuration table
*/
tinfo = SNMP_MALLOC_TYPEDEF( netsnmp_table_registration_info );
netsnmp_table_helper_add_indexes( tinfo, ASN_OCTET_STR, 0 );
tinfo->min_column = COLUMN_EXTCFG_FIRST_COLUMN;
tinfo->max_column = COLUMN_EXTCFG_LAST_COLUMN;
oid_buf[len] = 2;
#ifndef NETSNMP_NO_WRITE_SUPPORT
reg = netsnmp_create_handler_registration(
"nsExtendConfigTable", handle_nsExtendConfigTable,
oid_buf, len+1, HANDLER_CAN_RWRITE);
#else /* !NETSNMP_NO_WRITE_SUPPORT */
reg = netsnmp_create_handler_registration(
"nsExtendConfigTable", handle_nsExtendConfigTable,
oid_buf, len+1, HANDLER_CAN_RONLY);
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
rc = netsnmp_register_table_data( reg, dinfo, tinfo );
if (rc != SNMPERR_SUCCESS) {
goto bail;
}
netsnmp_handler_owns_table_info(reg->handler->next);
eptr->reg[0] = reg;
/*
* Register the main output table
* using the same table_data handle.
* This is sufficient to link the two tables,
* and implement the AUGMENTS behaviour
*/
tinfo = SNMP_MALLOC_TYPEDEF( netsnmp_table_registration_info );
netsnmp_table_helper_add_indexes( tinfo, ASN_OCTET_STR, 0 );
tinfo->min_column = COLUMN_EXTOUT1_FIRST_COLUMN;
tinfo->max_column = COLUMN_EXTOUT1_LAST_COLUMN;
oid_buf[len] = 3;
reg = netsnmp_create_handler_registration(
"nsExtendOut1Table", handle_nsExtendOutput1Table,
oid_buf, len+1, HANDLER_CAN_RONLY);
rc = netsnmp_register_table_data( reg, dinfo, tinfo );
if (rc != SNMPERR_SUCCESS)
goto bail;
netsnmp_handler_owns_table_info(reg->handler->next);
eptr->reg[1] = reg;
/*
* Register the multi-line output table
* using a simple table helper.
* This handles extracting the indexes from
* the request OID, but leaves most of
* the work to our handler routine.
* Still, it was nice while it lasted...
*/
tinfo = SNMP_MALLOC_TYPEDEF( netsnmp_table_registration_info );
netsnmp_table_helper_add_indexes( tinfo, ASN_OCTET_STR, ASN_INTEGER, 0 );
tinfo->min_column = COLUMN_EXTOUT2_FIRST_COLUMN;
tinfo->max_column = COLUMN_EXTOUT2_LAST_COLUMN;
oid_buf[len] = 4;
reg = netsnmp_create_handler_registration(
"nsExtendOut2Table", handle_nsExtendOutput2Table,
oid_buf, len+1, HANDLER_CAN_RONLY);
rc = netsnmp_register_table( reg, tinfo );
if (rc != SNMPERR_SUCCESS)
goto bail;
netsnmp_handler_owns_table_info(reg->handler->next);
eptr->reg[2] = reg;
/*
* Register a watched scalar to keep track of the number of entries
*/
oid_buf[len] = 1;
reg = netsnmp_create_handler_registration(
"nsExtendNumEntries", NULL,
oid_buf, len+1, HANDLER_CAN_RONLY);
winfo = netsnmp_create_watcher_info(
&(eptr->num_entries), sizeof(eptr->num_entries),
ASN_INTEGER, WATCHER_FIXED_SIZE);
rc = netsnmp_register_watched_scalar2( reg, winfo );
if (rc != SNMPERR_SUCCESS)
goto bail;
eptr->reg[3] = reg;
return eptr;
bail:
if (eptr->reg[3])
netsnmp_unregister_handler(eptr->reg[3]);
if (eptr->reg[2])
netsnmp_unregister_handler(eptr->reg[2]);
if (eptr->reg[1])
netsnmp_unregister_handler(eptr->reg[1]);
if (eptr->reg[0])
netsnmp_unregister_handler(eptr->reg[0]);
return NULL;
}
static void
_unregister_extend(extend_registration_block *eptr)
{
extend_registration_block *prev;
netsnmp_assert(eptr);
for (prev = ereg_head; prev && prev->next != eptr; prev = prev->next)
;
if (prev) {
netsnmp_assert(eptr == prev->next);
prev->next = eptr->next;
} else {
netsnmp_assert(eptr == ereg_head);
ereg_head = eptr->next;
}
netsnmp_table_data_delete_table(eptr->dinfo);
free(eptr->root_oid);
free(eptr);
}
int
extend_clear_callback(int majorID, int minorID,
void *serverarg, void *clientarg)
{
extend_registration_block *eptr, *enext = NULL;
for ( eptr=ereg_head; eptr; eptr=enext ) {
enext=eptr->next;
netsnmp_unregister_handler( eptr->reg[0] );
netsnmp_unregister_handler( eptr->reg[1] );
netsnmp_unregister_handler( eptr->reg[2] );
netsnmp_unregister_handler( eptr->reg[3] );
SNMP_FREE(eptr);
}
ereg_head = NULL;
return 0;
}
void init_extend( void )
{
snmpd_register_config_handler("extend", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("extend-sh", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("extendfix", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("exec2", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("sh2", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("execFix2", extend_parse_config, NULL, NULL);
(void)_register_extend( ns_extend_oid, OID_LENGTH(ns_extend_oid));
#ifndef USING_UCD_SNMP_EXTENSIBLE_MODULE
snmpd_register_config_handler("exec", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("sh", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("execFix", extend_parse_config, NULL, NULL);
compatability_entries = (netsnmp_old_extend *)
calloc( max_compatability_entries, sizeof(netsnmp_old_extend));
REGISTER_MIB("ucd-extensible", old_extensible_variables,
variable2, old_extensible_variables_oid);
#endif
snmp_register_callback(SNMP_CALLBACK_APPLICATION,
SNMPD_CALLBACK_PRE_UPDATE_CONFIG,
extend_clear_callback, NULL);
}
void
shutdown_extend(void)
{
#ifndef USING_UCD_SNMP_EXTENSIBLE_MODULE
free(compatability_entries);
compatability_entries = NULL;
#endif
while (ereg_head)
_unregister_extend(ereg_head);
}
/*************************
*
* Cached-data hooks
* see 'cache_handler' helper
*
*************************/
int
extend_load_cache(netsnmp_cache *cache, void *magic)
{
#ifndef USING_UTILITIES_EXECUTE_MODULE
NETSNMP_LOGONCE((LOG_WARNING,"support for run_exec_command not available\n"));
return -1;
#else
int out_len = 1024*100;
char out_buf[ 1024*100 ];
int cmd_len = 255*2 + 2; /* 2 * DisplayStrings */
char cmd_buf[ 255*2 + 2 ];
int ret;
char *cp;
char *line_buf[ 1024 ];
netsnmp_extend *extension = (netsnmp_extend *)magic;
if (!magic)
return -1;
DEBUGMSGTL(( "nsExtendTable:cache", "load %s", extension->token ));
if ( extension->args )
snprintf( cmd_buf, cmd_len, "%s %s", extension->command, extension->args );
else
snprintf( cmd_buf, cmd_len, "%s", extension->command );
if ( extension->flags & NS_EXTEND_FLAGS_SHELL )
ret = run_shell_command( cmd_buf, extension->input, out_buf, &out_len);
else
ret = run_exec_command( cmd_buf, extension->input, out_buf, &out_len);
DEBUGMSG(( "nsExtendTable:cache", ": %s : %d\n", cmd_buf, ret));
if (ret >= 0) {
if (out_buf[ out_len-1 ] == '\n')
out_buf[ --out_len ] = '\0'; /* Stomp on trailing newline */
extension->output = strdup( out_buf );
extension->out_len = out_len;
/*
* Now we need to pick the output apart into separate lines.
* Start by counting how many lines we've got, and keeping
* track of where each line starts in a static buffer
*/
extension->numlines = 1;
line_buf[ 0 ] = extension->output;
for (cp=extension->output; *cp; cp++) {
if (*cp == '\n') {
line_buf[ extension->numlines++ ] = cp+1;
}
}
if ( extension->numlines > 1 ) {
extension->lines = (char**)calloc( sizeof(char *), extension->numlines );
memcpy( extension->lines, line_buf,
sizeof(char *) * extension->numlines );
} else {
extension->lines = &extension->output;
}
}
extension->result = ret;
return ret;
#endif /* !defined(USING_UTILITIES_EXECUTE_MODULE) */
}
void
extend_free_cache(netsnmp_cache *cache, void *magic)
{
netsnmp_extend *extension = (netsnmp_extend *)magic;
if (!magic)
return;
DEBUGMSGTL(( "nsExtendTable:cache", "free %s\n", extension->token ));
if (extension->output) {
SNMP_FREE(extension->output);
extension->output = NULL;
}
if ( extension->numlines > 1 ) {
SNMP_FREE(extension->lines);
}
extension->lines = NULL;
extension->out_len = 0;
extension->numlines = 0;
}
/*************************
*
* Utility routines for setting up a new entry
* (either via SET requests, or the config file)
*
*************************/
void
_free_extension( netsnmp_extend *extension, extend_registration_block *ereg )
{
netsnmp_extend *eptr = NULL;
netsnmp_extend *eprev = NULL;
if (!extension)
return;
if (ereg) {
/* Unlink from 'ehead' list */
for (eptr=ereg->ehead; eptr; eptr=eptr->next) {
if (eptr == extension)
break;
eprev = eptr;
}
if (!eptr) {
snmp_log(LOG_ERR,
"extend: fell off end of list before finding extension\n");
return;
}
if (eprev)
eprev->next = eptr->next;
else
ereg->ehead = eptr->next;
netsnmp_table_data_remove_and_delete_row( ereg->dinfo, extension->row);
}
SNMP_FREE( extension->token );
SNMP_FREE( extension->cache );
SNMP_FREE( extension->command );
SNMP_FREE( extension->args );
SNMP_FREE( extension->input );
SNMP_FREE( extension );
return;
}
netsnmp_extend *
_new_extension( char *exec_name, int exec_flags, extend_registration_block *ereg )
{
netsnmp_extend *extension;
netsnmp_table_row *row;
netsnmp_extend *eptr1, *eptr2;
netsnmp_table_data *dinfo = ereg->dinfo;
if (!exec_name)
return NULL;
extension = SNMP_MALLOC_TYPEDEF( netsnmp_extend );
if (!extension)
return NULL;
extension->token = strdup( exec_name );
extension->flags = exec_flags;
extension->cache = netsnmp_cache_create( 0, extend_load_cache,
extend_free_cache, NULL, 0 );
if (extension->cache)
extension->cache->magic = extension;
row = netsnmp_create_table_data_row();
if (!row || !extension->cache) {
_free_extension( extension, ereg );
SNMP_FREE( row );
return NULL;
}
row->data = (void *)extension;
extension->row = row;
netsnmp_table_row_add_index( row, ASN_OCTET_STR,
exec_name, strlen(exec_name));
if ( netsnmp_table_data_add_row( dinfo, row) != SNMPERR_SUCCESS ) {
/* _free_extension( extension, ereg ); */
SNMP_FREE( extension ); /* Probably not sufficient */
SNMP_FREE( row );
return NULL;
}
ereg->num_entries++;
/*
* Now add this structure to a private linked list.
* We don't need this for the main tables - the
* 'table_data' helper will take care of those.
* But it's probably easier to handle the multi-line
* output table ourselves, for which we need access
* to the underlying data.
* So we'll keep a list internally as well.
*/
for ( eptr1 = ereg->ehead, eptr2 = NULL;
eptr1;
eptr2 = eptr1, eptr1 = eptr1->next ) {
if (strlen( eptr1->token ) > strlen( exec_name ))
break;
if (strlen( eptr1->token ) == strlen( exec_name ) &&
strcmp( eptr1->token, exec_name ) > 0 )
break;
}
if ( eptr2 )
eptr2->next = extension;
else
ereg->ehead = extension;
extension->next = eptr1;
return extension;
}
void
extend_parse_config(const char *token, char *cptr)
{
netsnmp_extend *extension;
char exec_name[STRMAX];
char exec_name2[STRMAX]; /* For use with UCD execFix directive */
char exec_command[STRMAX];
oid oid_buf[MAX_OID_LEN];
size_t oid_len;
extend_registration_block *eptr;
int flags;
int cache_timeout = 0;
int exec_type = NS_EXTEND_ETYPE_EXEC;
cptr = copy_nword(cptr, exec_name, sizeof(exec_name));
if (strcmp(exec_name, "-cacheTime") == 0) {
char cache_timeout_str[32];
cptr = copy_nword(cptr, cache_timeout_str, sizeof(cache_timeout_str));
/* If atoi can't do the conversion, it returns 0 */
cache_timeout = atoi(cache_timeout_str);
cptr = copy_nword(cptr, exec_name, sizeof(exec_name));
}
if (strcmp(exec_name, "-execType") == 0) {
char exec_type_str[16];
cptr = copy_nword(cptr, exec_type_str, sizeof(exec_type_str));
if (strcmp(exec_type_str, "sh") == 0)
exec_type = NS_EXTEND_ETYPE_SHELL;
else
exec_type = NS_EXTEND_ETYPE_EXEC;
cptr = copy_nword(cptr, exec_name, sizeof(exec_name));
}
if ( *exec_name == '.' ) {
oid_len = MAX_OID_LEN - 2;
if (0 == read_objid( exec_name, oid_buf, &oid_len )) {
config_perror("ERROR: Unrecognised OID" );
return;
}
cptr = copy_nword(cptr, exec_name, sizeof(exec_name));
if (!strcmp( token, "sh" ) ||
!strcmp( token, "exec" )) {
config_perror("ERROR: This output format has been deprecated - Please use the 'extend' directive instead" );
return;
}
} else {
memcpy( oid_buf, ns_extend_oid, sizeof(ns_extend_oid));
oid_len = OID_LENGTH(ns_extend_oid);
}
cptr = copy_nword(cptr, exec_command, sizeof(exec_command));
/* XXX - check 'exec_command' exists & is executable */
flags = (NS_EXTEND_FLAGS_ACTIVE | NS_EXTEND_FLAGS_CONFIG);
if (!strcmp( token, "sh" ) ||
!strcmp( token, "extend-sh" ) ||
!strcmp( token, "sh2") ||
exec_type == NS_EXTEND_ETYPE_SHELL)
flags |= NS_EXTEND_FLAGS_SHELL;
if (!strcmp( token, "execFix" ) ||
!strcmp( token, "extendfix" ) ||
!strcmp( token, "execFix2" )) {
strcpy( exec_name2, exec_name );
strcat( exec_name, "Fix" );
flags |= NS_EXTEND_FLAGS_WRITEABLE;
/* XXX - Check for shell... */
}
eptr = _register_extend( oid_buf, oid_len );
if (!eptr) {
snmp_log(LOG_ERR, "Failed to register extend entry '%s' - possibly duplicate name.\n", exec_name );
return;
}
extension = _new_extension( exec_name, flags, eptr );
if (extension) {
extension->command = strdup( exec_command );
if (cptr)
extension->args = strdup( cptr );
if (cache_timeout != 0)
extension->cache->timeout = cache_timeout;
} else {
snmp_log(LOG_ERR, "Failed to register extend entry '%s' - possibly duplicate name.\n", exec_name );
return;
}
#ifndef USING_UCD_SNMP_EXTENSIBLE_MODULE
/*
* Compatability with the UCD extTable
*/
if (!strcmp( token, "execFix" )) {
int i;
for ( i=0; i < num_compatability_entries; i++ ) {
if (!strcmp( exec_name2,
compatability_entries[i].exec_entry->token))
break;
}
if ( i == num_compatability_entries )
config_perror("No matching exec entry" );
else
compatability_entries[ i ].efix_entry = extension;
} else if (!strcmp( token, "sh" ) ||
!strcmp( token, "exec" )) {
if ( num_compatability_entries == max_compatability_entries ) {
/* XXX - should really use dynamic allocation */
netsnmp_old_extend *new_compatability_entries;
new_compatability_entries = realloc(compatability_entries,
max_compatability_entries*2*sizeof(netsnmp_old_extend));
if (!new_compatability_entries)
config_perror("No further UCD-compatible entries" );
else {
memset(new_compatability_entries+num_compatability_entries, 0,
sizeof(netsnmp_old_extend)*max_compatability_entries);
max_compatability_entries *= 2;
compatability_entries = new_compatability_entries;
}
}
if (num_compatability_entries != max_compatability_entries)
compatability_entries[
num_compatability_entries++ ].exec_entry = extension;
}
#endif
}
/*************************
*
* Main table handlers
* Most of the work is handled
* by the 'table_data' helper.
*
*************************/
int
handle_nsExtendConfigTable(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
{
netsnmp_request_info *request;
netsnmp_table_request_info *table_info;
netsnmp_extend *extension;
extend_registration_block *eptr;
int i;
int need_to_validate = 0;
for ( request=requests; request; request=request->next ) {
if (request->processed)
continue;
table_info = netsnmp_extract_table_info( request );
extension = (netsnmp_extend*)netsnmp_extract_table_row_data( request );
DEBUGMSGTL(( "nsExtendTable:config", "varbind: "));
DEBUGMSGOID(("nsExtendTable:config", request->requestvb->name,
request->requestvb->name_length));
DEBUGMSG(( "nsExtendTable:config", " (%s)\n",
se_find_label_in_slist("agent_mode", reqinfo->mode)));
switch (reqinfo->mode) {
case MODE_GET:
switch (table_info->colnum) {
case COLUMN_EXTCFG_COMMAND:
snmp_set_var_typed_value(
request->requestvb, ASN_OCTET_STR,
extension->command,
(extension->command)?strlen(extension->command):0);
break;
case COLUMN_EXTCFG_ARGS:
snmp_set_var_typed_value(
request->requestvb, ASN_OCTET_STR,
extension->args,
(extension->args)?strlen(extension->args):0);
break;
case COLUMN_EXTCFG_INPUT:
snmp_set_var_typed_value(
request->requestvb, ASN_OCTET_STR,
extension->input,
(extension->input)?strlen(extension->input):0);
break;
case COLUMN_EXTCFG_CACHETIME:
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&extension->cache->timeout, sizeof(int));
break;
case COLUMN_EXTCFG_EXECTYPE:
i = ((extension->flags & NS_EXTEND_FLAGS_SHELL) ?
NS_EXTEND_ETYPE_SHELL :
NS_EXTEND_ETYPE_EXEC);
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&i, sizeof(i));
break;
case COLUMN_EXTCFG_RUNTYPE:
i = ((extension->flags & NS_EXTEND_FLAGS_WRITEABLE) ?
NS_EXTEND_RTYPE_RWRITE :
NS_EXTEND_RTYPE_RONLY);
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&i, sizeof(i));
break;
case COLUMN_EXTCFG_STORAGE:
i = ((extension->flags & NS_EXTEND_FLAGS_CONFIG) ?
ST_PERMANENT : ST_VOLATILE);
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&i, sizeof(i));
break;
case COLUMN_EXTCFG_STATUS:
i = ((extension->flags & NS_EXTEND_FLAGS_ACTIVE) ?
RS_ACTIVE :
RS_NOTINSERVICE);
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&i, sizeof(i));
break;
default:
netsnmp_set_request_error(reqinfo, request, SNMP_NOSUCHOBJECT);
continue;
}
break;
/**********
*
* Start of SET handling
*
* All config objects are potentially writable except
* nsExtendStorage which is fixed as either 'permanent'
* (if read from a config file) or 'volatile' (if set via SNMP)
* The string-based settings of a 'permanent' entry cannot
* be changed - neither can the execution or run type.
* Such entries can be (temporarily) marked as inactive,
* and the cache timeout adjusted, but these changes are
* not persistent.
*
**********/
#if !defined(NETSNMP_NO_WRITE_SUPPORT) && ENABLE_EXTEND_WRITE_ACCESS
case MODE_SET_RESERVE1:
/*
* Validate the new assignments
*/
switch (table_info->colnum) {
case COLUMN_EXTCFG_COMMAND:
if (request->requestvb->type != ASN_OCTET_STR) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGTYPE);
return SNMP_ERR_WRONGTYPE;
}
/*
* Must have a full path to the command
* XXX - Assumes Unix-style paths
*/
if (request->requestvb->val_len == 0 ||
request->requestvb->val.string[0] != '/') {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGVALUE);
return SNMP_ERR_WRONGVALUE;
}
/*
* XXX - need to check this file exists
* (and is executable)
*/
if (extension && extension->flags & NS_EXTEND_FLAGS_CONFIG) {
/*
* config entries are "permanent" so can't be changed
*/
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_NOTWRITABLE);
return SNMP_ERR_NOTWRITABLE;
}
break;
case COLUMN_EXTCFG_ARGS:
case COLUMN_EXTCFG_INPUT:
if (request->requestvb->type != ASN_OCTET_STR) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGTYPE);
return SNMP_ERR_WRONGTYPE;
}
if (extension && extension->flags & NS_EXTEND_FLAGS_CONFIG) {
/*
* config entries are "permanent" so can't be changed
*/
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_NOTWRITABLE);
return SNMP_ERR_NOTWRITABLE;
}
break;
case COLUMN_EXTCFG_CACHETIME:
if (request->requestvb->type != ASN_INTEGER) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGTYPE);
return SNMP_ERR_WRONGTYPE;
}
i = *request->requestvb->val.integer;
/*
* -1 is a special value indicating "don't cache"
* [[ XXX - should this be 0 ?? ]]
* Otherwise, cache times must be non-negative
*/
if (i < -1 ) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGVALUE);
return SNMP_ERR_WRONGVALUE;
}
break;
case COLUMN_EXTCFG_EXECTYPE:
if (request->requestvb->type != ASN_INTEGER) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGTYPE);
return SNMP_ERR_WRONGTYPE;
}
i = *request->requestvb->val.integer;
if (i<1 || i>2) { /* 'exec(1)' or 'shell(2)' only */
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGVALUE);
return SNMP_ERR_WRONGVALUE;
}
if (extension && extension->flags & NS_EXTEND_FLAGS_CONFIG) {
/*
* config entries are "permanent" so can't be changed
*/
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_NOTWRITABLE);
return SNMP_ERR_NOTWRITABLE;
}
break;
case COLUMN_EXTCFG_RUNTYPE:
if (request->requestvb->type != ASN_INTEGER) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGTYPE);
return SNMP_ERR_WRONGTYPE;
}
/*
* 'run-on-read(1)', 'run-on-set(2)'
* or 'run-command(3)' only
*/
i = *request->requestvb->val.integer;
if (i<1 || i>3) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGVALUE);
return SNMP_ERR_WRONGVALUE;
}
/*
* 'run-command(3)' can only be used with
* a pre-existing 'run-on-set(2)' entry.
*/
if (i==3 && !(extension && (extension->flags & NS_EXTEND_FLAGS_WRITEABLE))) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_INCONSISTENTVALUE);
return SNMP_ERR_INCONSISTENTVALUE;
}
/*
* 'run-command(3)' is the only valid assignment
* for permanent (i.e. config) entries
*/
if ((extension && extension->flags & NS_EXTEND_FLAGS_CONFIG)
&& i!=3 ) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_INCONSISTENTVALUE);
return SNMP_ERR_INCONSISTENTVALUE;
}
break;
case COLUMN_EXTCFG_STATUS:
if (request->requestvb->type != ASN_INTEGER) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGTYPE);
return SNMP_ERR_WRONGTYPE;
}
i = *request->requestvb->val.integer;
switch (i) {
case RS_ACTIVE:
case RS_NOTINSERVICE:
if (!extension) {
/* Must be used with existing rows */
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_INCONSISTENTVALUE);
return SNMP_ERR_INCONSISTENTVALUE;
}
break; /* OK */
case RS_CREATEANDGO:
case RS_CREATEANDWAIT:
if (extension) {
/* Can only be used to create new rows */
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_INCONSISTENTVALUE);
return SNMP_ERR_INCONSISTENTVALUE;
}
break;
case RS_DESTROY:
break;
default:
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGVALUE);
return SNMP_ERR_WRONGVALUE;
}
break;
default:
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_NOTWRITABLE);
return SNMP_ERR_NOTWRITABLE;
}
break;
case MODE_SET_RESERVE2:
switch (table_info->colnum) {
case COLUMN_EXTCFG_STATUS:
i = *request->requestvb->val.integer;
switch (i) {
case RS_CREATEANDGO:
case RS_CREATEANDWAIT:
eptr = _find_extension_block( request->requestvb->name,
request->requestvb->name_length );
extension = _new_extension( (char *) table_info->indexes->val.string,
0, eptr );
if (!extension) { /* failed */
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_RESOURCEUNAVAILABLE);
return SNMP_ERR_RESOURCEUNAVAILABLE;
}
netsnmp_insert_table_row( request, extension->row );
}
}
break;
case MODE_SET_FREE:
switch (table_info->colnum) {
case COLUMN_EXTCFG_STATUS:
i = *request->requestvb->val.integer;
switch (i) {
case RS_CREATEANDGO:
case RS_CREATEANDWAIT:
eptr = _find_extension_block( request->requestvb->name,
request->requestvb->name_length );
_free_extension( extension, eptr );
}
}
break;
case MODE_SET_ACTION:
switch (table_info->colnum) {
case COLUMN_EXTCFG_COMMAND:
extension->old_command = extension->command;
extension->command = netsnmp_strdup_and_null(
request->requestvb->val.string,
request->requestvb->val_len);
break;
case COLUMN_EXTCFG_ARGS:
extension->old_args = extension->args;
extension->args = netsnmp_strdup_and_null(
request->requestvb->val.string,
request->requestvb->val_len);
break;
case COLUMN_EXTCFG_INPUT:
extension->old_input = extension->input;
extension->input = netsnmp_strdup_and_null(
request->requestvb->val.string,
request->requestvb->val_len);
break;
case COLUMN_EXTCFG_STATUS:
i = *request->requestvb->val.integer;
switch (i) {
case RS_ACTIVE:
case RS_CREATEANDGO:
need_to_validate = 1;
}
break;
}
break;
case MODE_SET_UNDO:
switch (table_info->colnum) {
case COLUMN_EXTCFG_COMMAND:
if ( extension && extension->old_command ) {
SNMP_FREE(extension->command);
extension->command = extension->old_command;
extension->old_command = NULL;
}
break;
case COLUMN_EXTCFG_ARGS:
if ( extension && extension->old_args ) {
SNMP_FREE(extension->args);
extension->args = extension->old_args;
extension->old_args = NULL;
}
break;
case COLUMN_EXTCFG_INPUT:
if ( extension && extension->old_input ) {
SNMP_FREE(extension->input);
extension->input = extension->old_input;
extension->old_input = NULL;
}
break;
case COLUMN_EXTCFG_STATUS:
i = *request->requestvb->val.integer;
switch (i) {
case RS_CREATEANDGO:
case RS_CREATEANDWAIT:
eptr = _find_extension_block( request->requestvb->name,
request->requestvb->name_length );
_free_extension( extension, eptr );
}
break;
}
break;
case MODE_SET_COMMIT:
switch (table_info->colnum) {
case COLUMN_EXTCFG_CACHETIME:
i = *request->requestvb->val.integer;
extension->cache->timeout = i;
break;
case COLUMN_EXTCFG_RUNTYPE:
i = *request->requestvb->val.integer;
switch (i) {
case 1:
extension->flags &= ~NS_EXTEND_FLAGS_WRITEABLE;
break;
case 2:
extension->flags |= NS_EXTEND_FLAGS_WRITEABLE;
break;
case 3:
(void)netsnmp_cache_check_and_reload( extension->cache );
break;
}
break;
case COLUMN_EXTCFG_EXECTYPE:
i = *request->requestvb->val.integer;
if ( i == NS_EXTEND_ETYPE_SHELL )
extension->flags |= NS_EXTEND_FLAGS_SHELL;
else
extension->flags &= ~NS_EXTEND_FLAGS_SHELL;
break;
case COLUMN_EXTCFG_STATUS:
i = *request->requestvb->val.integer;
switch (i) {
case RS_ACTIVE:
case RS_CREATEANDGO:
extension->flags |= NS_EXTEND_FLAGS_ACTIVE;
break;
case RS_NOTINSERVICE:
case RS_CREATEANDWAIT:
extension->flags &= ~NS_EXTEND_FLAGS_ACTIVE;
break;
case RS_DESTROY:
eptr = _find_extension_block( request->requestvb->name,
request->requestvb->name_length );
_free_extension( extension, eptr );
break;
}
}
break;
#endif /* !NETSNMP_NO_WRITE_SUPPORT and ENABLE_EXTEND_WRITE_ACCESS */
default:
netsnmp_set_request_error(reqinfo, request, SNMP_ERR_GENERR);
return SNMP_ERR_GENERR;
}
}
#if !defined(NETSNMP_NO_WRITE_SUPPORT) && ENABLE_EXTEND_WRITE_ACCESS
/*
* If we're marking a given row as active,
* then we need to check that it's ready.
*/
if (need_to_validate) {
for ( request=requests; request; request=request->next ) {
if (request->processed)
continue;
table_info = netsnmp_extract_table_info( request );
extension = (netsnmp_extend*)netsnmp_extract_table_row_data( request );
switch (table_info->colnum) {
case COLUMN_EXTCFG_STATUS:
i = *request->requestvb->val.integer;
if (( i == RS_ACTIVE || i == RS_CREATEANDGO ) &&
!(extension && extension->command &&
extension->command[0] == '/' /* &&
is_executable(extension->command) */)) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_INCONSISTENTVALUE);
return SNMP_ERR_INCONSISTENTVALUE;
}
}
}
}
#endif /* !NETSNMP_NO_WRITE_SUPPORT && ENABLE_EXTEND_WRITE_ACCESS */
return SNMP_ERR_NOERROR;
}
int
handle_nsExtendOutput1Table(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
{
netsnmp_request_info *request;
netsnmp_table_request_info *table_info;
netsnmp_extend *extension;
int len;
for ( request=requests; request; request=request->next ) {
if (request->processed)
continue;
table_info = netsnmp_extract_table_info( request );
extension = (netsnmp_extend*)netsnmp_extract_table_row_data( request );
DEBUGMSGTL(( "nsExtendTable:output1", "varbind: "));
DEBUGMSGOID(("nsExtendTable:output1", request->requestvb->name,
request->requestvb->name_length));
DEBUGMSG(( "nsExtendTable:output1", "\n"));
switch (reqinfo->mode) {
case MODE_GET:
if (!extension || !(extension->flags & NS_EXTEND_FLAGS_ACTIVE)) {
/*
* If this row is inactive, then skip it.
*/
netsnmp_set_request_error(reqinfo, request,
SNMP_NOSUCHINSTANCE);
continue;
}
if (!(extension->flags & NS_EXTEND_FLAGS_WRITEABLE) &&
(netsnmp_cache_check_and_reload( extension->cache ) < 0 )) {
/*
* If reloading the output cache of a 'run-on-read'
* entry fails, then skip it.
*/
netsnmp_set_request_error(reqinfo, request,
SNMP_NOSUCHINSTANCE);
continue;
}
if ((extension->flags & NS_EXTEND_FLAGS_WRITEABLE) &&
(netsnmp_cache_check_expired( extension->cache ) == 1 )) {
/*
* If the output cache of a 'run-on-write'
* entry has expired, then skip it.
*/
netsnmp_set_request_error(reqinfo, request,
SNMP_NOSUCHINSTANCE);
continue;
}
switch (table_info->colnum) {
case COLUMN_EXTOUT1_OUTLEN:
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&extension->out_len, sizeof(int));
break;
case COLUMN_EXTOUT1_OUTPUT1:
/*
* If we've got more than one line,
* find the length of the first one.
* Otherwise find the length of the whole string.
*/
if (extension->numlines > 1) {
len = (extension->lines[1])-(extension->output) -1;
} else if (extension->output) {
len = strlen(extension->output);
} else {
len = 0;
}
snmp_set_var_typed_value(
request->requestvb, ASN_OCTET_STR,
extension->output, len);
break;
case COLUMN_EXTOUT1_OUTPUT2:
snmp_set_var_typed_value(
request->requestvb, ASN_OCTET_STR,
extension->output,
(extension->output)?extension->out_len:0);
break;
case COLUMN_EXTOUT1_NUMLINES:
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&extension->numlines, sizeof(int));
break;
case COLUMN_EXTOUT1_RESULT:
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&extension->result, sizeof(int));
break;
default:
netsnmp_set_request_error(reqinfo, request, SNMP_NOSUCHOBJECT);
continue;
}
break;
default:
netsnmp_set_request_error(reqinfo, request, SNMP_ERR_GENERR);
return SNMP_ERR_GENERR;
}
}
return SNMP_ERR_NOERROR;
}
/*************************
*
* Multi-line output table handler
* Most of the work is handled here.
*
*************************/
/*
* Locate the appropriate entry for a given request
*/
netsnmp_extend *
_extend_find_entry( netsnmp_request_info *request,
netsnmp_table_request_info *table_info,
int mode )
{
netsnmp_extend *eptr;
extend_registration_block *ereg;
unsigned int line_idx;
oid oid_buf[MAX_OID_LEN];
int oid_len;
int i;
char *token;
size_t token_len;
if (!request || !table_info || !table_info->indexes
|| !table_info->indexes->next_variable) {
DEBUGMSGTL(( "nsExtendTable:output2", "invalid invocation\n"));
return NULL;
}
ereg = _find_extension_block( request->requestvb->name,
request->requestvb->name_length );
/***
* GET handling - find the exact entry being requested
***/
if ( mode == MODE_GET ) {
DEBUGMSGTL(( "nsExtendTable:output2", "GET: %s / %ld\n ",
table_info->indexes->val.string,
*table_info->indexes->next_variable->val.integer));
for ( eptr = ereg->ehead; eptr; eptr = eptr->next ) {
if ( !strcmp( eptr->token, (char *) table_info->indexes->val.string ))
break;
}
if ( eptr ) {
/*
* Ensure the output is available...
*/
if (!(eptr->flags & NS_EXTEND_FLAGS_ACTIVE) ||
(netsnmp_cache_check_and_reload( eptr->cache ) < 0 ))
return NULL;
/*
* ...and check the line requested is valid
*/
line_idx = *table_info->indexes->next_variable->val.integer;
if (line_idx < 1 || line_idx > eptr->numlines)
return NULL;
}
}
/***
* GETNEXT handling - find the first suitable entry
***/
else {
if (!table_info->indexes->val_len ) {
DEBUGMSGTL(( "nsExtendTable:output2", "GETNEXT: first entry\n"));
/*
* Beginning of the table - find the first active
* (and successful) entry, and use the first line of it
*/
for (eptr = ereg->ehead; eptr; eptr = eptr->next ) {
if ((eptr->flags & NS_EXTEND_FLAGS_ACTIVE) &&
(netsnmp_cache_check_and_reload( eptr->cache ) >= 0 )) {
line_idx = 1;
break;
}
}
} else {
token = (char *) table_info->indexes->val.string;
token_len = table_info->indexes->val_len;
line_idx = *table_info->indexes->next_variable->val.integer;
DEBUGMSGTL(( "nsExtendTable:output2", "GETNEXT: %s / %d\n ",
token, line_idx ));
/*
* Otherwise, find the first entry not earlier
* than the requested token...
*/
for (eptr = ereg->ehead; eptr; eptr = eptr->next ) {
if ( strlen(eptr->token) > token_len )
break;
if ( strlen(eptr->token) == token_len &&
strcmp(eptr->token, token) >= 0 )
break;
}
if (!eptr)
return NULL; /* (assuming there is one) */
/*
* ... and make sure it's active & the output is available
* (or use the first following entry that is)
*/
for ( ; eptr; eptr = eptr->next ) {
if ((eptr->flags & NS_EXTEND_FLAGS_ACTIVE) &&
(netsnmp_cache_check_and_reload( eptr->cache ) >= 0 )) {
break;
}
line_idx = 1;
}
if (!eptr)
return NULL; /* (assuming there is one) */
/*
* If we're working with the same entry that was requested,
* see whether we've reached the end of the output...
*/
if (!strcmp( eptr->token, token )) {
if ( eptr->numlines <= line_idx ) {
/*
* ... and if so, move on to the first line
* of the next (active and successful) entry.
*/
line_idx = 1;
for (eptr = eptr->next ; eptr; eptr = eptr->next ) {
if ((eptr->flags & NS_EXTEND_FLAGS_ACTIVE) &&
(netsnmp_cache_check_and_reload( eptr->cache ) >= 0 )) {
break;
}
}
} else {
/*
* Otherwise just use the next line of this entry.
*/
line_idx++;
}
}
else {
/*
* If this is not the same entry that was requested,
* then we should return the first line.
*/
line_idx = 1;
}
}
if (eptr) {
DEBUGMSGTL(( "nsExtendTable:output2", "GETNEXT -> %s / %d\n ",
eptr->token, line_idx));
/*
* Since we're processing a GETNEXT request,
* now we've found the appropriate entry (and line),
* we need to update the varbind OID ...
*/
memset(oid_buf, 0, sizeof(oid_buf));
oid_len = ereg->oid_len;
memcpy( oid_buf, ereg->root_oid, oid_len*sizeof(oid));
oid_buf[ oid_len++ ] = 4; /* nsExtendOutput2Table */
oid_buf[ oid_len++ ] = 1; /* nsExtendOutput2Entry */
oid_buf[ oid_len++ ] = COLUMN_EXTOUT2_OUTLINE;
/* string token index */
oid_buf[ oid_len++ ] = strlen(eptr->token);
for ( i=0; i < (int)strlen(eptr->token); i++ )
oid_buf[ oid_len+i ] = eptr->token[i];
oid_len += strlen( eptr->token );
/* plus line number */
oid_buf[ oid_len++ ] = line_idx;
snmp_set_var_objid( request->requestvb, oid_buf, oid_len );
/*
* ... and index values to match.
*/
snmp_set_var_value( table_info->indexes,
eptr->token, strlen(eptr->token));
snmp_set_var_value( table_info->indexes->next_variable,
(const u_char*)&line_idx, sizeof(line_idx));
}
}
return eptr; /* Finally, signal success */
}
/*
* Multi-line output handler
* Locate the appropriate entry (using _extend_find_entry)
* and return the appropriate output line
*/
int
handle_nsExtendOutput2Table(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
{
netsnmp_request_info *request;
netsnmp_table_request_info *table_info;
netsnmp_extend *extension;
char *cp;
unsigned int line_idx;
int len;
for ( request=requests; request; request=request->next ) {
if (request->processed)
continue;
table_info = netsnmp_extract_table_info( request );
extension = _extend_find_entry( request, table_info, reqinfo->mode );
DEBUGMSGTL(( "nsExtendTable:output2", "varbind: "));
DEBUGMSGOID(("nsExtendTable:output2", request->requestvb->name,
request->requestvb->name_length));
DEBUGMSG(( "nsExtendTable:output2", " (%s)\n",
(extension) ? extension->token : "[none]"));
if (!extension) {
if (reqinfo->mode == MODE_GET)
netsnmp_set_request_error(reqinfo, request, SNMP_NOSUCHINSTANCE);
else
netsnmp_set_request_error(reqinfo, request, SNMP_ENDOFMIBVIEW);
continue;
}
switch (reqinfo->mode) {
case MODE_GET:
case MODE_GETNEXT:
switch (table_info->colnum) {
case COLUMN_EXTOUT2_OUTLINE:
/*
* Determine which line we've been asked for....
*/
line_idx = *table_info->indexes->next_variable->val.integer;
if (line_idx < 1 || line_idx > extension->numlines) {
netsnmp_set_request_error(reqinfo, request, SNMP_NOSUCHINSTANCE);
continue;
}
cp = extension->lines[line_idx-1];
/*
* ... and how long it is.
*/
if ( extension->numlines > line_idx )
len = (extension->lines[line_idx])-cp -1;
else if (cp)
len = strlen(cp);
else
len = 0;
snmp_set_var_typed_value( request->requestvb,
ASN_OCTET_STR, cp, len );
break;
default:
netsnmp_set_request_error(reqinfo, request, SNMP_NOSUCHOBJECT);
continue;
}
break;
default:
netsnmp_set_request_error(reqinfo, request, SNMP_ERR_GENERR);
return SNMP_ERR_GENERR;
}
}
return SNMP_ERR_NOERROR;
}
#ifndef USING_UCD_SNMP_EXTENSIBLE_MODULE
/*************************
*
* Compatability with the UCD extTable
*
*************************/
char * _get_cmdline(netsnmp_extend *extend)
{
size_t size;
char *newbuf;
const char *args = extend->args;
if (args == NULL)
/* Use empty string for processes without arguments. */
args = "";
size = strlen(extend->command) + strlen(args) + 2;
if (size > cmdlinesize) {
newbuf = realloc(cmdlinebuf, size);
if (!newbuf) {
free(cmdlinebuf);
cmdlinebuf = NULL;
cmdlinesize = 0;
return NULL;
}
cmdlinebuf = newbuf;
cmdlinesize = size;
}
sprintf(cmdlinebuf, "%s %s", extend->command, args);
return cmdlinebuf;
}
u_char *
var_extensible_old(struct variable * vp,
oid * name,
size_t * length,
int exact,
size_t * var_len, WriteMethod ** write_method)
{
netsnmp_old_extend *exten = NULL;
static long long_ret;
unsigned int idx;
char *cmdline;
if (header_simple_table
(vp, name, length, exact, var_len, write_method, num_compatability_entries))
return (NULL);
idx = name[*length-1] -1;
if (idx > max_compatability_entries)
return NULL;
exten = &compatability_entries[idx];
switch (vp->magic) {
case MIBINDEX:
long_ret = name[*length - 1];
return (u_char *) &long_ret;
case ERRORNAME: /* name defined in config file */
*var_len = strlen(exten->exec_entry->token);
return ((u_char *) (exten->exec_entry->token));
case SHELLCOMMAND:
cmdline = _get_cmdline(exten->exec_entry);
if (cmdline)
*var_len = strlen(cmdline);
return (u_char *) cmdline;
case ERRORFLAG: /* return code from the process */
netsnmp_cache_check_and_reload( exten->exec_entry->cache );
long_ret = exten->exec_entry->result;
return (u_char *) &long_ret;
case ERRORMSG: /* first line of text returned from the process */
netsnmp_cache_check_and_reload( exten->exec_entry->cache );
if (exten->exec_entry->numlines > 1) {
*var_len = (exten->exec_entry->lines[1])-
(exten->exec_entry->output) -1;
} else if (exten->exec_entry->output) {
*var_len = strlen(exten->exec_entry->output);
} else {
*var_len = 0;
}
return (u_char *) exten->exec_entry->output;
case ERRORFIX:
*write_method = fixExec2Error;
long_return = 0;
return (u_char *) &long_return;
case ERRORFIXCMD:
if (exten->efix_entry) {
cmdline = _get_cmdline(exten->efix_entry);
if (cmdline)
*var_len = strlen(cmdline);
return (u_char *) cmdline;
} else {
*var_len = 0;
return (u_char *) &long_return; /* Just needs to be non-null! */
}
}
return NULL;
}
int
fixExec2Error(int action,
u_char * var_val,
u_char var_val_type,
size_t var_val_len,
u_char * statP, oid * name, size_t name_len)
{
netsnmp_old_extend *exten = NULL;
unsigned int idx;
idx = name[name_len-1] -1;
exten = &compatability_entries[ idx ];
#if !defined(NETSNMP_NO_WRITE_SUPPORT) && ENABLE_EXTEND_WRITE_ACCESS
switch (action) {
case MODE_SET_RESERVE1:
if (var_val_type != ASN_INTEGER) {
snmp_log(LOG_ERR, "Wrong type != int\n");
return SNMP_ERR_WRONGTYPE;
}
idx = *((long *) var_val);
if (idx != 1) {
snmp_log(LOG_ERR, "Wrong value != 1\n");
return SNMP_ERR_WRONGVALUE;
}
if (!exten || !exten->efix_entry) {
snmp_log(LOG_ERR, "No command to run\n");
return SNMP_ERR_GENERR;
}
return SNMP_ERR_NOERROR;
case MODE_SET_COMMIT:
netsnmp_cache_check_and_reload( exten->efix_entry->cache );
}
#endif /* !NETSNMP_NO_WRITE_SUPPORT && ENABLE_EXTEND_WRITE_ACCESS */
return SNMP_ERR_NOERROR;
}
#endif /* USING_UCD_SNMP_EXTENSIBLE_MODULE */
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_4227_0 |
crossvul-cpp_data_bad_3229_1 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3229_1 |
crossvul-cpp_data_good_3228_2 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include <signal.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/types.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#ifndef DEDICATED
#ifdef USE_LOCAL_HEADERS
# include "SDL.h"
# include "SDL_cpuinfo.h"
#else
# include <SDL.h>
# include <SDL_cpuinfo.h>
#endif
#endif
#include "sys_local.h"
#include "sys_loadlib.h"
#include "../qcommon/q_shared.h"
#include "../qcommon/qcommon.h"
static char binaryPath[ MAX_OSPATH ] = { 0 };
static char installPath[ MAX_OSPATH ] = { 0 };
/*
=================
Sys_SetBinaryPath
=================
*/
void Sys_SetBinaryPath(const char *path)
{
Q_strncpyz(binaryPath, path, sizeof(binaryPath));
}
/*
=================
Sys_BinaryPath
=================
*/
char *Sys_BinaryPath(void)
{
return binaryPath;
}
/*
=================
Sys_SetDefaultInstallPath
=================
*/
void Sys_SetDefaultInstallPath(const char *path)
{
Q_strncpyz(installPath, path, sizeof(installPath));
}
/*
=================
Sys_DefaultInstallPath
=================
*/
char *Sys_DefaultInstallPath(void)
{
if (*installPath)
return installPath;
else
return Sys_Cwd();
}
/*
=================
Sys_DefaultAppPath
=================
*/
char *Sys_DefaultAppPath(void)
{
return Sys_BinaryPath();
}
/*
=================
Sys_In_Restart_f
Restart the input subsystem
=================
*/
void Sys_In_Restart_f( void )
{
IN_Restart( );
}
/*
=================
Sys_ConsoleInput
Handle new console input
=================
*/
char *Sys_ConsoleInput(void)
{
return CON_Input( );
}
/*
==================
Sys_GetClipboardData
==================
*/
char *Sys_GetClipboardData(void)
{
#ifdef DEDICATED
return NULL;
#else
char *data = NULL;
char *cliptext;
if ( ( cliptext = SDL_GetClipboardText() ) != NULL ) {
if ( cliptext[0] != '\0' ) {
size_t bufsize = strlen( cliptext ) + 1;
data = Z_Malloc( bufsize );
Q_strncpyz( data, cliptext, bufsize );
// find first listed char and set to '\0'
strtok( data, "\n\r\b" );
}
SDL_free( cliptext );
}
return data;
#endif
}
#ifdef DEDICATED
# define PID_FILENAME PRODUCT_NAME "_server.pid"
#else
# define PID_FILENAME PRODUCT_NAME ".pid"
#endif
/*
=================
Sys_PIDFileName
=================
*/
static char *Sys_PIDFileName( const char *gamedir )
{
const char *homePath = Cvar_VariableString( "fs_homepath" );
if( *homePath != '\0' )
return va( "%s/%s/%s", homePath, gamedir, PID_FILENAME );
return NULL;
}
/*
=================
Sys_RemovePIDFile
=================
*/
void Sys_RemovePIDFile( const char *gamedir )
{
char *pidFile = Sys_PIDFileName( gamedir );
if( pidFile != NULL )
remove( pidFile );
}
/*
=================
Sys_WritePIDFile
Return qtrue if there is an existing stale PID file
=================
*/
static qboolean Sys_WritePIDFile( const char *gamedir )
{
char *pidFile = Sys_PIDFileName( gamedir );
FILE *f;
qboolean stale = qfalse;
if( pidFile == NULL )
return qfalse;
// First, check if the pid file is already there
if( ( f = fopen( pidFile, "r" ) ) != NULL )
{
char pidBuffer[ 64 ] = { 0 };
int pid;
pid = fread( pidBuffer, sizeof( char ), sizeof( pidBuffer ) - 1, f );
fclose( f );
if(pid > 0)
{
pid = atoi( pidBuffer );
if( !Sys_PIDIsRunning( pid ) )
stale = qtrue;
}
else
stale = qtrue;
}
if( FS_CreatePath( pidFile ) ) {
return 0;
}
if( ( f = fopen( pidFile, "w" ) ) != NULL )
{
fprintf( f, "%d", Sys_PID( ) );
fclose( f );
}
else
Com_Printf( S_COLOR_YELLOW "Couldn't write %s.\n", pidFile );
return stale;
}
/*
=================
Sys_InitPIDFile
=================
*/
void Sys_InitPIDFile( const char *gamedir ) {
if( Sys_WritePIDFile( gamedir ) ) {
#ifndef DEDICATED
char message[1024];
char modName[MAX_OSPATH];
FS_GetModDescription( gamedir, modName, sizeof ( modName ) );
Q_CleanStr( modName );
Com_sprintf( message, sizeof (message), "The last time %s ran, "
"it didn't exit properly. This may be due to inappropriate video "
"settings. Would you like to start with \"safe\" video settings?", modName );
if( Sys_Dialog( DT_YES_NO, message, "Abnormal Exit" ) == DR_YES ) {
Cvar_Set( "com_abnormalExit", "1" );
}
#endif
}
}
/*
=================
Sys_Exit
Single exit point (regular exit or in case of error)
=================
*/
static __attribute__ ((noreturn)) void Sys_Exit( int exitCode )
{
CON_Shutdown( );
#ifndef DEDICATED
SDL_Quit( );
#endif
if( exitCode < 2 && com_fullyInitialized )
{
// Normal exit
Sys_RemovePIDFile( FS_GetCurrentGameDir() );
}
NET_Shutdown( );
Sys_PlatformExit( );
exit( exitCode );
}
/*
=================
Sys_Quit
=================
*/
void Sys_Quit( void )
{
Sys_Exit( 0 );
}
/*
=================
Sys_GetProcessorFeatures
=================
*/
cpuFeatures_t Sys_GetProcessorFeatures( void )
{
cpuFeatures_t features = 0;
#ifndef DEDICATED
if( SDL_HasRDTSC( ) ) features |= CF_RDTSC;
if( SDL_Has3DNow( ) ) features |= CF_3DNOW;
if( SDL_HasMMX( ) ) features |= CF_MMX;
if( SDL_HasSSE( ) ) features |= CF_SSE;
if( SDL_HasSSE2( ) ) features |= CF_SSE2;
if( SDL_HasAltiVec( ) ) features |= CF_ALTIVEC;
#endif
return features;
}
/*
=================
Sys_Init
=================
*/
void Sys_Init(void)
{
Cmd_AddCommand( "in_restart", Sys_In_Restart_f );
Cvar_Set( "arch", OS_STRING " " ARCH_STRING );
Cvar_Set( "username", Sys_GetCurrentUser( ) );
}
/*
=================
Sys_AnsiColorPrint
Transform Q3 colour codes to ANSI escape sequences
=================
*/
void Sys_AnsiColorPrint( const char *msg )
{
static char buffer[ MAXPRINTMSG ];
int length = 0;
static int q3ToAnsi[ 8 ] =
{
30, // COLOR_BLACK
31, // COLOR_RED
32, // COLOR_GREEN
33, // COLOR_YELLOW
34, // COLOR_BLUE
36, // COLOR_CYAN
35, // COLOR_MAGENTA
0 // COLOR_WHITE
};
while( *msg )
{
if( Q_IsColorString( msg ) || *msg == '\n' )
{
// First empty the buffer
if( length > 0 )
{
buffer[ length ] = '\0';
fputs( buffer, stderr );
length = 0;
}
if( *msg == '\n' )
{
// Issue a reset and then the newline
fputs( "\033[0m\n", stderr );
msg++;
}
else
{
// Print the color code
Com_sprintf( buffer, sizeof( buffer ), "\033[%dm",
q3ToAnsi[ ColorIndex( *( msg + 1 ) ) ] );
fputs( buffer, stderr );
msg += 2;
}
}
else
{
if( length >= MAXPRINTMSG - 1 )
break;
buffer[ length ] = *msg;
length++;
msg++;
}
}
// Empty anything still left in the buffer
if( length > 0 )
{
buffer[ length ] = '\0';
fputs( buffer, stderr );
}
}
/*
=================
Sys_Print
=================
*/
void Sys_Print( const char *msg )
{
CON_LogWrite( msg );
CON_Print( msg );
}
/*
=================
Sys_Error
=================
*/
void Sys_Error( const char *error, ... )
{
va_list argptr;
char string[1024];
va_start (argptr,error);
Q_vsnprintf (string, sizeof(string), error, argptr);
va_end (argptr);
Sys_ErrorDialog( string );
Sys_Exit( 3 );
}
#if 0
/*
=================
Sys_Warn
=================
*/
static __attribute__ ((format (printf, 1, 2))) void Sys_Warn( char *warning, ... )
{
va_list argptr;
char string[1024];
va_start (argptr,warning);
Q_vsnprintf (string, sizeof(string), warning, argptr);
va_end (argptr);
CON_Print( va( "Warning: %s", string ) );
}
#endif
/*
============
Sys_FileTime
returns -1 if not present
============
*/
int Sys_FileTime( char *path )
{
struct stat buf;
if (stat (path,&buf) == -1)
return -1;
return buf.st_mtime;
}
/*
=================
Sys_UnloadDll
=================
*/
void Sys_UnloadDll( void *dllHandle )
{
if( !dllHandle )
{
Com_Printf("Sys_UnloadDll(NULL)\n");
return;
}
Sys_UnloadLibrary(dllHandle);
}
/*
=================
Sys_LoadDll
First try to load library name from system library path,
from executable path, then fs_basepath.
=================
*/
void *Sys_LoadDll(const char *name, qboolean useSystemLib)
{
void *dllhandle;
// Don't load any DLLs that end with the pk3 extension
if (COM_CompareExtension(name, ".pk3"))
{
Com_Printf("Rejecting DLL named \"%s\"", name);
return NULL;
}
if(useSystemLib)
Com_Printf("Trying to load \"%s\"...\n", name);
if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name)))
{
const char *topDir;
char libPath[MAX_OSPATH];
topDir = Sys_BinaryPath();
if(!*topDir)
topDir = ".";
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name);
if(!(dllhandle = Sys_LoadLibrary(libPath)))
{
const char *basePath = Cvar_VariableString("fs_basepath");
if(!basePath || !*basePath)
basePath = ".";
if(FS_FilenameCompare(topDir, basePath))
{
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name);
dllhandle = Sys_LoadLibrary(libPath);
}
if(!dllhandle)
Com_Printf("Loading \"%s\" failed\n", name);
}
}
return dllhandle;
}
/*
=================
Sys_LoadGameDll
Used to load a development dll instead of a virtual machine
=================
*/
void *Sys_LoadGameDll(const char *name,
intptr_t (QDECL **entryPoint)(int, ...),
intptr_t (*systemcalls)(intptr_t, ...))
{
void *libHandle;
void (*dllEntry)(intptr_t (*syscallptr)(intptr_t, ...));
assert(name);
Com_Printf( "Loading DLL file: %s\n", name);
libHandle = Sys_LoadLibrary(name);
if(!libHandle)
{
Com_Printf("Sys_LoadGameDll(%s) failed:\n\"%s\"\n", name, Sys_LibraryError());
return NULL;
}
dllEntry = Sys_LoadFunction( libHandle, "dllEntry" );
*entryPoint = Sys_LoadFunction( libHandle, "vmMain" );
if ( !*entryPoint || !dllEntry )
{
Com_Printf ( "Sys_LoadGameDll(%s) failed to find vmMain function:\n\"%s\" !\n", name, Sys_LibraryError( ) );
Sys_UnloadLibrary(libHandle);
return NULL;
}
Com_Printf ( "Sys_LoadGameDll(%s) found vmMain function at %p\n", name, *entryPoint );
dllEntry( systemcalls );
return libHandle;
}
/*
=================
Sys_ParseArgs
=================
*/
void Sys_ParseArgs( int argc, char **argv )
{
if( argc == 2 )
{
if( !strcmp( argv[1], "--version" ) ||
!strcmp( argv[1], "-v" ) )
{
const char* date = PRODUCT_DATE;
#ifdef DEDICATED
fprintf( stdout, Q3_VERSION " dedicated server (%s)\n", date );
#else
fprintf( stdout, Q3_VERSION " client (%s)\n", date );
#endif
Sys_Exit( 0 );
}
}
}
#ifndef DEFAULT_BASEDIR
# ifdef __APPLE__
# define DEFAULT_BASEDIR Sys_StripAppBundle(Sys_BinaryPath())
# else
# define DEFAULT_BASEDIR Sys_BinaryPath()
# endif
#endif
/*
=================
Sys_SigHandler
=================
*/
void Sys_SigHandler( int signal )
{
static qboolean signalcaught = qfalse;
if( signalcaught )
{
fprintf( stderr, "DOUBLE SIGNAL FAULT: Received signal %d, exiting...\n",
signal );
}
else
{
signalcaught = qtrue;
VM_Forced_Unload_Start();
#ifndef DEDICATED
CL_Shutdown(va("Received signal %d", signal), qtrue, qtrue);
#endif
SV_Shutdown(va("Received signal %d", signal) );
VM_Forced_Unload_Done();
}
if( signal == SIGTERM || signal == SIGINT )
Sys_Exit( 1 );
else
Sys_Exit( 2 );
}
/*
=================
main
=================
*/
int main( int argc, char **argv )
{
int i;
char commandLine[ MAX_STRING_CHARS ] = { 0 };
#ifndef DEDICATED
// SDL version check
// Compile time
# if !SDL_VERSION_ATLEAST(MINSDL_MAJOR,MINSDL_MINOR,MINSDL_PATCH)
# error A more recent version of SDL is required
# endif
// Run time
SDL_version ver;
SDL_GetVersion( &ver );
#define MINSDL_VERSION \
XSTRING(MINSDL_MAJOR) "." \
XSTRING(MINSDL_MINOR) "." \
XSTRING(MINSDL_PATCH)
if( SDL_VERSIONNUM( ver.major, ver.minor, ver.patch ) <
SDL_VERSIONNUM( MINSDL_MAJOR, MINSDL_MINOR, MINSDL_PATCH ) )
{
Sys_Dialog( DT_ERROR, va( "SDL version " MINSDL_VERSION " or greater is required, "
"but only version %d.%d.%d was found. You may be able to obtain a more recent copy "
"from http://www.libsdl.org/.", ver.major, ver.minor, ver.patch ), "SDL Library Too Old" );
Sys_Exit( 1 );
}
#endif
Sys_PlatformInit( );
// Set the initial time base
Sys_Milliseconds( );
#ifdef __APPLE__
// This is passed if we are launched by double-clicking
if ( argc >= 2 && Q_strncmp ( argv[1], "-psn", 4 ) == 0 )
argc = 1;
#endif
Sys_ParseArgs( argc, argv );
Sys_SetBinaryPath( Sys_Dirname( argv[ 0 ] ) );
Sys_SetDefaultInstallPath( DEFAULT_BASEDIR );
// Concatenate the command line for passing to Com_Init
for( i = 1; i < argc; i++ )
{
const qboolean containsSpaces = strchr(argv[i], ' ') != NULL;
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), argv[ i ] );
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), " " );
}
Com_Init( commandLine );
NET_Init( );
CON_Init( );
signal( SIGILL, Sys_SigHandler );
signal( SIGFPE, Sys_SigHandler );
signal( SIGSEGV, Sys_SigHandler );
signal( SIGTERM, Sys_SigHandler );
signal( SIGINT, Sys_SigHandler );
while( 1 )
{
IN_Frame( );
Com_Frame( );
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3228_2 |
crossvul-cpp_data_good_3229_1 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// common.c -- misc functions used in client and server
#include "q_shared.h"
#include "qcommon.h"
#include <setjmp.h>
#ifndef _WIN32
#include <netinet/in.h>
#include <sys/stat.h> // umask
#else
#include <winsock.h>
#endif
int demo_protocols[] =
{ 67, 66, 0 };
#define MAX_NUM_ARGVS 50
#define MIN_DEDICATED_COMHUNKMEGS 1
#define MIN_COMHUNKMEGS 56
#define DEF_COMHUNKMEGS 128
#define DEF_COMZONEMEGS 24
#define DEF_COMHUNKMEGS_S XSTRING(DEF_COMHUNKMEGS)
#define DEF_COMZONEMEGS_S XSTRING(DEF_COMZONEMEGS)
int com_argc;
char *com_argv[MAX_NUM_ARGVS+1];
jmp_buf abortframe; // an ERR_DROP occured, exit the entire frame
FILE *debuglogfile;
static fileHandle_t pipefile;
static fileHandle_t logfile;
fileHandle_t com_journalFile; // events are written here
fileHandle_t com_journalDataFile; // config files are written here
cvar_t *com_speeds;
cvar_t *com_developer;
cvar_t *com_dedicated;
cvar_t *com_timescale;
cvar_t *com_fixedtime;
cvar_t *com_journal;
cvar_t *com_maxfps;
cvar_t *com_altivec;
cvar_t *com_timedemo;
cvar_t *com_sv_running;
cvar_t *com_cl_running;
cvar_t *com_logfile; // 1 = buffer log, 2 = flush after each print
cvar_t *com_pipefile;
cvar_t *com_showtrace;
cvar_t *com_version;
cvar_t *com_blood;
cvar_t *com_buildScript; // for automated data building scripts
#ifdef CINEMATICS_INTRO
cvar_t *com_introPlayed;
#endif
cvar_t *cl_paused;
cvar_t *sv_paused;
cvar_t *cl_packetdelay;
cvar_t *sv_packetdelay;
cvar_t *com_cameraMode;
cvar_t *com_ansiColor;
cvar_t *com_unfocused;
cvar_t *com_maxfpsUnfocused;
cvar_t *com_minimized;
cvar_t *com_maxfpsMinimized;
cvar_t *com_abnormalExit;
cvar_t *com_standalone;
cvar_t *com_gamename;
cvar_t *com_protocol;
#ifdef LEGACY_PROTOCOL
cvar_t *com_legacyprotocol;
#endif
cvar_t *com_basegame;
cvar_t *com_homepath;
cvar_t *com_busyWait;
#if idx64
int (*Q_VMftol)(void);
#elif id386
long (QDECL *Q_ftol)(float f);
int (QDECL *Q_VMftol)(void);
void (QDECL *Q_SnapVector)(vec3_t vec);
#endif
// com_speeds times
int time_game;
int time_frontend; // renderer frontend time
int time_backend; // renderer backend time
int com_frameTime;
int com_frameNumber;
qboolean com_errorEntered = qfalse;
qboolean com_fullyInitialized = qfalse;
qboolean com_gameRestarting = qfalse;
qboolean com_gameClientRestarting = qfalse;
char com_errorMessage[MAXPRINTMSG];
void Com_WriteConfig_f( void );
void CIN_CloseAllVideos( void );
//============================================================================
static char *rd_buffer;
static int rd_buffersize;
static void (*rd_flush)( char *buffer );
void Com_BeginRedirect (char *buffer, int buffersize, void (*flush)( char *) )
{
if (!buffer || !buffersize || !flush)
return;
rd_buffer = buffer;
rd_buffersize = buffersize;
rd_flush = flush;
*rd_buffer = 0;
}
void Com_EndRedirect (void)
{
if ( rd_flush ) {
rd_flush(rd_buffer);
}
rd_buffer = NULL;
rd_buffersize = 0;
rd_flush = NULL;
}
/*
=============
Com_Printf
Both client and server can use this, and it will output
to the apropriate place.
A raw string should NEVER be passed as fmt, because of "%f" type crashers.
=============
*/
void QDECL Com_Printf( const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
static qboolean opening_qconsole = qfalse;
va_start (argptr,fmt);
Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
va_end (argptr);
if ( rd_buffer ) {
if ((strlen (msg) + strlen(rd_buffer)) > (rd_buffersize - 1)) {
rd_flush(rd_buffer);
*rd_buffer = 0;
}
Q_strcat(rd_buffer, rd_buffersize, msg);
// TTimo nooo .. that would defeat the purpose
//rd_flush(rd_buffer);
//*rd_buffer = 0;
return;
}
#ifndef DEDICATED
CL_ConsolePrint( msg );
#endif
// echo to dedicated console and early console
Sys_Print( msg );
// logfile
if ( com_logfile && com_logfile->integer ) {
// TTimo: only open the qconsole.log if the filesystem is in an initialized state
// also, avoid recursing in the qconsole.log opening (i.e. if fs_debug is on)
if ( !logfile && FS_Initialized() && !opening_qconsole) {
struct tm *newtime;
time_t aclock;
opening_qconsole = qtrue;
time( &aclock );
newtime = localtime( &aclock );
logfile = FS_FOpenFileWrite( "qconsole.log" );
if(logfile)
{
Com_Printf( "logfile opened on %s\n", asctime( newtime ) );
if ( com_logfile->integer > 1 )
{
// force it to not buffer so we get valid
// data even if we are crashing
FS_ForceFlush(logfile);
}
}
else
{
Com_Printf("Opening qconsole.log failed!\n");
Cvar_SetValue("logfile", 0);
}
opening_qconsole = qfalse;
}
if ( logfile && FS_Initialized()) {
FS_Write(msg, strlen(msg), logfile);
}
}
}
/*
================
Com_DPrintf
A Com_Printf that only shows up if the "developer" cvar is set
================
*/
void QDECL Com_DPrintf( const char *fmt, ...) {
va_list argptr;
char msg[MAXPRINTMSG];
if ( !com_developer || !com_developer->integer ) {
return; // don't confuse non-developers with techie stuff...
}
va_start (argptr,fmt);
Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
va_end (argptr);
Com_Printf ("%s", msg);
}
/*
=============
Com_Error
Both client and server can use this, and it will
do the appropriate thing.
=============
*/
void QDECL Com_Error( int code, const char *fmt, ... ) {
va_list argptr;
static int lastErrorTime;
static int errorCount;
int currentTime;
qboolean restartClient;
if(com_errorEntered)
Sys_Error("recursive error after: %s", com_errorMessage);
com_errorEntered = qtrue;
Cvar_Set("com_errorCode", va("%i", code));
// when we are running automated scripts, make sure we
// know if anything failed
if ( com_buildScript && com_buildScript->integer ) {
code = ERR_FATAL;
}
// if we are getting a solid stream of ERR_DROP, do an ERR_FATAL
currentTime = Sys_Milliseconds();
if ( currentTime - lastErrorTime < 100 ) {
if ( ++errorCount > 3 ) {
code = ERR_FATAL;
}
} else {
errorCount = 0;
}
lastErrorTime = currentTime;
va_start (argptr,fmt);
Q_vsnprintf (com_errorMessage, sizeof(com_errorMessage),fmt,argptr);
va_end (argptr);
if (code != ERR_DISCONNECT && code != ERR_NEED_CD)
Cvar_Set("com_errorMessage", com_errorMessage);
restartClient = com_gameClientRestarting && !( com_cl_running && com_cl_running->integer );
com_gameRestarting = qfalse;
com_gameClientRestarting = qfalse;
if (code == ERR_DISCONNECT || code == ERR_SERVERDISCONNECT) {
VM_Forced_Unload_Start();
SV_Shutdown( "Server disconnected" );
if ( restartClient ) {
CL_Init();
}
CL_Disconnect( qtrue );
CL_FlushMemory( );
VM_Forced_Unload_Done();
// make sure we can get at our local stuff
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp (abortframe, -1);
} else if (code == ERR_DROP) {
Com_Printf ("********************\nERROR: %s\n********************\n", com_errorMessage);
VM_Forced_Unload_Start();
SV_Shutdown (va("Server crashed: %s", com_errorMessage));
if ( restartClient ) {
CL_Init();
}
CL_Disconnect( qtrue );
CL_FlushMemory( );
VM_Forced_Unload_Done();
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp (abortframe, -1);
} else if ( code == ERR_NEED_CD ) {
VM_Forced_Unload_Start();
SV_Shutdown( "Server didn't have CD" );
if ( restartClient ) {
CL_Init();
}
if ( com_cl_running && com_cl_running->integer ) {
CL_Disconnect( qtrue );
CL_FlushMemory( );
VM_Forced_Unload_Done();
CL_CDDialog();
} else {
Com_Printf("Server didn't have CD\n" );
VM_Forced_Unload_Done();
}
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp (abortframe, -1);
} else {
VM_Forced_Unload_Start();
CL_Shutdown(va("Client fatal crashed: %s", com_errorMessage), qtrue, qtrue);
SV_Shutdown(va("Server fatal crashed: %s", com_errorMessage));
VM_Forced_Unload_Done();
}
Com_Shutdown ();
Sys_Error ("%s", com_errorMessage);
}
/*
=============
Com_Quit_f
Both client and server can use this, and it will
do the apropriate things.
=============
*/
void Com_Quit_f( void ) {
// don't try to shutdown if we are in a recursive error
char *p = Cmd_Args( );
if ( !com_errorEntered ) {
// Some VMs might execute "quit" command directly,
// which would trigger an unload of active VM error.
// Sys_Quit will kill this process anyways, so
// a corrupt call stack makes no difference
VM_Forced_Unload_Start();
SV_Shutdown(p[0] ? p : "Server quit");
CL_Shutdown(p[0] ? p : "Client quit", qtrue, qtrue);
VM_Forced_Unload_Done();
Com_Shutdown ();
FS_Shutdown(qtrue);
}
Sys_Quit ();
}
/*
============================================================================
COMMAND LINE FUNCTIONS
+ characters seperate the commandLine string into multiple console
command lines.
All of these are valid:
quake3 +set test blah +map test
quake3 set test blah+map test
quake3 set test blah + map test
============================================================================
*/
#define MAX_CONSOLE_LINES 32
int com_numConsoleLines;
char *com_consoleLines[MAX_CONSOLE_LINES];
/*
==================
Com_ParseCommandLine
Break it up into multiple console lines
==================
*/
void Com_ParseCommandLine( char *commandLine ) {
int inq = 0;
com_consoleLines[0] = commandLine;
com_numConsoleLines = 1;
while ( *commandLine ) {
if (*commandLine == '"') {
inq = !inq;
}
// look for a + separating character
// if commandLine came from a file, we might have real line seperators
if ( (*commandLine == '+' && !inq) || *commandLine == '\n' || *commandLine == '\r' ) {
if ( com_numConsoleLines == MAX_CONSOLE_LINES ) {
return;
}
com_consoleLines[com_numConsoleLines] = commandLine + 1;
com_numConsoleLines++;
*commandLine = 0;
}
commandLine++;
}
}
/*
===================
Com_SafeMode
Check for "safe" on the command line, which will
skip loading of q3config.cfg
===================
*/
qboolean Com_SafeMode( void ) {
int i;
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
Cmd_TokenizeString( com_consoleLines[i] );
if ( !Q_stricmp( Cmd_Argv(0), "safe" )
|| !Q_stricmp( Cmd_Argv(0), "cvar_restart" ) ) {
com_consoleLines[i][0] = 0;
return qtrue;
}
}
return qfalse;
}
/*
===============
Com_StartupVariable
Searches for command line parameters that are set commands.
If match is not NULL, only that cvar will be looked for.
That is necessary because cddir and basedir need to be set
before the filesystem is started, but all other sets should
be after execing the config and default.
===============
*/
void Com_StartupVariable( const char *match ) {
int i;
char *s;
for (i=0 ; i < com_numConsoleLines ; i++) {
Cmd_TokenizeString( com_consoleLines[i] );
if ( strcmp( Cmd_Argv(0), "set" ) ) {
continue;
}
s = Cmd_Argv(1);
if(!match || !strcmp(s, match))
{
if(Cvar_Flags(s) == CVAR_NONEXISTENT)
Cvar_Get(s, Cmd_ArgsFrom(2), CVAR_USER_CREATED);
else
Cvar_Set2(s, Cmd_ArgsFrom(2), qfalse);
}
}
}
/*
=================
Com_AddStartupCommands
Adds command line parameters as script statements
Commands are seperated by + signs
Returns qtrue if any late commands were added, which
will keep the demoloop from immediately starting
=================
*/
qboolean Com_AddStartupCommands( void ) {
int i;
qboolean added;
added = qfalse;
// quote every token, so args with semicolons can work
for (i=0 ; i < com_numConsoleLines ; i++) {
if ( !com_consoleLines[i] || !com_consoleLines[i][0] ) {
continue;
}
// set commands already added with Com_StartupVariable
if ( !Q_stricmpn( com_consoleLines[i], "set ", 4 ) ) {
continue;
}
added = qtrue;
Cbuf_AddText( com_consoleLines[i] );
Cbuf_AddText( "\n" );
}
return added;
}
//============================================================================
void Info_Print( const char *s ) {
char key[BIG_INFO_KEY];
char value[BIG_INFO_VALUE];
char *o;
int l;
if (*s == '\\')
s++;
while (*s)
{
o = key;
while (*s && *s != '\\')
*o++ = *s++;
l = o - key;
if (l < 20)
{
Com_Memset (o, ' ', 20-l);
key[20] = 0;
}
else
*o = 0;
Com_Printf ("%s ", key);
if (!*s)
{
Com_Printf ("MISSING VALUE\n");
return;
}
o = value;
s++;
while (*s && *s != '\\')
*o++ = *s++;
*o = 0;
if (*s)
s++;
Com_Printf ("%s\n", value);
}
}
/*
============
Com_StringContains
============
*/
char *Com_StringContains(char *str1, char *str2, int casesensitive) {
int len, i, j;
len = strlen(str1) - strlen(str2);
for (i = 0; i <= len; i++, str1++) {
for (j = 0; str2[j]; j++) {
if (casesensitive) {
if (str1[j] != str2[j]) {
break;
}
}
else {
if (toupper(str1[j]) != toupper(str2[j])) {
break;
}
}
}
if (!str2[j]) {
return str1;
}
}
return NULL;
}
/*
============
Com_Filter
============
*/
int Com_Filter(char *filter, char *name, int casesensitive)
{
char buf[MAX_TOKEN_CHARS];
char *ptr;
int i, found;
while(*filter) {
if (*filter == '*') {
filter++;
for (i = 0; *filter; i++) {
if (*filter == '*' || *filter == '?') break;
buf[i] = *filter;
filter++;
}
buf[i] = '\0';
if (strlen(buf)) {
ptr = Com_StringContains(name, buf, casesensitive);
if (!ptr) return qfalse;
name = ptr + strlen(buf);
}
}
else if (*filter == '?') {
filter++;
name++;
}
else if (*filter == '[' && *(filter+1) == '[') {
filter++;
}
else if (*filter == '[') {
filter++;
found = qfalse;
while(*filter && !found) {
if (*filter == ']' && *(filter+1) != ']') break;
if (*(filter+1) == '-' && *(filter+2) && (*(filter+2) != ']' || *(filter+3) == ']')) {
if (casesensitive) {
if (*name >= *filter && *name <= *(filter+2)) found = qtrue;
}
else {
if (toupper(*name) >= toupper(*filter) &&
toupper(*name) <= toupper(*(filter+2))) found = qtrue;
}
filter += 3;
}
else {
if (casesensitive) {
if (*filter == *name) found = qtrue;
}
else {
if (toupper(*filter) == toupper(*name)) found = qtrue;
}
filter++;
}
}
if (!found) return qfalse;
while(*filter) {
if (*filter == ']' && *(filter+1) != ']') break;
filter++;
}
filter++;
name++;
}
else {
if (casesensitive) {
if (*filter != *name) return qfalse;
}
else {
if (toupper(*filter) != toupper(*name)) return qfalse;
}
filter++;
name++;
}
}
return qtrue;
}
/*
============
Com_FilterPath
============
*/
int Com_FilterPath(char *filter, char *name, int casesensitive)
{
int i;
char new_filter[MAX_QPATH];
char new_name[MAX_QPATH];
for (i = 0; i < MAX_QPATH-1 && filter[i]; i++) {
if ( filter[i] == '\\' || filter[i] == ':' ) {
new_filter[i] = '/';
}
else {
new_filter[i] = filter[i];
}
}
new_filter[i] = '\0';
for (i = 0; i < MAX_QPATH-1 && name[i]; i++) {
if ( name[i] == '\\' || name[i] == ':' ) {
new_name[i] = '/';
}
else {
new_name[i] = name[i];
}
}
new_name[i] = '\0';
return Com_Filter(new_filter, new_name, casesensitive);
}
/*
================
Com_RealTime
================
*/
int Com_RealTime(qtime_t *qtime) {
time_t t;
struct tm *tms;
t = time(NULL);
if (!qtime)
return t;
tms = localtime(&t);
if (tms) {
qtime->tm_sec = tms->tm_sec;
qtime->tm_min = tms->tm_min;
qtime->tm_hour = tms->tm_hour;
qtime->tm_mday = tms->tm_mday;
qtime->tm_mon = tms->tm_mon;
qtime->tm_year = tms->tm_year;
qtime->tm_wday = tms->tm_wday;
qtime->tm_yday = tms->tm_yday;
qtime->tm_isdst = tms->tm_isdst;
}
return t;
}
/*
==============================================================================
ZONE MEMORY ALLOCATION
There is never any space between memblocks, and there will never be two
contiguous free memblocks.
The rover can be left pointing at a non-empty block
The zone calls are pretty much only used for small strings and structures,
all big things are allocated on the hunk.
==============================================================================
*/
#define ZONEID 0x1d4a11
#define MINFRAGMENT 64
typedef struct zonedebug_s {
char *label;
char *file;
int line;
int allocSize;
} zonedebug_t;
typedef struct memblock_s {
int size; // including the header and possibly tiny fragments
int tag; // a tag of 0 is a free block
struct memblock_s *next, *prev;
int id; // should be ZONEID
#ifdef ZONE_DEBUG
zonedebug_t d;
#endif
} memblock_t;
typedef struct {
int size; // total bytes malloced, including header
int used; // total bytes used
memblock_t blocklist; // start / end cap for linked list
memblock_t *rover;
} memzone_t;
// main zone for all "dynamic" memory allocation
memzone_t *mainzone;
// we also have a small zone for small allocations that would only
// fragment the main zone (think of cvar and cmd strings)
memzone_t *smallzone;
void Z_CheckHeap( void );
/*
========================
Z_ClearZone
========================
*/
void Z_ClearZone( memzone_t *zone, int size ) {
memblock_t *block;
// set the entire zone to one free block
zone->blocklist.next = zone->blocklist.prev = block =
(memblock_t *)( (byte *)zone + sizeof(memzone_t) );
zone->blocklist.tag = 1; // in use block
zone->blocklist.id = 0;
zone->blocklist.size = 0;
zone->rover = block;
zone->size = size;
zone->used = 0;
block->prev = block->next = &zone->blocklist;
block->tag = 0; // free block
block->id = ZONEID;
block->size = size - sizeof(memzone_t);
}
/*
========================
Z_AvailableZoneMemory
========================
*/
int Z_AvailableZoneMemory( memzone_t *zone ) {
return zone->size - zone->used;
}
/*
========================
Z_AvailableMemory
========================
*/
int Z_AvailableMemory( void ) {
return Z_AvailableZoneMemory( mainzone );
}
/*
========================
Z_Free
========================
*/
void Z_Free( void *ptr ) {
memblock_t *block, *other;
memzone_t *zone;
if (!ptr) {
Com_Error( ERR_DROP, "Z_Free: NULL pointer" );
}
block = (memblock_t *) ( (byte *)ptr - sizeof(memblock_t));
if (block->id != ZONEID) {
Com_Error( ERR_FATAL, "Z_Free: freed a pointer without ZONEID" );
}
if (block->tag == 0) {
Com_Error( ERR_FATAL, "Z_Free: freed a freed pointer" );
}
// if static memory
if (block->tag == TAG_STATIC) {
return;
}
// check the memory trash tester
if ( *(int *)((byte *)block + block->size - 4 ) != ZONEID ) {
Com_Error( ERR_FATAL, "Z_Free: memory block wrote past end" );
}
if (block->tag == TAG_SMALL) {
zone = smallzone;
}
else {
zone = mainzone;
}
zone->used -= block->size;
// set the block to something that should cause problems
// if it is referenced...
Com_Memset( ptr, 0xaa, block->size - sizeof( *block ) );
block->tag = 0; // mark as free
other = block->prev;
if (!other->tag) {
// merge with previous free block
other->size += block->size;
other->next = block->next;
other->next->prev = other;
if (block == zone->rover) {
zone->rover = other;
}
block = other;
}
zone->rover = block;
other = block->next;
if ( !other->tag ) {
// merge the next free block onto the end
block->size += other->size;
block->next = other->next;
block->next->prev = block;
}
}
/*
================
Z_FreeTags
================
*/
void Z_FreeTags( int tag ) {
int count;
memzone_t *zone;
if ( tag == TAG_SMALL ) {
zone = smallzone;
}
else {
zone = mainzone;
}
count = 0;
// use the rover as our pointer, because
// Z_Free automatically adjusts it
zone->rover = zone->blocklist.next;
do {
if ( zone->rover->tag == tag ) {
count++;
Z_Free( (void *)(zone->rover + 1) );
continue;
}
zone->rover = zone->rover->next;
} while ( zone->rover != &zone->blocklist );
}
/*
================
Z_TagMalloc
================
*/
#ifdef ZONE_DEBUG
void *Z_TagMallocDebug( int size, int tag, char *label, char *file, int line ) {
int allocSize;
#else
void *Z_TagMalloc( int size, int tag ) {
#endif
int extra;
memblock_t *start, *rover, *new, *base;
memzone_t *zone;
if (!tag) {
Com_Error( ERR_FATAL, "Z_TagMalloc: tried to use a 0 tag" );
}
if ( tag == TAG_SMALL ) {
zone = smallzone;
}
else {
zone = mainzone;
}
#ifdef ZONE_DEBUG
allocSize = size;
#endif
//
// scan through the block list looking for the first free block
// of sufficient size
//
size += sizeof(memblock_t); // account for size of block header
size += 4; // space for memory trash tester
size = PAD(size, sizeof(intptr_t)); // align to 32/64 bit boundary
base = rover = zone->rover;
start = base->prev;
do {
if (rover == start) {
// scaned all the way around the list
#ifdef ZONE_DEBUG
Z_LogHeap();
Com_Error(ERR_FATAL, "Z_Malloc: failed on allocation of %i bytes from the %s zone: %s, line: %d (%s)",
size, zone == smallzone ? "small" : "main", file, line, label);
#else
Com_Error(ERR_FATAL, "Z_Malloc: failed on allocation of %i bytes from the %s zone",
size, zone == smallzone ? "small" : "main");
#endif
return NULL;
}
if (rover->tag) {
base = rover = rover->next;
} else {
rover = rover->next;
}
} while (base->tag || base->size < size);
//
// found a block big enough
//
extra = base->size - size;
if (extra > MINFRAGMENT) {
// there will be a free fragment after the allocated block
new = (memblock_t *) ((byte *)base + size );
new->size = extra;
new->tag = 0; // free block
new->prev = base;
new->id = ZONEID;
new->next = base->next;
new->next->prev = new;
base->next = new;
base->size = size;
}
base->tag = tag; // no longer a free block
zone->rover = base->next; // next allocation will start looking here
zone->used += base->size; //
base->id = ZONEID;
#ifdef ZONE_DEBUG
base->d.label = label;
base->d.file = file;
base->d.line = line;
base->d.allocSize = allocSize;
#endif
// marker for memory trash testing
*(int *)((byte *)base + base->size - 4) = ZONEID;
return (void *) ((byte *)base + sizeof(memblock_t));
}
/*
========================
Z_Malloc
========================
*/
#ifdef ZONE_DEBUG
void *Z_MallocDebug( int size, char *label, char *file, int line ) {
#else
void *Z_Malloc( int size ) {
#endif
void *buf;
//Z_CheckHeap (); // DEBUG
#ifdef ZONE_DEBUG
buf = Z_TagMallocDebug( size, TAG_GENERAL, label, file, line );
#else
buf = Z_TagMalloc( size, TAG_GENERAL );
#endif
Com_Memset( buf, 0, size );
return buf;
}
#ifdef ZONE_DEBUG
void *S_MallocDebug( int size, char *label, char *file, int line ) {
return Z_TagMallocDebug( size, TAG_SMALL, label, file, line );
}
#else
void *S_Malloc( int size ) {
return Z_TagMalloc( size, TAG_SMALL );
}
#endif
/*
========================
Z_CheckHeap
========================
*/
void Z_CheckHeap( void ) {
memblock_t *block;
for (block = mainzone->blocklist.next ; ; block = block->next) {
if (block->next == &mainzone->blocklist) {
break; // all blocks have been hit
}
if ( (byte *)block + block->size != (byte *)block->next)
Com_Error( ERR_FATAL, "Z_CheckHeap: block size does not touch the next block" );
if ( block->next->prev != block) {
Com_Error( ERR_FATAL, "Z_CheckHeap: next block doesn't have proper back link" );
}
if ( !block->tag && !block->next->tag ) {
Com_Error( ERR_FATAL, "Z_CheckHeap: two consecutive free blocks" );
}
}
}
/*
========================
Z_LogZoneHeap
========================
*/
void Z_LogZoneHeap( memzone_t *zone, char *name ) {
#ifdef ZONE_DEBUG
char dump[32], *ptr;
int i, j;
#endif
memblock_t *block;
char buf[4096];
int size, allocSize, numBlocks;
if (!logfile || !FS_Initialized())
return;
size = numBlocks = 0;
#ifdef ZONE_DEBUG
allocSize = 0;
#endif
Com_sprintf(buf, sizeof(buf), "\r\n================\r\n%s log\r\n================\r\n", name);
FS_Write(buf, strlen(buf), logfile);
for (block = zone->blocklist.next ; block->next != &zone->blocklist; block = block->next) {
if (block->tag) {
#ifdef ZONE_DEBUG
ptr = ((char *) block) + sizeof(memblock_t);
j = 0;
for (i = 0; i < 20 && i < block->d.allocSize; i++) {
if (ptr[i] >= 32 && ptr[i] < 127) {
dump[j++] = ptr[i];
}
else {
dump[j++] = '_';
}
}
dump[j] = '\0';
Com_sprintf(buf, sizeof(buf), "size = %8d: %s, line: %d (%s) [%s]\r\n", block->d.allocSize, block->d.file, block->d.line, block->d.label, dump);
FS_Write(buf, strlen(buf), logfile);
allocSize += block->d.allocSize;
#endif
size += block->size;
numBlocks++;
}
}
#ifdef ZONE_DEBUG
// subtract debug memory
size -= numBlocks * sizeof(zonedebug_t);
#else
allocSize = numBlocks * sizeof(memblock_t); // + 32 bit alignment
#endif
Com_sprintf(buf, sizeof(buf), "%d %s memory in %d blocks\r\n", size, name, numBlocks);
FS_Write(buf, strlen(buf), logfile);
Com_sprintf(buf, sizeof(buf), "%d %s memory overhead\r\n", size - allocSize, name);
FS_Write(buf, strlen(buf), logfile);
}
/*
========================
Z_LogHeap
========================
*/
void Z_LogHeap( void ) {
Z_LogZoneHeap( mainzone, "MAIN" );
Z_LogZoneHeap( smallzone, "SMALL" );
}
// static mem blocks to reduce a lot of small zone overhead
typedef struct memstatic_s {
memblock_t b;
byte mem[2];
} memstatic_t;
memstatic_t emptystring =
{ {(sizeof(memblock_t)+2 + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'\0', '\0'} };
memstatic_t numberstring[] = {
{ {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'0', '\0'} },
{ {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'1', '\0'} },
{ {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'2', '\0'} },
{ {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'3', '\0'} },
{ {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'4', '\0'} },
{ {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'5', '\0'} },
{ {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'6', '\0'} },
{ {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'7', '\0'} },
{ {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'8', '\0'} },
{ {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'9', '\0'} }
};
/*
========================
CopyString
NOTE: never write over the memory CopyString returns because
memory from a memstatic_t might be returned
========================
*/
char *CopyString( const char *in ) {
char *out;
if (!in[0]) {
return ((char *)&emptystring) + sizeof(memblock_t);
}
else if (!in[1]) {
if (in[0] >= '0' && in[0] <= '9') {
return ((char *)&numberstring[in[0]-'0']) + sizeof(memblock_t);
}
}
out = S_Malloc (strlen(in)+1);
strcpy (out, in);
return out;
}
/*
==============================================================================
Goals:
reproducable without history effects -- no out of memory errors on weird map to map changes
allow restarting of the client without fragmentation
minimize total pages in use at run time
minimize total pages needed during load time
Single block of memory with stack allocators coming from both ends towards the middle.
One side is designated the temporary memory allocator.
Temporary memory can be allocated and freed in any order.
A highwater mark is kept of the most in use at any time.
When there is no temporary memory allocated, the permanent and temp sides
can be switched, allowing the already touched temp memory to be used for
permanent storage.
Temp memory must never be allocated on two ends at once, or fragmentation
could occur.
If we have any in-use temp memory, additional temp allocations must come from
that side.
If not, we can choose to make either side the new temp side and push future
permanent allocations to the other side. Permanent allocations should be
kept on the side that has the current greatest wasted highwater mark.
==============================================================================
*/
#define HUNK_MAGIC 0x89537892
#define HUNK_FREE_MAGIC 0x89537893
typedef struct {
int magic;
int size;
} hunkHeader_t;
typedef struct {
int mark;
int permanent;
int temp;
int tempHighwater;
} hunkUsed_t;
typedef struct hunkblock_s {
int size;
byte printed;
struct hunkblock_s *next;
char *label;
char *file;
int line;
} hunkblock_t;
static hunkblock_t *hunkblocks;
static hunkUsed_t hunk_low, hunk_high;
static hunkUsed_t *hunk_permanent, *hunk_temp;
static byte *s_hunkData = NULL;
static int s_hunkTotal;
static int s_zoneTotal;
static int s_smallZoneTotal;
/*
=================
Com_Meminfo_f
=================
*/
void Com_Meminfo_f( void ) {
memblock_t *block;
int zoneBytes, zoneBlocks;
int smallZoneBytes, smallZoneBlocks;
int botlibBytes, rendererBytes;
int unused;
zoneBytes = 0;
botlibBytes = 0;
rendererBytes = 0;
zoneBlocks = 0;
for (block = mainzone->blocklist.next ; ; block = block->next) {
if ( Cmd_Argc() != 1 ) {
Com_Printf ("block:%p size:%7i tag:%3i\n",
(void *)block, block->size, block->tag);
}
if ( block->tag ) {
zoneBytes += block->size;
zoneBlocks++;
if ( block->tag == TAG_BOTLIB ) {
botlibBytes += block->size;
} else if ( block->tag == TAG_RENDERER ) {
rendererBytes += block->size;
}
}
if (block->next == &mainzone->blocklist) {
break; // all blocks have been hit
}
if ( (byte *)block + block->size != (byte *)block->next) {
Com_Printf ("ERROR: block size does not touch the next block\n");
}
if ( block->next->prev != block) {
Com_Printf ("ERROR: next block doesn't have proper back link\n");
}
if ( !block->tag && !block->next->tag ) {
Com_Printf ("ERROR: two consecutive free blocks\n");
}
}
smallZoneBytes = 0;
smallZoneBlocks = 0;
for (block = smallzone->blocklist.next ; ; block = block->next) {
if ( block->tag ) {
smallZoneBytes += block->size;
smallZoneBlocks++;
}
if (block->next == &smallzone->blocklist) {
break; // all blocks have been hit
}
}
Com_Printf( "%8i bytes total hunk\n", s_hunkTotal );
Com_Printf( "%8i bytes total zone\n", s_zoneTotal );
Com_Printf( "\n" );
Com_Printf( "%8i low mark\n", hunk_low.mark );
Com_Printf( "%8i low permanent\n", hunk_low.permanent );
if ( hunk_low.temp != hunk_low.permanent ) {
Com_Printf( "%8i low temp\n", hunk_low.temp );
}
Com_Printf( "%8i low tempHighwater\n", hunk_low.tempHighwater );
Com_Printf( "\n" );
Com_Printf( "%8i high mark\n", hunk_high.mark );
Com_Printf( "%8i high permanent\n", hunk_high.permanent );
if ( hunk_high.temp != hunk_high.permanent ) {
Com_Printf( "%8i high temp\n", hunk_high.temp );
}
Com_Printf( "%8i high tempHighwater\n", hunk_high.tempHighwater );
Com_Printf( "\n" );
Com_Printf( "%8i total hunk in use\n", hunk_low.permanent + hunk_high.permanent );
unused = 0;
if ( hunk_low.tempHighwater > hunk_low.permanent ) {
unused += hunk_low.tempHighwater - hunk_low.permanent;
}
if ( hunk_high.tempHighwater > hunk_high.permanent ) {
unused += hunk_high.tempHighwater - hunk_high.permanent;
}
Com_Printf( "%8i unused highwater\n", unused );
Com_Printf( "\n" );
Com_Printf( "%8i bytes in %i zone blocks\n", zoneBytes, zoneBlocks );
Com_Printf( " %8i bytes in dynamic botlib\n", botlibBytes );
Com_Printf( " %8i bytes in dynamic renderer\n", rendererBytes );
Com_Printf( " %8i bytes in dynamic other\n", zoneBytes - ( botlibBytes + rendererBytes ) );
Com_Printf( " %8i bytes in small Zone memory\n", smallZoneBytes );
}
/*
===============
Com_TouchMemory
Touch all known used data to make sure it is paged in
===============
*/
void Com_TouchMemory( void ) {
int start, end;
int i, j;
int sum;
memblock_t *block;
Z_CheckHeap();
start = Sys_Milliseconds();
sum = 0;
j = hunk_low.permanent >> 2;
for ( i = 0 ; i < j ; i+=64 ) { // only need to touch each page
sum += ((int *)s_hunkData)[i];
}
i = ( s_hunkTotal - hunk_high.permanent ) >> 2;
j = hunk_high.permanent >> 2;
for ( ; i < j ; i+=64 ) { // only need to touch each page
sum += ((int *)s_hunkData)[i];
}
for (block = mainzone->blocklist.next ; ; block = block->next) {
if ( block->tag ) {
j = block->size >> 2;
for ( i = 0 ; i < j ; i+=64 ) { // only need to touch each page
sum += ((int *)block)[i];
}
}
if ( block->next == &mainzone->blocklist ) {
break; // all blocks have been hit
}
}
end = Sys_Milliseconds();
Com_Printf( "Com_TouchMemory: %i msec\n", end - start );
}
/*
=================
Com_InitZoneMemory
=================
*/
void Com_InitSmallZoneMemory( void ) {
s_smallZoneTotal = 512 * 1024;
smallzone = calloc( s_smallZoneTotal, 1 );
if ( !smallzone ) {
Com_Error( ERR_FATAL, "Small zone data failed to allocate %1.1f megs", (float)s_smallZoneTotal / (1024*1024) );
}
Z_ClearZone( smallzone, s_smallZoneTotal );
}
void Com_InitZoneMemory( void ) {
cvar_t *cv;
// Please note: com_zoneMegs can only be set on the command line, and
// not in q3config.cfg or Com_StartupVariable, as they haven't been
// executed by this point. It's a chicken and egg problem. We need the
// memory manager configured to handle those places where you would
// configure the memory manager.
// allocate the random block zone
cv = Cvar_Get( "com_zoneMegs", DEF_COMZONEMEGS_S, CVAR_LATCH | CVAR_ARCHIVE );
if ( cv->integer < DEF_COMZONEMEGS ) {
s_zoneTotal = 1024 * 1024 * DEF_COMZONEMEGS;
} else {
s_zoneTotal = cv->integer * 1024 * 1024;
}
mainzone = calloc( s_zoneTotal, 1 );
if ( !mainzone ) {
Com_Error( ERR_FATAL, "Zone data failed to allocate %i megs", s_zoneTotal / (1024*1024) );
}
Z_ClearZone( mainzone, s_zoneTotal );
}
/*
=================
Hunk_Log
=================
*/
void Hunk_Log( void) {
hunkblock_t *block;
char buf[4096];
int size, numBlocks;
if (!logfile || !FS_Initialized())
return;
size = 0;
numBlocks = 0;
Com_sprintf(buf, sizeof(buf), "\r\n================\r\nHunk log\r\n================\r\n");
FS_Write(buf, strlen(buf), logfile);
for (block = hunkblocks ; block; block = block->next) {
#ifdef HUNK_DEBUG
Com_sprintf(buf, sizeof(buf), "size = %8d: %s, line: %d (%s)\r\n", block->size, block->file, block->line, block->label);
FS_Write(buf, strlen(buf), logfile);
#endif
size += block->size;
numBlocks++;
}
Com_sprintf(buf, sizeof(buf), "%d Hunk memory\r\n", size);
FS_Write(buf, strlen(buf), logfile);
Com_sprintf(buf, sizeof(buf), "%d hunk blocks\r\n", numBlocks);
FS_Write(buf, strlen(buf), logfile);
}
/*
=================
Hunk_SmallLog
=================
*/
void Hunk_SmallLog( void) {
hunkblock_t *block, *block2;
char buf[4096];
int size, locsize, numBlocks;
if (!logfile || !FS_Initialized())
return;
for (block = hunkblocks ; block; block = block->next) {
block->printed = qfalse;
}
size = 0;
numBlocks = 0;
Com_sprintf(buf, sizeof(buf), "\r\n================\r\nHunk Small log\r\n================\r\n");
FS_Write(buf, strlen(buf), logfile);
for (block = hunkblocks; block; block = block->next) {
if (block->printed) {
continue;
}
locsize = block->size;
for (block2 = block->next; block2; block2 = block2->next) {
if (block->line != block2->line) {
continue;
}
if (Q_stricmp(block->file, block2->file)) {
continue;
}
size += block2->size;
locsize += block2->size;
block2->printed = qtrue;
}
#ifdef HUNK_DEBUG
Com_sprintf(buf, sizeof(buf), "size = %8d: %s, line: %d (%s)\r\n", locsize, block->file, block->line, block->label);
FS_Write(buf, strlen(buf), logfile);
#endif
size += block->size;
numBlocks++;
}
Com_sprintf(buf, sizeof(buf), "%d Hunk memory\r\n", size);
FS_Write(buf, strlen(buf), logfile);
Com_sprintf(buf, sizeof(buf), "%d hunk blocks\r\n", numBlocks);
FS_Write(buf, strlen(buf), logfile);
}
/*
=================
Com_InitHunkZoneMemory
=================
*/
void Com_InitHunkMemory( void ) {
cvar_t *cv;
int nMinAlloc;
char *pMsg = NULL;
// make sure the file system has allocated and "not" freed any temp blocks
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if (FS_LoadStack() != 0) {
Com_Error( ERR_FATAL, "Hunk initialization failed. File system load stack not zero");
}
// allocate the stack based hunk allocator
cv = Cvar_Get( "com_hunkMegs", DEF_COMHUNKMEGS_S, CVAR_LATCH | CVAR_ARCHIVE );
Cvar_SetDescription(cv, "The size of the hunk memory segment");
// if we are not dedicated min allocation is 56, otherwise min is 1
if (com_dedicated && com_dedicated->integer) {
nMinAlloc = MIN_DEDICATED_COMHUNKMEGS;
pMsg = "Minimum com_hunkMegs for a dedicated server is %i, allocating %i megs.\n";
}
else {
nMinAlloc = MIN_COMHUNKMEGS;
pMsg = "Minimum com_hunkMegs is %i, allocating %i megs.\n";
}
if ( cv->integer < nMinAlloc ) {
s_hunkTotal = 1024 * 1024 * nMinAlloc;
Com_Printf(pMsg, nMinAlloc, s_hunkTotal / (1024 * 1024));
} else {
s_hunkTotal = cv->integer * 1024 * 1024;
}
s_hunkData = calloc( s_hunkTotal + 31, 1 );
if ( !s_hunkData ) {
Com_Error( ERR_FATAL, "Hunk data failed to allocate %i megs", s_hunkTotal / (1024*1024) );
}
// cacheline align
s_hunkData = (byte *) ( ( (intptr_t)s_hunkData + 31 ) & ~31 );
Hunk_Clear();
Cmd_AddCommand( "meminfo", Com_Meminfo_f );
#ifdef ZONE_DEBUG
Cmd_AddCommand( "zonelog", Z_LogHeap );
#endif
#ifdef HUNK_DEBUG
Cmd_AddCommand( "hunklog", Hunk_Log );
Cmd_AddCommand( "hunksmalllog", Hunk_SmallLog );
#endif
}
/*
====================
Hunk_MemoryRemaining
====================
*/
int Hunk_MemoryRemaining( void ) {
int low, high;
low = hunk_low.permanent > hunk_low.temp ? hunk_low.permanent : hunk_low.temp;
high = hunk_high.permanent > hunk_high.temp ? hunk_high.permanent : hunk_high.temp;
return s_hunkTotal - ( low + high );
}
/*
===================
Hunk_SetMark
The server calls this after the level and game VM have been loaded
===================
*/
void Hunk_SetMark( void ) {
hunk_low.mark = hunk_low.permanent;
hunk_high.mark = hunk_high.permanent;
}
/*
=================
Hunk_ClearToMark
The client calls this before starting a vid_restart or snd_restart
=================
*/
void Hunk_ClearToMark( void ) {
hunk_low.permanent = hunk_low.temp = hunk_low.mark;
hunk_high.permanent = hunk_high.temp = hunk_high.mark;
}
/*
=================
Hunk_CheckMark
=================
*/
qboolean Hunk_CheckMark( void ) {
if( hunk_low.mark || hunk_high.mark ) {
return qtrue;
}
return qfalse;
}
void CL_ShutdownCGame( void );
void CL_ShutdownUI( void );
void SV_ShutdownGameProgs( void );
/*
=================
Hunk_Clear
The server calls this before shutting down or loading a new map
=================
*/
void Hunk_Clear( void ) {
#ifndef DEDICATED
CL_ShutdownCGame();
CL_ShutdownUI();
#endif
SV_ShutdownGameProgs();
#ifndef DEDICATED
CIN_CloseAllVideos();
#endif
hunk_low.mark = 0;
hunk_low.permanent = 0;
hunk_low.temp = 0;
hunk_low.tempHighwater = 0;
hunk_high.mark = 0;
hunk_high.permanent = 0;
hunk_high.temp = 0;
hunk_high.tempHighwater = 0;
hunk_permanent = &hunk_low;
hunk_temp = &hunk_high;
Com_Printf( "Hunk_Clear: reset the hunk ok\n" );
VM_Clear();
#ifdef HUNK_DEBUG
hunkblocks = NULL;
#endif
}
static void Hunk_SwapBanks( void ) {
hunkUsed_t *swap;
// can't swap banks if there is any temp already allocated
if ( hunk_temp->temp != hunk_temp->permanent ) {
return;
}
// if we have a larger highwater mark on this side, start making
// our permanent allocations here and use the other side for temp
if ( hunk_temp->tempHighwater - hunk_temp->permanent >
hunk_permanent->tempHighwater - hunk_permanent->permanent ) {
swap = hunk_temp;
hunk_temp = hunk_permanent;
hunk_permanent = swap;
}
}
/*
=================
Hunk_Alloc
Allocate permanent (until the hunk is cleared) memory
=================
*/
#ifdef HUNK_DEBUG
void *Hunk_AllocDebug( int size, ha_pref preference, char *label, char *file, int line ) {
#else
void *Hunk_Alloc( int size, ha_pref preference ) {
#endif
void *buf;
if ( s_hunkData == NULL)
{
Com_Error( ERR_FATAL, "Hunk_Alloc: Hunk memory system not initialized" );
}
// can't do preference if there is any temp allocated
if (preference == h_dontcare || hunk_temp->temp != hunk_temp->permanent) {
Hunk_SwapBanks();
} else {
if (preference == h_low && hunk_permanent != &hunk_low) {
Hunk_SwapBanks();
} else if (preference == h_high && hunk_permanent != &hunk_high) {
Hunk_SwapBanks();
}
}
#ifdef HUNK_DEBUG
size += sizeof(hunkblock_t);
#endif
// round to cacheline
size = (size+31)&~31;
if ( hunk_low.temp + hunk_high.temp + size > s_hunkTotal ) {
#ifdef HUNK_DEBUG
Hunk_Log();
Hunk_SmallLog();
Com_Error(ERR_DROP, "Hunk_Alloc failed on %i: %s, line: %d (%s)", size, file, line, label);
#else
Com_Error(ERR_DROP, "Hunk_Alloc failed on %i", size);
#endif
}
if ( hunk_permanent == &hunk_low ) {
buf = (void *)(s_hunkData + hunk_permanent->permanent);
hunk_permanent->permanent += size;
} else {
hunk_permanent->permanent += size;
buf = (void *)(s_hunkData + s_hunkTotal - hunk_permanent->permanent );
}
hunk_permanent->temp = hunk_permanent->permanent;
Com_Memset( buf, 0, size );
#ifdef HUNK_DEBUG
{
hunkblock_t *block;
block = (hunkblock_t *) buf;
block->size = size - sizeof(hunkblock_t);
block->file = file;
block->label = label;
block->line = line;
block->next = hunkblocks;
hunkblocks = block;
buf = ((byte *) buf) + sizeof(hunkblock_t);
}
#endif
return buf;
}
/*
=================
Hunk_AllocateTempMemory
This is used by the file loading system.
Multiple files can be loaded in temporary memory.
When the files-in-use count reaches zero, all temp memory will be deleted
=================
*/
void *Hunk_AllocateTempMemory( int size ) {
void *buf;
hunkHeader_t *hdr;
// return a Z_Malloc'd block if the hunk has not been initialized
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( s_hunkData == NULL )
{
return Z_Malloc(size);
}
Hunk_SwapBanks();
size = PAD(size, sizeof(intptr_t)) + sizeof( hunkHeader_t );
if ( hunk_temp->temp + hunk_permanent->permanent + size > s_hunkTotal ) {
Com_Error( ERR_DROP, "Hunk_AllocateTempMemory: failed on %i", size );
}
if ( hunk_temp == &hunk_low ) {
buf = (void *)(s_hunkData + hunk_temp->temp);
hunk_temp->temp += size;
} else {
hunk_temp->temp += size;
buf = (void *)(s_hunkData + s_hunkTotal - hunk_temp->temp );
}
if ( hunk_temp->temp > hunk_temp->tempHighwater ) {
hunk_temp->tempHighwater = hunk_temp->temp;
}
hdr = (hunkHeader_t *)buf;
buf = (void *)(hdr+1);
hdr->magic = HUNK_MAGIC;
hdr->size = size;
// don't bother clearing, because we are going to load a file over it
return buf;
}
/*
==================
Hunk_FreeTempMemory
==================
*/
void Hunk_FreeTempMemory( void *buf ) {
hunkHeader_t *hdr;
// free with Z_Free if the hunk has not been initialized
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( s_hunkData == NULL )
{
Z_Free(buf);
return;
}
hdr = ( (hunkHeader_t *)buf ) - 1;
if ( hdr->magic != HUNK_MAGIC ) {
Com_Error( ERR_FATAL, "Hunk_FreeTempMemory: bad magic" );
}
hdr->magic = HUNK_FREE_MAGIC;
// this only works if the files are freed in stack order,
// otherwise the memory will stay around until Hunk_ClearTempMemory
if ( hunk_temp == &hunk_low ) {
if ( hdr == (void *)(s_hunkData + hunk_temp->temp - hdr->size ) ) {
hunk_temp->temp -= hdr->size;
} else {
Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
}
} else {
if ( hdr == (void *)(s_hunkData + s_hunkTotal - hunk_temp->temp ) ) {
hunk_temp->temp -= hdr->size;
} else {
Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
}
}
}
/*
=================
Hunk_ClearTempMemory
The temp space is no longer needed. If we have left more
touched but unused memory on this side, have future
permanent allocs use this side.
=================
*/
void Hunk_ClearTempMemory( void ) {
if ( s_hunkData != NULL ) {
hunk_temp->temp = hunk_temp->permanent;
}
}
/*
===================================================================
EVENTS AND JOURNALING
In addition to these events, .cfg files are also copied to the
journaled file
===================================================================
*/
#define MAX_PUSHED_EVENTS 1024
static int com_pushedEventsHead = 0;
static int com_pushedEventsTail = 0;
static sysEvent_t com_pushedEvents[MAX_PUSHED_EVENTS];
/*
=================
Com_InitJournaling
=================
*/
void Com_InitJournaling( void ) {
Com_StartupVariable( "journal" );
com_journal = Cvar_Get ("journal", "0", CVAR_INIT);
if ( !com_journal->integer ) {
return;
}
if ( com_journal->integer == 1 ) {
Com_Printf( "Journaling events\n");
com_journalFile = FS_FOpenFileWrite( "journal.dat" );
com_journalDataFile = FS_FOpenFileWrite( "journaldata.dat" );
} else if ( com_journal->integer == 2 ) {
Com_Printf( "Replaying journaled events\n");
FS_FOpenFileRead( "journal.dat", &com_journalFile, qtrue );
FS_FOpenFileRead( "journaldata.dat", &com_journalDataFile, qtrue );
}
if ( !com_journalFile || !com_journalDataFile ) {
Cvar_Set( "com_journal", "0" );
com_journalFile = 0;
com_journalDataFile = 0;
Com_Printf( "Couldn't open journal files\n" );
}
}
/*
========================================================================
EVENT LOOP
========================================================================
*/
#define MAX_QUEUED_EVENTS 256
#define MASK_QUEUED_EVENTS ( MAX_QUEUED_EVENTS - 1 )
static sysEvent_t eventQueue[ MAX_QUEUED_EVENTS ];
static int eventHead = 0;
static int eventTail = 0;
/*
================
Com_QueueEvent
A time of 0 will get the current time
Ptr should either be null, or point to a block of data that can
be freed by the game later.
================
*/
void Com_QueueEvent( int time, sysEventType_t type, int value, int value2, int ptrLength, void *ptr )
{
sysEvent_t *ev;
ev = &eventQueue[ eventHead & MASK_QUEUED_EVENTS ];
if ( eventHead - eventTail >= MAX_QUEUED_EVENTS )
{
Com_Printf("Com_QueueEvent: overflow\n");
// we are discarding an event, but don't leak memory
if ( ev->evPtr )
{
Z_Free( ev->evPtr );
}
eventTail++;
}
eventHead++;
if ( time == 0 )
{
time = Sys_Milliseconds();
}
ev->evTime = time;
ev->evType = type;
ev->evValue = value;
ev->evValue2 = value2;
ev->evPtrLength = ptrLength;
ev->evPtr = ptr;
}
/*
================
Com_GetSystemEvent
================
*/
sysEvent_t Com_GetSystemEvent( void )
{
sysEvent_t ev;
char *s;
// return if we have data
if ( eventHead > eventTail )
{
eventTail++;
return eventQueue[ ( eventTail - 1 ) & MASK_QUEUED_EVENTS ];
}
// check for console commands
s = Sys_ConsoleInput();
if ( s )
{
char *b;
int len;
len = strlen( s ) + 1;
b = Z_Malloc( len );
strcpy( b, s );
Com_QueueEvent( 0, SE_CONSOLE, 0, 0, len, b );
}
// return if we have data
if ( eventHead > eventTail )
{
eventTail++;
return eventQueue[ ( eventTail - 1 ) & MASK_QUEUED_EVENTS ];
}
// create an empty event to return
memset( &ev, 0, sizeof( ev ) );
ev.evTime = Sys_Milliseconds();
return ev;
}
/*
=================
Com_GetRealEvent
=================
*/
sysEvent_t Com_GetRealEvent( void ) {
int r;
sysEvent_t ev;
// either get an event from the system or the journal file
if ( com_journal->integer == 2 ) {
r = FS_Read( &ev, sizeof(ev), com_journalFile );
if ( r != sizeof(ev) ) {
Com_Error( ERR_FATAL, "Error reading from journal file" );
}
if ( ev.evPtrLength ) {
ev.evPtr = Z_Malloc( ev.evPtrLength );
r = FS_Read( ev.evPtr, ev.evPtrLength, com_journalFile );
if ( r != ev.evPtrLength ) {
Com_Error( ERR_FATAL, "Error reading from journal file" );
}
}
} else {
ev = Com_GetSystemEvent();
// write the journal value out if needed
if ( com_journal->integer == 1 ) {
r = FS_Write( &ev, sizeof(ev), com_journalFile );
if ( r != sizeof(ev) ) {
Com_Error( ERR_FATAL, "Error writing to journal file" );
}
if ( ev.evPtrLength ) {
r = FS_Write( ev.evPtr, ev.evPtrLength, com_journalFile );
if ( r != ev.evPtrLength ) {
Com_Error( ERR_FATAL, "Error writing to journal file" );
}
}
}
}
return ev;
}
/*
=================
Com_InitPushEvent
=================
*/
void Com_InitPushEvent( void ) {
// clear the static buffer array
// this requires SE_NONE to be accepted as a valid but NOP event
memset( com_pushedEvents, 0, sizeof(com_pushedEvents) );
// reset counters while we are at it
// beware: GetEvent might still return an SE_NONE from the buffer
com_pushedEventsHead = 0;
com_pushedEventsTail = 0;
}
/*
=================
Com_PushEvent
=================
*/
void Com_PushEvent( sysEvent_t *event ) {
sysEvent_t *ev;
static int printedWarning = 0;
ev = &com_pushedEvents[ com_pushedEventsHead & (MAX_PUSHED_EVENTS-1) ];
if ( com_pushedEventsHead - com_pushedEventsTail >= MAX_PUSHED_EVENTS ) {
// don't print the warning constantly, or it can give time for more...
if ( !printedWarning ) {
printedWarning = qtrue;
Com_Printf( "WARNING: Com_PushEvent overflow\n" );
}
if ( ev->evPtr ) {
Z_Free( ev->evPtr );
}
com_pushedEventsTail++;
} else {
printedWarning = qfalse;
}
*ev = *event;
com_pushedEventsHead++;
}
/*
=================
Com_GetEvent
=================
*/
sysEvent_t Com_GetEvent( void ) {
if ( com_pushedEventsHead > com_pushedEventsTail ) {
com_pushedEventsTail++;
return com_pushedEvents[ (com_pushedEventsTail-1) & (MAX_PUSHED_EVENTS-1) ];
}
return Com_GetRealEvent();
}
/*
=================
Com_RunAndTimeServerPacket
=================
*/
void Com_RunAndTimeServerPacket( netadr_t *evFrom, msg_t *buf ) {
int t1, t2, msec;
t1 = 0;
if ( com_speeds->integer ) {
t1 = Sys_Milliseconds ();
}
SV_PacketEvent( *evFrom, buf );
if ( com_speeds->integer ) {
t2 = Sys_Milliseconds ();
msec = t2 - t1;
if ( com_speeds->integer == 3 ) {
Com_Printf( "SV_PacketEvent time: %i\n", msec );
}
}
}
/*
=================
Com_EventLoop
Returns last event time
=================
*/
int Com_EventLoop( void ) {
sysEvent_t ev;
netadr_t evFrom;
byte bufData[MAX_MSGLEN];
msg_t buf;
MSG_Init( &buf, bufData, sizeof( bufData ) );
while ( 1 ) {
ev = Com_GetEvent();
// if no more events are available
if ( ev.evType == SE_NONE ) {
// manually send packet events for the loopback channel
while ( NET_GetLoopPacket( NS_CLIENT, &evFrom, &buf ) ) {
CL_PacketEvent( evFrom, &buf );
}
while ( NET_GetLoopPacket( NS_SERVER, &evFrom, &buf ) ) {
// if the server just shut down, flush the events
if ( com_sv_running->integer ) {
Com_RunAndTimeServerPacket( &evFrom, &buf );
}
}
return ev.evTime;
}
switch(ev.evType)
{
case SE_KEY:
CL_KeyEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_CHAR:
CL_CharEvent( ev.evValue );
break;
case SE_MOUSE:
CL_MouseEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_JOYSTICK_AXIS:
CL_JoystickEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_CONSOLE:
Cbuf_AddText( (char *)ev.evPtr );
Cbuf_AddText( "\n" );
break;
default:
Com_Error( ERR_FATAL, "Com_EventLoop: bad event type %i", ev.evType );
break;
}
// free any block data
if ( ev.evPtr ) {
Z_Free( ev.evPtr );
}
}
return 0; // never reached
}
/*
================
Com_Milliseconds
Can be used for profiling, but will be journaled accurately
================
*/
int Com_Milliseconds (void) {
sysEvent_t ev;
// get events and push them until we get a null event with the current time
do {
ev = Com_GetRealEvent();
if ( ev.evType != SE_NONE ) {
Com_PushEvent( &ev );
}
} while ( ev.evType != SE_NONE );
return ev.evTime;
}
//============================================================================
/*
=============
Com_Error_f
Just throw a fatal error to
test error shutdown procedures
=============
*/
static void __attribute__((__noreturn__)) Com_Error_f (void) {
if ( Cmd_Argc() > 1 ) {
Com_Error( ERR_DROP, "Testing drop error" );
} else {
Com_Error( ERR_FATAL, "Testing fatal error" );
}
}
/*
=============
Com_Freeze_f
Just freeze in place for a given number of seconds to test
error recovery
=============
*/
static void Com_Freeze_f (void) {
float s;
int start, now;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "freeze <seconds>\n" );
return;
}
s = atof( Cmd_Argv(1) );
start = Com_Milliseconds();
while ( 1 ) {
now = Com_Milliseconds();
if ( ( now - start ) * 0.001 > s ) {
break;
}
}
}
/*
=================
Com_Crash_f
A way to force a bus error for development reasons
=================
*/
static void Com_Crash_f( void ) {
* ( volatile int * ) 0 = 0x12345678;
}
/*
==================
Com_Setenv_f
For controlling environment variables
==================
*/
void Com_Setenv_f(void)
{
int argc = Cmd_Argc();
char *arg1 = Cmd_Argv(1);
if(argc > 2)
{
char *arg2 = Cmd_ArgsFrom(2);
Sys_SetEnv(arg1, arg2);
}
else if(argc == 2)
{
char *env = getenv(arg1);
if(env)
Com_Printf("%s=%s\n", arg1, env);
else
Com_Printf("%s undefined\n", arg1);
}
}
/*
==================
Com_ExecuteCfg
For controlling environment variables
==================
*/
void Com_ExecuteCfg(void)
{
Cbuf_ExecuteText(EXEC_NOW, "exec default.cfg\n");
Cbuf_Execute(); // Always execute after exec to prevent text buffer overflowing
if(!Com_SafeMode())
{
// skip the q3config.cfg and autoexec.cfg if "safe" is on the command line
Cbuf_ExecuteText(EXEC_NOW, "exec " Q3CONFIG_CFG "\n");
Cbuf_Execute();
Cbuf_ExecuteText(EXEC_NOW, "exec autoexec.cfg\n");
Cbuf_Execute();
}
}
/*
==================
Com_GameRestart
Change to a new mod properly with cleaning up cvars before switching.
==================
*/
void Com_GameRestart(int checksumFeed, qboolean disconnect)
{
// make sure no recursion can be triggered
if(!com_gameRestarting && com_fullyInitialized)
{
com_gameRestarting = qtrue;
com_gameClientRestarting = com_cl_running->integer;
// Kill server if we have one
if(com_sv_running->integer)
SV_Shutdown("Game directory changed");
if(com_gameClientRestarting)
{
if(disconnect)
CL_Disconnect(qfalse);
CL_Shutdown("Game directory changed", disconnect, qfalse);
}
FS_Restart(checksumFeed);
// Clean out any user and VM created cvars
Cvar_Restart(qtrue);
Com_ExecuteCfg();
if(disconnect)
{
// We don't want to change any network settings if gamedir
// change was triggered by a connect to server because the
// new network settings might make the connection fail.
NET_Restart_f();
}
if(com_gameClientRestarting)
{
CL_Init();
CL_StartHunkUsers(qfalse);
}
com_gameRestarting = qfalse;
com_gameClientRestarting = qfalse;
}
}
/*
==================
Com_GameRestart_f
Expose possibility to change current running mod to the user
==================
*/
void Com_GameRestart_f(void)
{
if(!FS_FilenameCompare(Cmd_Argv(1), com_basegame->string))
{
// This is the standard base game. Servers and clients should
// use "" and not the standard basegame name because this messes
// up pak file negotiation and lots of other stuff
Cvar_Set("fs_game", "");
}
else
Cvar_Set("fs_game", Cmd_Argv(1));
Com_GameRestart(0, qtrue);
}
#ifndef STANDALONE
// TTimo: centralizing the cl_cdkey stuff after I discovered a buffer overflow problem with the dedicated server version
// not sure it's necessary to have different defaults for regular and dedicated, but I don't want to risk it
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=470
#ifndef DEDICATED
char cl_cdkey[34] = " ";
#else
char cl_cdkey[34] = "123456789";
#endif
/*
=================
Com_ReadCDKey
=================
*/
qboolean CL_CDKeyValidate( const char *key, const char *checksum );
void Com_ReadCDKey( const char *filename ) {
fileHandle_t f;
char buffer[33];
char fbuffer[MAX_OSPATH];
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/q3key", filename);
FS_SV_FOpenFileRead( fbuffer, &f );
if ( !f ) {
Q_strncpyz( cl_cdkey, " ", 17 );
return;
}
Com_Memset( buffer, 0, sizeof(buffer) );
FS_Read( buffer, 16, f );
FS_FCloseFile( f );
if (CL_CDKeyValidate(buffer, NULL)) {
Q_strncpyz( cl_cdkey, buffer, 17 );
} else {
Q_strncpyz( cl_cdkey, " ", 17 );
}
}
/*
=================
Com_AppendCDKey
=================
*/
void Com_AppendCDKey( const char *filename ) {
fileHandle_t f;
char buffer[33];
char fbuffer[MAX_OSPATH];
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/q3key", filename);
FS_SV_FOpenFileRead( fbuffer, &f );
if (!f) {
Q_strncpyz( &cl_cdkey[16], " ", 17 );
return;
}
Com_Memset( buffer, 0, sizeof(buffer) );
FS_Read( buffer, 16, f );
FS_FCloseFile( f );
if (CL_CDKeyValidate(buffer, NULL)) {
strcat( &cl_cdkey[16], buffer );
} else {
Q_strncpyz( &cl_cdkey[16], " ", 17 );
}
}
#ifndef DEDICATED
/*
=================
Com_WriteCDKey
=================
*/
static void Com_WriteCDKey( const char *filename, const char *ikey ) {
fileHandle_t f;
char fbuffer[MAX_OSPATH];
char key[17];
#ifndef _WIN32
mode_t savedumask;
#endif
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/q3key", filename);
Q_strncpyz( key, ikey, 17 );
if(!CL_CDKeyValidate(key, NULL) ) {
return;
}
#ifndef _WIN32
savedumask = umask(0077);
#endif
f = FS_SV_FOpenFileWrite( fbuffer );
if ( !f ) {
Com_Printf ("Couldn't write CD key to %s.\n", fbuffer );
goto out;
}
FS_Write( key, 16, f );
FS_Printf( f, "\n// generated by quake, do not modify\r\n" );
FS_Printf( f, "// Do not give this file to ANYONE.\r\n" );
FS_Printf( f, "// id Software and Activision will NOT ask you to send this file to them.\r\n");
FS_FCloseFile( f );
out:
#ifndef _WIN32
umask(savedumask);
#else
;
#endif
}
#endif
#endif // STANDALONE
static void Com_DetectAltivec(void)
{
// Only detect if user hasn't forcibly disabled it.
if (com_altivec->integer) {
static qboolean altivec = qfalse;
static qboolean detected = qfalse;
if (!detected) {
altivec = ( Sys_GetProcessorFeatures( ) & CF_ALTIVEC );
detected = qtrue;
}
if (!altivec) {
Cvar_Set( "com_altivec", "0" ); // we don't have it! Disable support!
}
}
}
/*
=================
Com_DetectSSE
Find out whether we have SSE support for Q_ftol function
=================
*/
#if id386 || idx64
static void Com_DetectSSE(void)
{
#if !idx64
cpuFeatures_t feat;
feat = Sys_GetProcessorFeatures();
if(feat & CF_SSE)
{
if(feat & CF_SSE2)
Q_SnapVector = qsnapvectorsse;
else
Q_SnapVector = qsnapvectorx87;
Q_ftol = qftolsse;
#endif
Q_VMftol = qvmftolsse;
Com_Printf("SSE instruction set enabled\n");
#if !idx64
}
else
{
Q_ftol = qftolx87;
Q_VMftol = qvmftolx87;
Q_SnapVector = qsnapvectorx87;
Com_Printf("SSE instruction set not available\n");
}
#endif
}
#else
#define Com_DetectSSE()
#endif
/*
=================
Com_InitRand
Seed the random number generator, if possible with an OS supplied random seed.
=================
*/
static void Com_InitRand(void)
{
unsigned int seed;
if(Sys_RandomBytes((byte *) &seed, sizeof(seed)))
srand(seed);
else
srand(time(NULL));
}
/*
=================
Com_Init
=================
*/
void Com_Init( char *commandLine ) {
char *s;
int qport;
Com_Printf( "%s %s %s\n", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
if ( setjmp (abortframe) ) {
Sys_Error ("Error during initialization");
}
// Clear queues
Com_Memset( &eventQueue[ 0 ], 0, MAX_QUEUED_EVENTS * sizeof( sysEvent_t ) );
// initialize the weak pseudo-random number generator for use later.
Com_InitRand();
// do this before anything else decides to push events
Com_InitPushEvent();
Com_InitSmallZoneMemory();
Cvar_Init ();
// prepare enough of the subsystems to handle
// cvar and command buffer management
Com_ParseCommandLine( commandLine );
// Swap_Init ();
Cbuf_Init ();
Com_DetectSSE();
// override anything from the config files with command line args
Com_StartupVariable( NULL );
Com_InitZoneMemory();
Cmd_Init ();
// get the developer cvar set as early as possible
com_developer = Cvar_Get("developer", "0", CVAR_TEMP);
// done early so bind command exists
CL_InitKeyCommands();
com_standalone = Cvar_Get("com_standalone", "0", CVAR_ROM);
com_basegame = Cvar_Get("com_basegame", BASEGAME, CVAR_INIT);
com_homepath = Cvar_Get("com_homepath", "", CVAR_INIT);
if(!com_basegame->string[0])
Cvar_ForceReset("com_basegame");
FS_InitFilesystem ();
Com_InitJournaling();
// Add some commands here already so users can use them from config files
Cmd_AddCommand ("setenv", Com_Setenv_f);
if (com_developer && com_developer->integer)
{
Cmd_AddCommand ("error", Com_Error_f);
Cmd_AddCommand ("crash", Com_Crash_f);
Cmd_AddCommand ("freeze", Com_Freeze_f);
}
Cmd_AddCommand ("quit", Com_Quit_f);
Cmd_AddCommand ("changeVectors", MSG_ReportChangeVectors_f );
Cmd_AddCommand ("writeconfig", Com_WriteConfig_f );
Cmd_SetCommandCompletionFunc( "writeconfig", Cmd_CompleteCfgName );
Cmd_AddCommand("game_restart", Com_GameRestart_f);
Com_ExecuteCfg();
// override anything from the config files with command line args
Com_StartupVariable( NULL );
// get dedicated here for proper hunk megs initialization
#ifdef DEDICATED
com_dedicated = Cvar_Get ("dedicated", "1", CVAR_INIT);
Cvar_CheckRange( com_dedicated, 1, 2, qtrue );
#else
com_dedicated = Cvar_Get ("dedicated", "0", CVAR_LATCH);
Cvar_CheckRange( com_dedicated, 0, 2, qtrue );
#endif
// allocate the stack based hunk allocator
Com_InitHunkMemory();
// if any archived cvars are modified after this, we will trigger a writing
// of the config file
cvar_modifiedFlags &= ~CVAR_ARCHIVE;
//
// init commands and vars
//
com_altivec = Cvar_Get ("com_altivec", "1", CVAR_ARCHIVE);
com_maxfps = Cvar_Get ("com_maxfps", "85", CVAR_ARCHIVE);
com_blood = Cvar_Get ("com_blood", "1", CVAR_ARCHIVE);
com_logfile = Cvar_Get ("logfile", "0", CVAR_TEMP );
com_timescale = Cvar_Get ("timescale", "1", CVAR_CHEAT | CVAR_SYSTEMINFO );
com_fixedtime = Cvar_Get ("fixedtime", "0", CVAR_CHEAT);
com_showtrace = Cvar_Get ("com_showtrace", "0", CVAR_CHEAT);
com_speeds = Cvar_Get ("com_speeds", "0", 0);
com_timedemo = Cvar_Get ("timedemo", "0", CVAR_CHEAT);
com_cameraMode = Cvar_Get ("com_cameraMode", "0", CVAR_CHEAT);
cl_paused = Cvar_Get ("cl_paused", "0", CVAR_ROM);
sv_paused = Cvar_Get ("sv_paused", "0", CVAR_ROM);
cl_packetdelay = Cvar_Get ("cl_packetdelay", "0", CVAR_CHEAT);
sv_packetdelay = Cvar_Get ("sv_packetdelay", "0", CVAR_CHEAT);
com_sv_running = Cvar_Get ("sv_running", "0", CVAR_ROM);
com_cl_running = Cvar_Get ("cl_running", "0", CVAR_ROM);
com_buildScript = Cvar_Get( "com_buildScript", "0", 0 );
com_ansiColor = Cvar_Get( "com_ansiColor", "0", CVAR_ARCHIVE );
com_unfocused = Cvar_Get( "com_unfocused", "0", CVAR_ROM );
com_maxfpsUnfocused = Cvar_Get( "com_maxfpsUnfocused", "0", CVAR_ARCHIVE );
com_minimized = Cvar_Get( "com_minimized", "0", CVAR_ROM );
com_maxfpsMinimized = Cvar_Get( "com_maxfpsMinimized", "0", CVAR_ARCHIVE );
com_abnormalExit = Cvar_Get( "com_abnormalExit", "0", CVAR_ROM );
com_busyWait = Cvar_Get("com_busyWait", "0", CVAR_ARCHIVE);
Cvar_Get("com_errorMessage", "", CVAR_ROM | CVAR_NORESTART);
#ifdef CINEMATICS_INTRO
com_introPlayed = Cvar_Get( "com_introplayed", "0", CVAR_ARCHIVE);
#endif
s = va("%s %s %s", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
com_version = Cvar_Get ("version", s, CVAR_ROM | CVAR_SERVERINFO );
com_gamename = Cvar_Get("com_gamename", GAMENAME_FOR_MASTER, CVAR_SERVERINFO | CVAR_INIT);
com_protocol = Cvar_Get("com_protocol", va("%i", PROTOCOL_VERSION), CVAR_SERVERINFO | CVAR_INIT);
#ifdef LEGACY_PROTOCOL
com_legacyprotocol = Cvar_Get("com_legacyprotocol", va("%i", PROTOCOL_LEGACY_VERSION), CVAR_INIT);
// Keep for compatibility with old mods / mods that haven't updated yet.
if(com_legacyprotocol->integer > 0)
Cvar_Get("protocol", com_legacyprotocol->string, CVAR_ROM);
else
#endif
Cvar_Get("protocol", com_protocol->string, CVAR_ROM);
Sys_Init();
Sys_InitPIDFile( FS_GetCurrentGameDir() );
// Pick a random port value
Com_RandomBytes( (byte*)&qport, sizeof(int) );
Netchan_Init( qport & 0xffff );
VM_Init();
SV_Init();
com_dedicated->modified = qfalse;
#ifndef DEDICATED
CL_Init();
#endif
// set com_frameTime so that if a map is started on the
// command line it will still be able to count on com_frameTime
// being random enough for a serverid
com_frameTime = Com_Milliseconds();
// add + commands from command line
if ( !Com_AddStartupCommands() ) {
// if the user didn't give any commands, run default action
if ( !com_dedicated->integer ) {
#ifdef CINEMATICS_LOGO
Cbuf_AddText ("cinematic " CINEMATICS_LOGO "\n");
#endif
#ifdef CINEMATICS_INTRO
if( !com_introPlayed->integer ) {
Cvar_Set( com_introPlayed->name, "1" );
Cvar_Set( "nextmap", "cinematic " CINEMATICS_INTRO );
}
#endif
}
}
// start in full screen ui mode
Cvar_Set("r_uiFullScreen", "1");
CL_StartHunkUsers( qfalse );
// make sure single player is off by default
Cvar_Set("ui_singlePlayerActive", "0");
com_fullyInitialized = qtrue;
// always set the cvar, but only print the info if it makes sense.
Com_DetectAltivec();
#if idppc
Com_Printf ("Altivec support is %s\n", com_altivec->integer ? "enabled" : "disabled");
#endif
com_pipefile = Cvar_Get( "com_pipefile", "", CVAR_ARCHIVE|CVAR_LATCH );
if( com_pipefile->string[0] )
{
pipefile = FS_FCreateOpenPipeFile( com_pipefile->string );
}
Com_Printf ("--- Common Initialization Complete ---\n");
}
/*
===============
Com_ReadFromPipe
Read whatever is in com_pipefile, if anything, and execute it
===============
*/
void Com_ReadFromPipe( void )
{
static char buf[MAX_STRING_CHARS];
static int accu = 0;
int read;
if( !pipefile )
return;
while( ( read = FS_Read( buf + accu, sizeof( buf ) - accu - 1, pipefile ) ) > 0 )
{
char *brk = NULL;
int i;
for( i = accu; i < accu + read; ++i )
{
if( buf[ i ] == '\0' )
buf[ i ] = '\n';
if( buf[ i ] == '\n' || buf[ i ] == '\r' )
brk = &buf[ i + 1 ];
}
buf[ accu + read ] = '\0';
accu += read;
if( brk )
{
char tmp = *brk;
*brk = '\0';
Cbuf_ExecuteText( EXEC_APPEND, buf );
*brk = tmp;
accu -= brk - buf;
memmove( buf, brk, accu + 1 );
}
else if( accu >= sizeof( buf ) - 1 ) // full
{
Cbuf_ExecuteText( EXEC_APPEND, buf );
accu = 0;
}
}
}
//==================================================================
void Com_WriteConfigToFile( const char *filename ) {
fileHandle_t f;
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf ("Couldn't write %s.\n", filename );
return;
}
FS_Printf (f, "// generated by quake, do not modify\n");
Key_WriteBindings (f);
Cvar_WriteVariables (f);
FS_FCloseFile( f );
}
/*
===============
Com_WriteConfiguration
Writes key bindings and archived cvars to config file if modified
===============
*/
void Com_WriteConfiguration( void ) {
#if !defined(DEDICATED) && !defined(STANDALONE)
cvar_t *fs;
#endif
// if we are quiting without fully initializing, make sure
// we don't write out anything
if ( !com_fullyInitialized ) {
return;
}
if ( !(cvar_modifiedFlags & CVAR_ARCHIVE ) ) {
return;
}
cvar_modifiedFlags &= ~CVAR_ARCHIVE;
Com_WriteConfigToFile( Q3CONFIG_CFG );
// not needed for dedicated or standalone
#if !defined(DEDICATED) && !defined(STANDALONE)
fs = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
if(!com_standalone->integer)
{
if (UI_usesUniqueCDKey() && fs && fs->string[0] != 0) {
Com_WriteCDKey( fs->string, &cl_cdkey[16] );
} else {
Com_WriteCDKey( BASEGAME, cl_cdkey );
}
}
#endif
}
/*
===============
Com_WriteConfig_f
Write the config file to a specific name
===============
*/
void Com_WriteConfig_f( void ) {
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: writeconfig <filename>\n" );
return;
}
if (!COM_CompareExtension(filename, ".cfg"))
{
Com_Printf("Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n");
return;
}
Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
Com_Printf( "Writing %s.\n", filename );
Com_WriteConfigToFile( filename );
}
/*
================
Com_ModifyMsec
================
*/
int Com_ModifyMsec( int msec ) {
int clampTime;
//
// modify time for debugging values
//
if ( com_fixedtime->integer ) {
msec = com_fixedtime->integer;
} else if ( com_timescale->value ) {
msec *= com_timescale->value;
} else if (com_cameraMode->integer) {
msec *= com_timescale->value;
}
// don't let it scale below 1 msec
if ( msec < 1 && com_timescale->value) {
msec = 1;
}
if ( com_dedicated->integer ) {
// dedicated servers don't want to clamp for a much longer
// period, because it would mess up all the client's views
// of time.
if (com_sv_running->integer && msec > 500)
Com_Printf( "Hitch warning: %i msec frame time\n", msec );
clampTime = 5000;
} else
if ( !com_sv_running->integer ) {
// clients of remote servers do not want to clamp time, because
// it would skew their view of the server's time temporarily
clampTime = 5000;
} else {
// for local single player gaming
// we may want to clamp the time to prevent players from
// flying off edges when something hitches.
clampTime = 200;
}
if ( msec > clampTime ) {
msec = clampTime;
}
return msec;
}
/*
=================
Com_TimeVal
=================
*/
int Com_TimeVal(int minMsec)
{
int timeVal;
timeVal = Sys_Milliseconds() - com_frameTime;
if(timeVal >= minMsec)
timeVal = 0;
else
timeVal = minMsec - timeVal;
return timeVal;
}
/*
=================
Com_Frame
=================
*/
void Com_Frame( void ) {
int msec, minMsec;
int timeVal, timeValSV;
static int lastTime = 0, bias = 0;
int timeBeforeFirstEvents;
int timeBeforeServer;
int timeBeforeEvents;
int timeBeforeClient;
int timeAfter;
if ( setjmp (abortframe) ) {
return; // an ERR_DROP was thrown
}
timeBeforeFirstEvents =0;
timeBeforeServer =0;
timeBeforeEvents =0;
timeBeforeClient = 0;
timeAfter = 0;
// write config file if anything changed
Com_WriteConfiguration();
//
// main event loop
//
if ( com_speeds->integer ) {
timeBeforeFirstEvents = Sys_Milliseconds ();
}
// Figure out how much time we have
if(!com_timedemo->integer)
{
if(com_dedicated->integer)
minMsec = SV_FrameMsec();
else
{
if(com_minimized->integer && com_maxfpsMinimized->integer > 0)
minMsec = 1000 / com_maxfpsMinimized->integer;
else if(com_unfocused->integer && com_maxfpsUnfocused->integer > 0)
minMsec = 1000 / com_maxfpsUnfocused->integer;
else if(com_maxfps->integer > 0)
minMsec = 1000 / com_maxfps->integer;
else
minMsec = 1;
timeVal = com_frameTime - lastTime;
bias += timeVal - minMsec;
if(bias > minMsec)
bias = minMsec;
// Adjust minMsec if previous frame took too long to render so
// that framerate is stable at the requested value.
minMsec -= bias;
}
}
else
minMsec = 1;
do
{
if(com_sv_running->integer)
{
timeValSV = SV_SendQueuedPackets();
timeVal = Com_TimeVal(minMsec);
if(timeValSV < timeVal)
timeVal = timeValSV;
}
else
timeVal = Com_TimeVal(minMsec);
if(com_busyWait->integer || timeVal < 1)
NET_Sleep(0);
else
NET_Sleep(timeVal - 1);
} while(Com_TimeVal(minMsec));
lastTime = com_frameTime;
com_frameTime = Com_EventLoop();
msec = com_frameTime - lastTime;
Cbuf_Execute ();
if (com_altivec->modified)
{
Com_DetectAltivec();
com_altivec->modified = qfalse;
}
// mess with msec if needed
msec = Com_ModifyMsec(msec);
//
// server side
//
if ( com_speeds->integer ) {
timeBeforeServer = Sys_Milliseconds ();
}
SV_Frame( msec );
// if "dedicated" has been modified, start up
// or shut down the client system.
// Do this after the server may have started,
// but before the client tries to auto-connect
if ( com_dedicated->modified ) {
// get the latched value
Cvar_Get( "dedicated", "0", 0 );
com_dedicated->modified = qfalse;
if ( !com_dedicated->integer ) {
SV_Shutdown( "dedicated set to 0" );
CL_FlushMemory();
}
}
#ifndef DEDICATED
//
// client system
//
//
// run event loop a second time to get server to client packets
// without a frame of latency
//
if ( com_speeds->integer ) {
timeBeforeEvents = Sys_Milliseconds ();
}
Com_EventLoop();
Cbuf_Execute ();
//
// client side
//
if ( com_speeds->integer ) {
timeBeforeClient = Sys_Milliseconds ();
}
CL_Frame( msec );
if ( com_speeds->integer ) {
timeAfter = Sys_Milliseconds ();
}
#else
if ( com_speeds->integer ) {
timeAfter = Sys_Milliseconds ();
timeBeforeEvents = timeAfter;
timeBeforeClient = timeAfter;
}
#endif
NET_FlushPacketQueue();
//
// report timing information
//
if ( com_speeds->integer ) {
int all, sv, ev, cl;
all = timeAfter - timeBeforeServer;
sv = timeBeforeEvents - timeBeforeServer;
ev = timeBeforeServer - timeBeforeFirstEvents + timeBeforeClient - timeBeforeEvents;
cl = timeAfter - timeBeforeClient;
sv -= time_game;
cl -= time_frontend + time_backend;
Com_Printf ("frame:%i all:%3i sv:%3i ev:%3i cl:%3i gm:%3i rf:%3i bk:%3i\n",
com_frameNumber, all, sv, ev, cl, time_game, time_frontend, time_backend );
}
//
// trace optimization tracking
//
if ( com_showtrace->integer ) {
extern int c_traces, c_brush_traces, c_patch_traces;
extern int c_pointcontents;
Com_Printf ("%4i traces (%ib %ip) %4i points\n", c_traces,
c_brush_traces, c_patch_traces, c_pointcontents);
c_traces = 0;
c_brush_traces = 0;
c_patch_traces = 0;
c_pointcontents = 0;
}
Com_ReadFromPipe( );
com_frameNumber++;
}
/*
=================
Com_Shutdown
=================
*/
void Com_Shutdown (void) {
if (logfile) {
FS_FCloseFile (logfile);
logfile = 0;
}
if ( com_journalFile ) {
FS_FCloseFile( com_journalFile );
com_journalFile = 0;
}
if( pipefile ) {
FS_FCloseFile( pipefile );
FS_HomeRemove( com_pipefile->string );
}
}
/*
===========================================
command line completion
===========================================
*/
/*
==================
Field_Clear
==================
*/
void Field_Clear( field_t *edit ) {
memset(edit->buffer, 0, MAX_EDIT_LINE);
edit->cursor = 0;
edit->scroll = 0;
}
static const char *completionString;
static char shortestMatch[MAX_TOKEN_CHARS];
static int matchCount;
// field we are working on, passed to Field_AutoComplete(&g_consoleCommand for instance)
static field_t *completionField;
/*
===============
FindMatches
===============
*/
static void FindMatches( const char *s ) {
int i;
if ( Q_stricmpn( s, completionString, strlen( completionString ) ) ) {
return;
}
matchCount++;
if ( matchCount == 1 ) {
Q_strncpyz( shortestMatch, s, sizeof( shortestMatch ) );
return;
}
// cut shortestMatch to the amount common with s
for ( i = 0 ; shortestMatch[i] ; i++ ) {
if ( i >= strlen( s ) ) {
shortestMatch[i] = 0;
break;
}
if ( tolower(shortestMatch[i]) != tolower(s[i]) ) {
shortestMatch[i] = 0;
}
}
}
/*
===============
PrintMatches
===============
*/
static void PrintMatches( const char *s ) {
if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
Com_Printf( " %s\n", s );
}
}
/*
===============
PrintCvarMatches
===============
*/
static void PrintCvarMatches( const char *s ) {
char value[ TRUNCATE_LENGTH ];
if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
Com_TruncateLongString( value, Cvar_VariableString( s ) );
Com_Printf( " %s = \"%s\"\n", s, value );
}
}
/*
===============
Field_FindFirstSeparator
===============
*/
static char *Field_FindFirstSeparator( char *s )
{
int i;
for( i = 0; i < strlen( s ); i++ )
{
if( s[ i ] == ';' )
return &s[ i ];
}
return NULL;
}
/*
===============
Field_Complete
===============
*/
static qboolean Field_Complete( void )
{
int completionOffset;
if( matchCount == 0 )
return qtrue;
completionOffset = strlen( completionField->buffer ) - strlen( completionString );
Q_strncpyz( &completionField->buffer[ completionOffset ], shortestMatch,
sizeof( completionField->buffer ) - completionOffset );
completionField->cursor = strlen( completionField->buffer );
if( matchCount == 1 )
{
Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " );
completionField->cursor++;
return qtrue;
}
Com_Printf( "]%s\n", completionField->buffer );
return qfalse;
}
#ifndef DEDICATED
/*
===============
Field_CompleteKeyname
===============
*/
void Field_CompleteKeyname( void )
{
matchCount = 0;
shortestMatch[ 0 ] = 0;
Key_KeynameCompletion( FindMatches );
if( !Field_Complete( ) )
Key_KeynameCompletion( PrintMatches );
}
#endif
/*
===============
Field_CompleteFilename
===============
*/
void Field_CompleteFilename( const char *dir,
const char *ext, qboolean stripExt, qboolean allowNonPureFilesOnDisk )
{
matchCount = 0;
shortestMatch[ 0 ] = 0;
FS_FilenameCompletion( dir, ext, stripExt, FindMatches, allowNonPureFilesOnDisk );
if( !Field_Complete( ) )
FS_FilenameCompletion( dir, ext, stripExt, PrintMatches, allowNonPureFilesOnDisk );
}
/*
===============
Field_CompleteCommand
===============
*/
void Field_CompleteCommand( char *cmd,
qboolean doCommands, qboolean doCvars )
{
int completionArgument = 0;
// Skip leading whitespace and quotes
cmd = Com_SkipCharset( cmd, " \"" );
Cmd_TokenizeStringIgnoreQuotes( cmd );
completionArgument = Cmd_Argc( );
// If there is trailing whitespace on the cmd
if( *( cmd + strlen( cmd ) - 1 ) == ' ' )
{
completionString = "";
completionArgument++;
}
else
completionString = Cmd_Argv( completionArgument - 1 );
#ifndef DEDICATED
// Unconditionally add a '\' to the start of the buffer
if( completionField->buffer[ 0 ] &&
completionField->buffer[ 0 ] != '\\' )
{
if( completionField->buffer[ 0 ] != '/' )
{
// Buffer is full, refuse to complete
if( strlen( completionField->buffer ) + 1 >=
sizeof( completionField->buffer ) )
return;
memmove( &completionField->buffer[ 1 ],
&completionField->buffer[ 0 ],
strlen( completionField->buffer ) + 1 );
completionField->cursor++;
}
completionField->buffer[ 0 ] = '\\';
}
#endif
if( completionArgument > 1 )
{
const char *baseCmd = Cmd_Argv( 0 );
char *p;
#ifndef DEDICATED
// This should always be true
if( baseCmd[ 0 ] == '\\' || baseCmd[ 0 ] == '/' )
baseCmd++;
#endif
if( ( p = Field_FindFirstSeparator( cmd ) ) )
Field_CompleteCommand( p + 1, qtrue, qtrue ); // Compound command
else
Cmd_CompleteArgument( baseCmd, cmd, completionArgument );
}
else
{
if( completionString[0] == '\\' || completionString[0] == '/' )
completionString++;
matchCount = 0;
shortestMatch[ 0 ] = 0;
if( strlen( completionString ) == 0 )
return;
if( doCommands )
Cmd_CommandCompletion( FindMatches );
if( doCvars )
Cvar_CommandCompletion( FindMatches );
if( !Field_Complete( ) )
{
// run through again, printing matches
if( doCommands )
Cmd_CommandCompletion( PrintMatches );
if( doCvars )
Cvar_CommandCompletion( PrintCvarMatches );
}
}
}
/*
===============
Field_AutoComplete
Perform Tab expansion
===============
*/
void Field_AutoComplete( field_t *field )
{
completionField = field;
Field_CompleteCommand( completionField->buffer, qtrue, qtrue );
}
/*
==================
Com_RandomBytes
fills string array with len random bytes, preferably from the OS randomizer
==================
*/
void Com_RandomBytes( byte *string, int len )
{
int i;
if( Sys_RandomBytes( string, len ) )
return;
Com_Printf( "Com_RandomBytes: using weak randomization\n" );
for( i = 0; i < len; i++ )
string[i] = (unsigned char)( rand() % 256 );
}
/*
==================
Com_IsVoipTarget
Returns non-zero if given clientNum is enabled in voipTargets, zero otherwise.
If clientNum is negative return if any bit is set.
==================
*/
qboolean Com_IsVoipTarget(uint8_t *voipTargets, int voipTargetsSize, int clientNum)
{
int index;
if(clientNum < 0)
{
for(index = 0; index < voipTargetsSize; index++)
{
if(voipTargets[index])
return qtrue;
}
return qfalse;
}
index = clientNum >> 3;
if(index < voipTargetsSize)
return (voipTargets[index] & (1 << (clientNum & 0x07)));
return qfalse;
}
/*
===============
Field_CompletePlayerName
===============
*/
static qboolean Field_CompletePlayerNameFinal( qboolean whitespace )
{
int completionOffset;
if( matchCount == 0 )
return qtrue;
completionOffset = strlen( completionField->buffer ) - strlen( completionString );
Q_strncpyz( &completionField->buffer[ completionOffset ], shortestMatch,
sizeof( completionField->buffer ) - completionOffset );
completionField->cursor = strlen( completionField->buffer );
if( matchCount == 1 && whitespace )
{
Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " );
completionField->cursor++;
return qtrue;
}
return qfalse;
}
static void Name_PlayerNameCompletion( const char **names, int nameCount, void(*callback)(const char *s) )
{
int i;
for( i = 0; i < nameCount; i++ ) {
callback( names[ i ] );
}
}
qboolean Com_FieldStringToPlayerName( char *name, int length, const char *rawname )
{
char hex[5];
int i;
int ch;
if( name == NULL || rawname == NULL )
return qfalse;
if( length <= 0 )
return qtrue;
for( i = 0; *rawname && i + 1 <= length; rawname++, i++ ) {
if( *rawname == '\\' ) {
Q_strncpyz( hex, rawname + 1, sizeof(hex) );
ch = Com_HexStrToInt( hex );
if( ch > -1 ) {
name[i] = ch;
rawname += 4; //hex string length, 0xXX
} else {
name[i] = *rawname;
}
} else {
name[i] = *rawname;
}
}
name[i] = '\0';
return qtrue;
}
qboolean Com_PlayerNameToFieldString( char *str, int length, const char *name )
{
const char *p;
int i;
int x1, x2;
if( str == NULL || name == NULL )
return qfalse;
if( length <= 0 )
return qtrue;
*str = '\0';
p = name;
for( i = 0; *p != '\0'; i++, p++ )
{
if( i + 1 >= length )
break;
if( *p <= ' ' )
{
if( i + 5 + 1 >= length )
break;
x1 = *p >> 4;
x2 = *p & 15;
str[i+0] = '\\';
str[i+1] = '0';
str[i+2] = 'x';
str[i+3] = x1 > 9 ? x1 - 10 + 'a' : x1 + '0';
str[i+4] = x2 > 9 ? x2 - 10 + 'a' : x2 + '0';
i += 4;
} else {
str[i] = *p;
}
}
str[i] = '\0';
return qtrue;
}
void Field_CompletePlayerName( const char **names, int nameCount )
{
qboolean whitespace;
matchCount = 0;
shortestMatch[ 0 ] = 0;
if( nameCount <= 0 )
return;
Name_PlayerNameCompletion( names, nameCount, FindMatches );
if( completionString[0] == '\0' )
{
Com_PlayerNameToFieldString( shortestMatch, sizeof( shortestMatch ), names[ 0 ] );
}
//allow to tab player names
//if full player name switch to next player name
if( completionString[0] != '\0'
&& Q_stricmp( shortestMatch, completionString ) == 0
&& nameCount > 1 )
{
int i;
for( i = 0; i < nameCount; i++ ) {
if( Q_stricmp( names[ i ], completionString ) == 0 )
{
i++;
if( i >= nameCount )
{
i = 0;
}
Com_PlayerNameToFieldString( shortestMatch, sizeof( shortestMatch ), names[ i ] );
break;
}
}
}
if( matchCount > 1 )
{
Com_Printf( "]%s\n", completionField->buffer );
Name_PlayerNameCompletion( names, nameCount, PrintMatches );
}
whitespace = nameCount == 1? qtrue: qfalse;
if( !Field_CompletePlayerNameFinal( whitespace ) )
{
}
}
int QDECL Com_strCompare( const void *a, const void *b )
{
const char **pa = (const char **)a;
const char **pb = (const char **)b;
return strcmp( *pa, *pb );
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3229_1 |
crossvul-cpp_data_bad_3231_2 | /*
===========================================================================
Return to Castle Wolfenstein single player GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein single player GPL Source Code (RTCW SP Source Code).
RTCW SP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW SP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
// console.c
#include "client.h"
int g_console_field_width = 78;
#define COLNSOLE_COLOR COLOR_WHITE //COLOR_BLACK
#define NUM_CON_TIMES 4
//#define CON_TEXTSIZE 32768
#define CON_TEXTSIZE 65536 // (SA) DM want's more console...
typedef struct {
qboolean initialized;
short text[CON_TEXTSIZE];
int current; // line where next message will be printed
int x; // offset in current line for next print
int display; // bottom of console displays this line
int linewidth; // characters across screen
int totallines; // total lines in console scrollback
float xadjust; // for wide aspect screens
float displayFrac; // aproaches finalFrac at scr_conspeed
float finalFrac; // 0.0 to 1.0 lines of console to display
int vislines; // in scanlines
int times[NUM_CON_TIMES]; // cls.realtime time the line was generated
// for transparent notify lines
vec4_t color;
} console_t;
console_t con;
cvar_t *con_debug;
cvar_t *con_conspeed;
cvar_t *con_notifytime;
#define DEFAULT_CONSOLE_WIDTH 78
/*
================
Con_ToggleConsole_f
================
*/
void Con_ToggleConsole_f( void ) {
// Can't toggle the console when it's the only thing available
if ( clc.state == CA_DISCONNECTED && Key_GetCatcher( ) == KEYCATCH_CONSOLE ) {
return;
}
Field_Clear( &g_consoleField );
g_consoleField.widthInChars = g_console_field_width;
Con_ClearNotify();
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_CONSOLE );
}
/*
===================
Con_ToggleMenu_f
===================
*/
void Con_ToggleMenu_f( void ) {
CL_KeyEvent( K_ESCAPE, qtrue, Sys_Milliseconds() );
CL_KeyEvent( K_ESCAPE, qfalse, Sys_Milliseconds() );
}
/*
================
Con_MessageMode_f
================
*/
void Con_MessageMode_f( void ) {
chat_playerNum = -1;
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode2_f
================
*/
void Con_MessageMode2_f( void ) {
chat_playerNum = -1;
chat_team = qtrue;
Field_Clear( &chatField );
chatField.widthInChars = 25;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode3_f
================
*/
void Con_MessageMode3_f( void ) {
chat_playerNum = VM_Call( cgvm, CG_CROSSHAIR_PLAYER );
if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) {
chat_playerNum = -1;
return;
}
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode4_f
================
*/
void Con_MessageMode4_f( void ) {
chat_playerNum = VM_Call( cgvm, CG_LAST_ATTACKER );
if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) {
chat_playerNum = -1;
return;
}
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
// NERVE - SMF
/*
================
Con_StartLimboMode_f
================
*/
void Con_StartLimboMode_f( void ) {
chat_limbo = qtrue;
}
/*
================
Con_StopLimboMode_f
================
*/
void Con_StopLimboMode_f( void ) {
chat_limbo = qfalse;
}
// -NERVE - SMF
/*
================
Con_Clear_f
================
*/
void Con_Clear_f( void ) {
int i;
for ( i = 0 ; i < CON_TEXTSIZE ; i++ ) {
con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
}
Con_Bottom(); // go to end
}
/*
================
Con_Dump_f
Save the console contents out to a file
================
*/
void Con_Dump_f( void ) {
int l, x, i;
short *line;
fileHandle_t f;
int bufferlen;
char *buffer;
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: condump <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".txt" );
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf ("ERROR: couldn't open %s.\n", filename);
return;
}
Com_Printf ("Dumped console text to %s.\n", filename );
// skip empty lines
for ( l = con.current - con.totallines + 1 ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( x = 0 ; x < con.linewidth ; x++ )
if ( ( line[x] & 0xff ) != ' ' ) {
break;
}
if ( x != con.linewidth ) {
break;
}
}
#ifdef _WIN32
bufferlen = con.linewidth + 3 * sizeof ( char );
#else
bufferlen = con.linewidth + 2 * sizeof ( char );
#endif
buffer = Hunk_AllocateTempMemory( bufferlen );
// write the remaining lines
buffer[bufferlen-1] = 0;
for ( ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( i = 0; i < con.linewidth; i++ )
buffer[i] = line[i] & 0xff;
for ( x = con.linewidth - 1 ; x >= 0 ; x-- )
{
if ( buffer[x] == ' ' ) {
buffer[x] = 0;
} else {
break;
}
}
#ifdef _WIN32
Q_strcat(buffer, bufferlen, "\r\n");
#else
Q_strcat(buffer, bufferlen, "\n");
#endif
FS_Write( buffer, strlen( buffer ), f );
}
Hunk_FreeTempMemory( buffer );
FS_FCloseFile( f );
}
/*
================
Con_ClearNotify
================
*/
void Con_ClearNotify( void ) {
int i;
for ( i = 0 ; i < NUM_CON_TIMES ; i++ ) {
con.times[i] = 0;
}
}
/*
================
Con_CheckResize
If the line width has changed, reformat the buffer.
================
*/
void Con_CheckResize( void ) {
int i, j, width, oldwidth, oldtotallines, numlines, numchars;
short tbuf[CON_TEXTSIZE];
width = ( SCREEN_WIDTH / SMALLCHAR_WIDTH ) - 2;
if ( width == con.linewidth ) {
return;
}
if ( width < 1 ) { // video hasn't been initialized yet
width = DEFAULT_CONSOLE_WIDTH;
con.linewidth = width;
con.totallines = CON_TEXTSIZE / con.linewidth;
for ( i = 0; i < CON_TEXTSIZE; i++ )
con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
} else
{
oldwidth = con.linewidth;
con.linewidth = width;
oldtotallines = con.totallines;
con.totallines = CON_TEXTSIZE / con.linewidth;
numlines = oldtotallines;
if ( con.totallines < numlines ) {
numlines = con.totallines;
}
numchars = oldwidth;
if ( con.linewidth < numchars ) {
numchars = con.linewidth;
}
memcpy( tbuf, con.text, CON_TEXTSIZE * sizeof( short ) );
for ( i = 0; i < CON_TEXTSIZE; i++ )
con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
for ( i = 0 ; i < numlines ; i++ )
{
for ( j = 0 ; j < numchars ; j++ )
{
con.text[( con.totallines - 1 - i ) * con.linewidth + j] =
tbuf[( ( con.current - i + oldtotallines ) %
oldtotallines ) * oldwidth + j];
}
}
Con_ClearNotify();
}
con.current = con.totallines - 1;
con.display = con.current;
}
/*
==================
Cmd_CompleteTxtName
==================
*/
void Cmd_CompleteTxtName( char *args, int argNum ) {
if( argNum == 2 ) {
Field_CompleteFilename( "", "txt", qfalse, qtrue );
}
}
/*
================
Con_Init
================
*/
void Con_Init( void ) {
int i;
con_notifytime = Cvar_Get( "con_notifytime", "3", 0 );
con_conspeed = Cvar_Get( "scr_conspeed", "3", 0 );
con_debug = Cvar_Get( "con_debug", "0", CVAR_ARCHIVE ); //----(SA) added
Field_Clear( &g_consoleField );
g_consoleField.widthInChars = g_console_field_width;
for ( i = 0 ; i < COMMAND_HISTORY ; i++ ) {
Field_Clear( &historyEditLines[i] );
historyEditLines[i].widthInChars = g_console_field_width;
}
CL_LoadConsoleHistory( );
Cmd_AddCommand( "toggleconsole", Con_ToggleConsole_f );
Cmd_AddCommand ("togglemenu", Con_ToggleMenu_f);
Cmd_AddCommand( "messagemode", Con_MessageMode_f );
Cmd_AddCommand( "messagemode2", Con_MessageMode2_f );
Cmd_AddCommand( "messagemode3", Con_MessageMode3_f );
Cmd_AddCommand( "messagemode4", Con_MessageMode4_f );
Cmd_AddCommand( "startLimboMode", Con_StartLimboMode_f ); // NERVE - SMF
Cmd_AddCommand( "stopLimboMode", Con_StopLimboMode_f ); // NERVE - SMF
Cmd_AddCommand( "clear", Con_Clear_f );
Cmd_AddCommand( "condump", Con_Dump_f );
Cmd_SetCommandCompletionFunc( "condump", Cmd_CompleteTxtName );
}
/*
================
Con_Shutdown
================
*/
void Con_Shutdown(void)
{
Cmd_RemoveCommand("toggleconsole");
Cmd_RemoveCommand("togglemenu");
Cmd_RemoveCommand("messagemode");
Cmd_RemoveCommand("messagemode2");
Cmd_RemoveCommand("messagemode3");
Cmd_RemoveCommand("messagemode4");
Cmd_RemoveCommand("startLimboMode");
Cmd_RemoveCommand("stopLimboMode");
Cmd_RemoveCommand("clear");
Cmd_RemoveCommand("condump");
}
/*
===============
Con_Linefeed
===============
*/
void Con_Linefeed( void ) {
int i;
// mark time for transparent overlay
if ( con.current >= 0 ) {
con.times[con.current % NUM_CON_TIMES] = cls.realtime;
}
con.x = 0;
if ( con.display == con.current ) {
con.display++;
}
con.current++;
for ( i = 0; i < con.linewidth; i++ )
con.text[( con.current % con.totallines ) * con.linewidth + i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
}
/*
================
CL_ConsolePrint
Handles cursor positioning, line wrapping, etc
All console printing must go through this in order to be logged to disk
If no console is visible, the text will appear at the top of the game window
================
*/
void CL_ConsolePrint( char *txt ) {
int y, l;
unsigned char c;
unsigned short color;
// for some demos we don't want to ever show anything on the console
if ( cl_noprint && cl_noprint->integer ) {
return;
}
if ( !con.initialized ) {
con.color[0] =
con.color[1] =
con.color[2] =
con.color[3] = 1.0f;
con.linewidth = -1;
Con_CheckResize();
con.initialized = qtrue;
}
color = ColorIndex( COLNSOLE_COLOR );
while ( (c = *((unsigned char *) txt)) != 0 ) {
if ( Q_IsColorString( txt ) ) {
color = ColorIndex( *( txt + 1 ) );
txt += 2;
continue;
}
// count word length
for ( l = 0 ; l < con.linewidth ; l++ ) {
if ( txt[l] <= ' ' ) {
break;
}
}
// word wrap
if ( l != con.linewidth && ( con.x + l >= con.linewidth ) ) {
Con_Linefeed();
}
txt++;
switch ( c )
{
case '\n':
Con_Linefeed();
break;
case '\r':
con.x = 0;
break;
default: // display character and advance
y = con.current % con.totallines;
con.text[y * con.linewidth + con.x] = ( color << 8 ) | c;
con.x++;
if(con.x >= con.linewidth)
Con_Linefeed();
break;
}
}
// mark time for transparent overlay
if ( con.current >= 0 ) {
con.times[con.current % NUM_CON_TIMES] = cls.realtime;
}
}
/*
==============================================================================
DRAWING
==============================================================================
*/
/*
================
Con_DrawInput
Draw the editline after a ] prompt
================
*/
void Con_DrawInput( void ) {
int y;
if ( clc.state != CA_DISCONNECTED && !(Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ) {
return;
}
y = con.vislines - ( SMALLCHAR_HEIGHT * 2 );
re.SetColor( con.color );
SCR_DrawSmallChar( con.xadjust + 1 * SMALLCHAR_WIDTH, y, ']' );
Field_Draw( &g_consoleField, con.xadjust + 2 * SMALLCHAR_WIDTH, y,
SCREEN_WIDTH - 3 * SMALLCHAR_WIDTH, qtrue, qtrue );
}
/*
================
Con_DrawNotify
Draws the last few lines of output transparently over the game top
================
*/
void Con_DrawNotify( void ) {
int x, v;
short *text;
int i;
int time;
int skip;
int currentColor;
currentColor = 7;
re.SetColor( g_color_table[currentColor] );
v = 0;
for ( i = con.current - NUM_CON_TIMES + 1 ; i <= con.current ; i++ )
{
if ( i < 0 ) {
continue;
}
time = con.times[i % NUM_CON_TIMES];
if ( time == 0 ) {
continue;
}
time = cls.realtime - time;
if ( time > con_notifytime->value * 1000 ) {
continue;
}
text = con.text + ( i % con.totallines ) * con.linewidth;
if (cl.snap.ps.pm_type != PM_INTERMISSION && Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME) ) {
continue;
}
for ( x = 0 ; x < con.linewidth ; x++ ) {
if ( ( text[x] & 0xff ) == ' ' ) {
continue;
}
if ( ColorIndexForNumber( text[x] >> 8 ) != currentColor ) {
currentColor = ColorIndexForNumber( text[x] >> 8 );
re.SetColor( g_color_table[currentColor] );
}
SCR_DrawSmallChar( cl_conXOffset->integer + con.xadjust + ( x + 1 ) * SMALLCHAR_WIDTH, v, text[x] & 0xff );
}
v += SMALLCHAR_HEIGHT;
}
re.SetColor( NULL );
if (Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME) ) {
return;
}
// draw the chat line
if ( Key_GetCatcher( ) & KEYCATCH_MESSAGE ) {
if ( chat_team ) {
SCR_DrawBigString (8, v, "say_team:", 1.0f, qfalse );
skip = 10;
} else
{
SCR_DrawBigString (8, v, "say:", 1.0f, qfalse );
skip = 5;
}
Field_BigDraw( &chatField, skip * BIGCHAR_WIDTH, v, SCREEN_WIDTH - ( skip + 1 ) * BIGCHAR_WIDTH, qtrue, qtrue );
}
}
/*
================
Con_DrawSolidConsole
Draws the console with the solid background
================
*/
void Con_DrawSolidConsole( float frac ) {
int i, x, y;
int rows;
short *text;
int row;
int lines;
int currentColor;
vec4_t color;
lines = cls.glconfig.vidHeight * frac;
if ( lines <= 0 ) {
return;
}
if ( lines > cls.glconfig.vidHeight ) {
lines = cls.glconfig.vidHeight;
}
// on wide screens, we will center the text
con.xadjust = 0;
SCR_AdjustFrom640( &con.xadjust, NULL, NULL, NULL );
// draw the background
y = frac * SCREEN_HEIGHT;
if ( y < 1 ) {
y = 0;
} else {
SCR_DrawPic( 0, 0, SCREEN_WIDTH, y, cls.consoleShader );
if ( frac >= 0.5f ) {
color[0] = color[1] = color[2] = frac * 2.0f;
color[3] = 1.0f;
re.SetColor( color );
// draw the logo
SCR_DrawPic( 192, 70, 256, 128, cls.consoleShader2 );
re.SetColor( NULL );
}
}
color[0] = 0;
color[1] = 0;
color[2] = 0;
color[3] = 0.6f;
SCR_FillRect( 0, y, SCREEN_WIDTH, 2, color );
// draw the version number
re.SetColor( g_color_table[ColorIndex( COLNSOLE_COLOR )] );
i = strlen( Q3_VERSION );
for ( x = 0 ; x < i ; x++ ) {
SCR_DrawSmallChar( cls.glconfig.vidWidth - ( i - x + 1 ) * SMALLCHAR_WIDTH, lines - SMALLCHAR_HEIGHT, Q3_VERSION[x] );
}
// draw the text
con.vislines = lines;
rows = ( lines - SMALLCHAR_HEIGHT ) / SMALLCHAR_HEIGHT; // rows of text to draw
y = lines - ( SMALLCHAR_HEIGHT * 3 );
// draw from the bottom up
if ( con.display != con.current ) {
// draw arrows to show the buffer is backscrolled
re.SetColor( g_color_table[ColorIndex( COLOR_WHITE )] );
for ( x = 0 ; x < con.linewidth ; x += 4 )
SCR_DrawSmallChar( con.xadjust + ( x + 1 ) * SMALLCHAR_WIDTH, y, '^' );
y -= SMALLCHAR_HEIGHT;
rows--;
}
row = con.display;
if ( con.x == 0 ) {
row--;
}
currentColor = 7;
re.SetColor( g_color_table[currentColor] );
for ( i = 0 ; i < rows ; i++, y -= SMALLCHAR_HEIGHT, row-- )
{
if ( row < 0 ) {
break;
}
if ( con.current - row >= con.totallines ) {
// past scrollback wrap point
continue;
}
text = con.text + ( row % con.totallines ) * con.linewidth;
for ( x = 0 ; x < con.linewidth ; x++ ) {
if ( ( text[x] & 0xff ) == ' ' ) {
continue;
}
if ( ColorIndexForNumber( text[x] >> 8 ) != currentColor ) {
currentColor = ColorIndexForNumber( text[x] >> 8 );
re.SetColor( g_color_table[currentColor] );
}
SCR_DrawSmallChar( con.xadjust + ( x + 1 ) * SMALLCHAR_WIDTH, y, text[x] & 0xff );
}
}
// draw the input prompt, user text, and cursor if desired
Con_DrawInput();
re.SetColor( NULL );
}
/*
==================
Con_DrawConsole
==================
*/
void Con_DrawConsole( void ) {
// check for console width changes from a vid mode change
Con_CheckResize();
// if disconnected, render console full screen
switch ( clc.state ) {
case CA_UNINITIALIZED:
case CA_CONNECTING: // sending request packets to the server
case CA_CHALLENGING: // sending challenge packets to the server
case CA_CONNECTED: // netchan_t established, getting gamestate
case CA_PRIMED: // got gamestate, waiting for first frame
case CA_LOADING: // only during cgame initialization, never during main loop
if ( !con_debug->integer ) { // these are all 'no console at all' when con_debug is not set
return;
}
if ( Key_GetCatcher( ) & KEYCATCH_UI ) {
return;
}
Con_DrawSolidConsole( 1.0 );
return;
case CA_DISCONNECTED: // not talking to a server
if ( !( Key_GetCatcher( ) & KEYCATCH_UI ) ) {
Con_DrawSolidConsole( 1.0 );
return;
}
break;
case CA_ACTIVE: // game views should be displayed
if ( con.displayFrac ) {
if ( con_debug->integer == 2 ) { // 2 means draw full screen console at '~'
// Con_DrawSolidConsole( 1.0f );
Con_DrawSolidConsole( con.displayFrac * 2.0f );
return;
}
}
break;
case CA_CINEMATIC: // playing a cinematic or a static pic, not connected to a server
default:
break;
}
if ( con.displayFrac ) {
Con_DrawSolidConsole( con.displayFrac );
} else {
Con_DrawNotify(); // draw notify lines
}
}
//================================================================
/*
==================
Con_RunConsole
Scroll it up or down
==================
*/
void Con_RunConsole( void ) {
// decide on the destination height of the console
if ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) {
con.finalFrac = 0.5; // half screen
} else {
con.finalFrac = 0; // none visible
}
// scroll towards the destination height
if ( con.finalFrac < con.displayFrac ) {
con.displayFrac -= con_conspeed->value * cls.realFrametime * 0.001;
if ( con.finalFrac > con.displayFrac ) {
con.displayFrac = con.finalFrac;
}
} else if ( con.finalFrac > con.displayFrac ) {
con.displayFrac += con_conspeed->value * cls.realFrametime * 0.001;
if ( con.finalFrac < con.displayFrac ) {
con.displayFrac = con.finalFrac;
}
}
}
void Con_PageUp( void ) {
con.display -= 2;
if ( con.current - con.display >= con.totallines ) {
con.display = con.current - con.totallines + 1;
}
}
void Con_PageDown( void ) {
con.display += 2;
if ( con.display > con.current ) {
con.display = con.current;
}
}
void Con_Top( void ) {
con.display = con.totallines;
if ( con.current - con.display >= con.totallines ) {
con.display = con.current - con.totallines + 1;
}
}
void Con_Bottom( void ) {
con.display = con.current;
}
void Con_Close( void ) {
if ( !com_cl_running->integer ) {
return;
}
Field_Clear( &g_consoleField );
Con_ClearNotify();
Key_SetCatcher( Key_GetCatcher( ) & ~KEYCATCH_CONSOLE );
con.finalFrac = 0; // none visible
con.displayFrac = 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3231_2 |
crossvul-cpp_data_good_5626_0 | /*
* Virtio Support
*
* Copyright IBM, Corp. 2007
*
* Authors:
* Anthony Liguori <aliguori@us.ibm.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
*/
#include <inttypes.h>
#include "trace.h"
#include "qemu/error-report.h"
#include "hw/virtio/virtio.h"
#include "qemu/atomic.h"
#include "hw/virtio/virtio-bus.h"
/* The alignment to use between consumer and producer parts of vring.
* x86 pagesize again. */
#define VIRTIO_PCI_VRING_ALIGN 4096
typedef struct VRingDesc
{
uint64_t addr;
uint32_t len;
uint16_t flags;
uint16_t next;
} VRingDesc;
typedef struct VRingAvail
{
uint16_t flags;
uint16_t idx;
uint16_t ring[0];
} VRingAvail;
typedef struct VRingUsedElem
{
uint32_t id;
uint32_t len;
} VRingUsedElem;
typedef struct VRingUsed
{
uint16_t flags;
uint16_t idx;
VRingUsedElem ring[0];
} VRingUsed;
typedef struct VRing
{
unsigned int num;
hwaddr desc;
hwaddr avail;
hwaddr used;
} VRing;
struct VirtQueue
{
VRing vring;
hwaddr pa;
uint16_t last_avail_idx;
/* Last used index value we have signalled on */
uint16_t signalled_used;
/* Last used index value we have signalled on */
bool signalled_used_valid;
/* Notification enabled? */
bool notification;
uint16_t queue_index;
int inuse;
uint16_t vector;
void (*handle_output)(VirtIODevice *vdev, VirtQueue *vq);
VirtIODevice *vdev;
EventNotifier guest_notifier;
EventNotifier host_notifier;
};
/* virt queue functions */
static void virtqueue_init(VirtQueue *vq)
{
hwaddr pa = vq->pa;
vq->vring.desc = pa;
vq->vring.avail = pa + vq->vring.num * sizeof(VRingDesc);
vq->vring.used = vring_align(vq->vring.avail +
offsetof(VRingAvail, ring[vq->vring.num]),
VIRTIO_PCI_VRING_ALIGN);
}
static inline uint64_t vring_desc_addr(hwaddr desc_pa, int i)
{
hwaddr pa;
pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, addr);
return ldq_phys(pa);
}
static inline uint32_t vring_desc_len(hwaddr desc_pa, int i)
{
hwaddr pa;
pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, len);
return ldl_phys(pa);
}
static inline uint16_t vring_desc_flags(hwaddr desc_pa, int i)
{
hwaddr pa;
pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, flags);
return lduw_phys(pa);
}
static inline uint16_t vring_desc_next(hwaddr desc_pa, int i)
{
hwaddr pa;
pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, next);
return lduw_phys(pa);
}
static inline uint16_t vring_avail_flags(VirtQueue *vq)
{
hwaddr pa;
pa = vq->vring.avail + offsetof(VRingAvail, flags);
return lduw_phys(pa);
}
static inline uint16_t vring_avail_idx(VirtQueue *vq)
{
hwaddr pa;
pa = vq->vring.avail + offsetof(VRingAvail, idx);
return lduw_phys(pa);
}
static inline uint16_t vring_avail_ring(VirtQueue *vq, int i)
{
hwaddr pa;
pa = vq->vring.avail + offsetof(VRingAvail, ring[i]);
return lduw_phys(pa);
}
static inline uint16_t vring_used_event(VirtQueue *vq)
{
return vring_avail_ring(vq, vq->vring.num);
}
static inline void vring_used_ring_id(VirtQueue *vq, int i, uint32_t val)
{
hwaddr pa;
pa = vq->vring.used + offsetof(VRingUsed, ring[i].id);
stl_phys(pa, val);
}
static inline void vring_used_ring_len(VirtQueue *vq, int i, uint32_t val)
{
hwaddr pa;
pa = vq->vring.used + offsetof(VRingUsed, ring[i].len);
stl_phys(pa, val);
}
static uint16_t vring_used_idx(VirtQueue *vq)
{
hwaddr pa;
pa = vq->vring.used + offsetof(VRingUsed, idx);
return lduw_phys(pa);
}
static inline void vring_used_idx_set(VirtQueue *vq, uint16_t val)
{
hwaddr pa;
pa = vq->vring.used + offsetof(VRingUsed, idx);
stw_phys(pa, val);
}
static inline void vring_used_flags_set_bit(VirtQueue *vq, int mask)
{
hwaddr pa;
pa = vq->vring.used + offsetof(VRingUsed, flags);
stw_phys(pa, lduw_phys(pa) | mask);
}
static inline void vring_used_flags_unset_bit(VirtQueue *vq, int mask)
{
hwaddr pa;
pa = vq->vring.used + offsetof(VRingUsed, flags);
stw_phys(pa, lduw_phys(pa) & ~mask);
}
static inline void vring_avail_event(VirtQueue *vq, uint16_t val)
{
hwaddr pa;
if (!vq->notification) {
return;
}
pa = vq->vring.used + offsetof(VRingUsed, ring[vq->vring.num]);
stw_phys(pa, val);
}
void virtio_queue_set_notification(VirtQueue *vq, int enable)
{
vq->notification = enable;
if (vq->vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) {
vring_avail_event(vq, vring_avail_idx(vq));
} else if (enable) {
vring_used_flags_unset_bit(vq, VRING_USED_F_NO_NOTIFY);
} else {
vring_used_flags_set_bit(vq, VRING_USED_F_NO_NOTIFY);
}
if (enable) {
/* Expose avail event/used flags before caller checks the avail idx. */
smp_mb();
}
}
int virtio_queue_ready(VirtQueue *vq)
{
return vq->vring.avail != 0;
}
int virtio_queue_empty(VirtQueue *vq)
{
return vring_avail_idx(vq) == vq->last_avail_idx;
}
void virtqueue_fill(VirtQueue *vq, const VirtQueueElement *elem,
unsigned int len, unsigned int idx)
{
unsigned int offset;
int i;
trace_virtqueue_fill(vq, elem, len, idx);
offset = 0;
for (i = 0; i < elem->in_num; i++) {
size_t size = MIN(len - offset, elem->in_sg[i].iov_len);
cpu_physical_memory_unmap(elem->in_sg[i].iov_base,
elem->in_sg[i].iov_len,
1, size);
offset += size;
}
for (i = 0; i < elem->out_num; i++)
cpu_physical_memory_unmap(elem->out_sg[i].iov_base,
elem->out_sg[i].iov_len,
0, elem->out_sg[i].iov_len);
idx = (idx + vring_used_idx(vq)) % vq->vring.num;
/* Get a pointer to the next entry in the used ring. */
vring_used_ring_id(vq, idx, elem->index);
vring_used_ring_len(vq, idx, len);
}
void virtqueue_flush(VirtQueue *vq, unsigned int count)
{
uint16_t old, new;
/* Make sure buffer is written before we update index. */
smp_wmb();
trace_virtqueue_flush(vq, count);
old = vring_used_idx(vq);
new = old + count;
vring_used_idx_set(vq, new);
vq->inuse -= count;
if (unlikely((int16_t)(new - vq->signalled_used) < (uint16_t)(new - old)))
vq->signalled_used_valid = false;
}
void virtqueue_push(VirtQueue *vq, const VirtQueueElement *elem,
unsigned int len)
{
virtqueue_fill(vq, elem, len, 0);
virtqueue_flush(vq, 1);
}
static int virtqueue_num_heads(VirtQueue *vq, unsigned int idx)
{
uint16_t num_heads = vring_avail_idx(vq) - idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (num_heads > vq->vring.num) {
error_report("Guest moved used index from %u to %u",
idx, vring_avail_idx(vq));
exit(1);
}
/* On success, callers read a descriptor at vq->last_avail_idx.
* Make sure descriptor read does not bypass avail index read. */
if (num_heads) {
smp_rmb();
}
return num_heads;
}
static unsigned int virtqueue_get_head(VirtQueue *vq, unsigned int idx)
{
unsigned int head;
/* Grab the next descriptor number they're advertising, and increment
* the index we've seen. */
head = vring_avail_ring(vq, idx % vq->vring.num);
/* If their number is silly, that's a fatal mistake. */
if (head >= vq->vring.num) {
error_report("Guest says index %u is available", head);
exit(1);
}
return head;
}
static unsigned virtqueue_next_desc(hwaddr desc_pa,
unsigned int i, unsigned int max)
{
unsigned int next;
/* If this descriptor says it doesn't chain, we're done. */
if (!(vring_desc_flags(desc_pa, i) & VRING_DESC_F_NEXT))
return max;
/* Check they're not leading us off end of descriptors. */
next = vring_desc_next(desc_pa, i);
/* Make sure compiler knows to grab that: we don't want it changing! */
smp_wmb();
if (next >= max) {
error_report("Desc next is %u", next);
exit(1);
}
return next;
}
void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes,
unsigned int *out_bytes,
unsigned max_in_bytes, unsigned max_out_bytes)
{
unsigned int idx;
unsigned int total_bufs, in_total, out_total;
idx = vq->last_avail_idx;
total_bufs = in_total = out_total = 0;
while (virtqueue_num_heads(vq, idx)) {
unsigned int max, num_bufs, indirect = 0;
hwaddr desc_pa;
int i;
max = vq->vring.num;
num_bufs = total_bufs;
i = virtqueue_get_head(vq, idx++);
desc_pa = vq->vring.desc;
if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_INDIRECT) {
if (vring_desc_len(desc_pa, i) % sizeof(VRingDesc)) {
error_report("Invalid size for indirect buffer table");
exit(1);
}
/* If we've got too many, that implies a descriptor loop. */
if (num_bufs >= max) {
error_report("Looped descriptor");
exit(1);
}
/* loop over the indirect descriptor table */
indirect = 1;
max = vring_desc_len(desc_pa, i) / sizeof(VRingDesc);
num_bufs = i = 0;
desc_pa = vring_desc_addr(desc_pa, i);
}
do {
/* If we've got too many, that implies a descriptor loop. */
if (++num_bufs > max) {
error_report("Looped descriptor");
exit(1);
}
if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_WRITE) {
in_total += vring_desc_len(desc_pa, i);
} else {
out_total += vring_desc_len(desc_pa, i);
}
if (in_total >= max_in_bytes && out_total >= max_out_bytes) {
goto done;
}
} while ((i = virtqueue_next_desc(desc_pa, i, max)) != max);
if (!indirect)
total_bufs = num_bufs;
else
total_bufs++;
}
done:
if (in_bytes) {
*in_bytes = in_total;
}
if (out_bytes) {
*out_bytes = out_total;
}
}
int virtqueue_avail_bytes(VirtQueue *vq, unsigned int in_bytes,
unsigned int out_bytes)
{
unsigned int in_total, out_total;
virtqueue_get_avail_bytes(vq, &in_total, &out_total, in_bytes, out_bytes);
return in_bytes <= in_total && out_bytes <= out_total;
}
void virtqueue_map_sg(struct iovec *sg, hwaddr *addr,
size_t num_sg, int is_write)
{
unsigned int i;
hwaddr len;
for (i = 0; i < num_sg; i++) {
len = sg[i].iov_len;
sg[i].iov_base = cpu_physical_memory_map(addr[i], &len, is_write);
if (sg[i].iov_base == NULL || len != sg[i].iov_len) {
error_report("virtio: trying to map MMIO memory");
exit(1);
}
}
}
int virtqueue_pop(VirtQueue *vq, VirtQueueElement *elem)
{
unsigned int i, head, max;
hwaddr desc_pa = vq->vring.desc;
if (!virtqueue_num_heads(vq, vq->last_avail_idx))
return 0;
/* When we start there are none of either input nor output. */
elem->out_num = elem->in_num = 0;
max = vq->vring.num;
i = head = virtqueue_get_head(vq, vq->last_avail_idx++);
if (vq->vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) {
vring_avail_event(vq, vring_avail_idx(vq));
}
if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_INDIRECT) {
if (vring_desc_len(desc_pa, i) % sizeof(VRingDesc)) {
error_report("Invalid size for indirect buffer table");
exit(1);
}
/* loop over the indirect descriptor table */
max = vring_desc_len(desc_pa, i) / sizeof(VRingDesc);
desc_pa = vring_desc_addr(desc_pa, i);
i = 0;
}
/* Collect all the descriptors */
do {
struct iovec *sg;
if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_WRITE) {
if (elem->in_num >= ARRAY_SIZE(elem->in_sg)) {
error_report("Too many write descriptors in indirect table");
exit(1);
}
elem->in_addr[elem->in_num] = vring_desc_addr(desc_pa, i);
sg = &elem->in_sg[elem->in_num++];
} else {
if (elem->out_num >= ARRAY_SIZE(elem->out_sg)) {
error_report("Too many read descriptors in indirect table");
exit(1);
}
elem->out_addr[elem->out_num] = vring_desc_addr(desc_pa, i);
sg = &elem->out_sg[elem->out_num++];
}
sg->iov_len = vring_desc_len(desc_pa, i);
/* If we've got too many, that implies a descriptor loop. */
if ((elem->in_num + elem->out_num) > max) {
error_report("Looped descriptor");
exit(1);
}
} while ((i = virtqueue_next_desc(desc_pa, i, max)) != max);
/* Now map what we have collected */
virtqueue_map_sg(elem->in_sg, elem->in_addr, elem->in_num, 1);
virtqueue_map_sg(elem->out_sg, elem->out_addr, elem->out_num, 0);
elem->index = head;
vq->inuse++;
trace_virtqueue_pop(vq, elem, elem->in_num, elem->out_num);
return elem->in_num + elem->out_num;
}
/* virtio device */
static void virtio_notify_vector(VirtIODevice *vdev, uint16_t vector)
{
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->notify) {
k->notify(qbus->parent, vector);
}
}
void virtio_update_irq(VirtIODevice *vdev)
{
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
}
void virtio_set_status(VirtIODevice *vdev, uint8_t val)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
trace_virtio_set_status(vdev, val);
if (k->set_status) {
k->set_status(vdev, val);
}
vdev->status = val;
}
void virtio_reset(void *opaque)
{
VirtIODevice *vdev = opaque;
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
int i;
virtio_set_status(vdev, 0);
if (k->reset) {
k->reset(vdev);
}
vdev->guest_features = 0;
vdev->queue_sel = 0;
vdev->status = 0;
vdev->isr = 0;
vdev->config_vector = VIRTIO_NO_VECTOR;
virtio_notify_vector(vdev, vdev->config_vector);
for(i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
vdev->vq[i].vring.desc = 0;
vdev->vq[i].vring.avail = 0;
vdev->vq[i].vring.used = 0;
vdev->vq[i].last_avail_idx = 0;
vdev->vq[i].pa = 0;
vdev->vq[i].vector = VIRTIO_NO_VECTOR;
vdev->vq[i].signalled_used = 0;
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
}
}
uint32_t virtio_config_readb(VirtIODevice *vdev, uint32_t addr)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint8_t val;
if (addr + sizeof(val) > vdev->config_len) {
return (uint32_t)-1;
}
k->get_config(vdev, vdev->config);
val = ldub_p(vdev->config + addr);
return val;
}
uint32_t virtio_config_readw(VirtIODevice *vdev, uint32_t addr)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint16_t val;
if (addr + sizeof(val) > vdev->config_len) {
return (uint32_t)-1;
}
k->get_config(vdev, vdev->config);
val = lduw_p(vdev->config + addr);
return val;
}
uint32_t virtio_config_readl(VirtIODevice *vdev, uint32_t addr)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint32_t val;
if (addr + sizeof(val) > vdev->config_len) {
return (uint32_t)-1;
}
k->get_config(vdev, vdev->config);
val = ldl_p(vdev->config + addr);
return val;
}
void virtio_config_writeb(VirtIODevice *vdev, uint32_t addr, uint32_t data)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint8_t val = data;
if (addr + sizeof(val) > vdev->config_len) {
return;
}
stb_p(vdev->config + addr, val);
if (k->set_config) {
k->set_config(vdev, vdev->config);
}
}
void virtio_config_writew(VirtIODevice *vdev, uint32_t addr, uint32_t data)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint16_t val = data;
if (addr + sizeof(val) > vdev->config_len) {
return;
}
stw_p(vdev->config + addr, val);
if (k->set_config) {
k->set_config(vdev, vdev->config);
}
}
void virtio_config_writel(VirtIODevice *vdev, uint32_t addr, uint32_t data)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint32_t val = data;
if (addr + sizeof(val) > vdev->config_len) {
return;
}
stl_p(vdev->config + addr, val);
if (k->set_config) {
k->set_config(vdev, vdev->config);
}
}
void virtio_queue_set_addr(VirtIODevice *vdev, int n, hwaddr addr)
{
vdev->vq[n].pa = addr;
virtqueue_init(&vdev->vq[n]);
}
hwaddr virtio_queue_get_addr(VirtIODevice *vdev, int n)
{
return vdev->vq[n].pa;
}
int virtio_queue_get_num(VirtIODevice *vdev, int n)
{
return vdev->vq[n].vring.num;
}
int virtio_queue_get_id(VirtQueue *vq)
{
VirtIODevice *vdev = vq->vdev;
assert(vq >= &vdev->vq[0] && vq < &vdev->vq[VIRTIO_PCI_QUEUE_MAX]);
return vq - &vdev->vq[0];
}
void virtio_queue_notify_vq(VirtQueue *vq)
{
if (vq->vring.desc) {
VirtIODevice *vdev = vq->vdev;
trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
vq->handle_output(vdev, vq);
}
}
void virtio_queue_notify(VirtIODevice *vdev, int n)
{
virtio_queue_notify_vq(&vdev->vq[n]);
}
uint16_t virtio_queue_vector(VirtIODevice *vdev, int n)
{
return n < VIRTIO_PCI_QUEUE_MAX ? vdev->vq[n].vector :
VIRTIO_NO_VECTOR;
}
void virtio_queue_set_vector(VirtIODevice *vdev, int n, uint16_t vector)
{
if (n < VIRTIO_PCI_QUEUE_MAX)
vdev->vq[n].vector = vector;
}
VirtQueue *virtio_add_queue(VirtIODevice *vdev, int queue_size,
void (*handle_output)(VirtIODevice *, VirtQueue *))
{
int i;
for (i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
if (vdev->vq[i].vring.num == 0)
break;
}
if (i == VIRTIO_PCI_QUEUE_MAX || queue_size > VIRTQUEUE_MAX_SIZE)
abort();
vdev->vq[i].vring.num = queue_size;
vdev->vq[i].handle_output = handle_output;
return &vdev->vq[i];
}
void virtio_del_queue(VirtIODevice *vdev, int n)
{
if (n < 0 || n >= VIRTIO_PCI_QUEUE_MAX) {
abort();
}
vdev->vq[n].vring.num = 0;
}
void virtio_irq(VirtQueue *vq)
{
trace_virtio_irq(vq);
vq->vdev->isr |= 0x01;
virtio_notify_vector(vq->vdev, vq->vector);
}
/* Assuming a given event_idx value from the other size, if
* we have just incremented index from old to new_idx,
* should we trigger an event? */
static inline int vring_need_event(uint16_t event, uint16_t new, uint16_t old)
{
/* Note: Xen has similar logic for notification hold-off
* in include/xen/interface/io/ring.h with req_event and req_prod
* corresponding to event_idx + 1 and new respectively.
* Note also that req_event and req_prod in Xen start at 1,
* event indexes in virtio start at 0. */
return (uint16_t)(new - event - 1) < (uint16_t)(new - old);
}
static bool vring_notify(VirtIODevice *vdev, VirtQueue *vq)
{
uint16_t old, new;
bool v;
/* We need to expose used array entries before checking used event. */
smp_mb();
/* Always notify when queue is empty (when feature acknowledge) */
if (((vdev->guest_features & (1 << VIRTIO_F_NOTIFY_ON_EMPTY)) &&
!vq->inuse && vring_avail_idx(vq) == vq->last_avail_idx)) {
return true;
}
if (!(vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX))) {
return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT);
}
v = vq->signalled_used_valid;
vq->signalled_used_valid = true;
old = vq->signalled_used;
new = vq->signalled_used = vring_used_idx(vq);
return !v || vring_need_event(vring_used_event(vq), new, old);
}
void virtio_notify(VirtIODevice *vdev, VirtQueue *vq)
{
if (!vring_notify(vdev, vq)) {
return;
}
trace_virtio_notify(vdev, vq);
vdev->isr |= 0x01;
virtio_notify_vector(vdev, vq->vector);
}
void virtio_notify_config(VirtIODevice *vdev)
{
if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))
return;
vdev->isr |= 0x03;
virtio_notify_vector(vdev, vdev->config_vector);
}
void virtio_save(VirtIODevice *vdev, QEMUFile *f)
{
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
int i;
if (k->save_config) {
k->save_config(qbus->parent, f);
}
qemu_put_8s(f, &vdev->status);
qemu_put_8s(f, &vdev->isr);
qemu_put_be16s(f, &vdev->queue_sel);
qemu_put_be32s(f, &vdev->guest_features);
qemu_put_be32(f, vdev->config_len);
qemu_put_buffer(f, vdev->config, vdev->config_len);
for (i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
if (vdev->vq[i].vring.num == 0)
break;
}
qemu_put_be32(f, i);
for (i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
if (vdev->vq[i].vring.num == 0)
break;
qemu_put_be32(f, vdev->vq[i].vring.num);
qemu_put_be64(f, vdev->vq[i].pa);
qemu_put_be16s(f, &vdev->vq[i].last_avail_idx);
if (k->save_queue) {
k->save_queue(qbus->parent, i, f);
}
}
}
int virtio_set_features(VirtIODevice *vdev, uint32_t val)
{
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *vbusk = VIRTIO_BUS_GET_CLASS(qbus);
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint32_t supported_features = vbusk->get_features(qbus->parent);
bool bad = (val & ~supported_features) != 0;
val &= supported_features;
if (k->set_features) {
k->set_features(vdev, val);
}
vdev->guest_features = val;
return bad ? -1 : 0;
}
int virtio_load(VirtIODevice *vdev, QEMUFile *f)
{
int num, i, ret;
uint32_t features;
uint32_t supported_features;
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->load_config) {
ret = k->load_config(qbus->parent, f);
if (ret)
return ret;
}
qemu_get_8s(f, &vdev->status);
qemu_get_8s(f, &vdev->isr);
qemu_get_be16s(f, &vdev->queue_sel);
qemu_get_be32s(f, &features);
if (virtio_set_features(vdev, features) < 0) {
supported_features = k->get_features(qbus->parent);
error_report("Features 0x%x unsupported. Allowed features: 0x%x",
features, supported_features);
return -1;
}
vdev->config_len = qemu_get_be32(f);
qemu_get_buffer(f, vdev->config, vdev->config_len);
num = qemu_get_be32(f);
for (i = 0; i < num; i++) {
vdev->vq[i].vring.num = qemu_get_be32(f);
vdev->vq[i].pa = qemu_get_be64(f);
qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
if (vdev->vq[i].pa) {
uint16_t nheads;
virtqueue_init(&vdev->vq[i]);
nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (nheads > vdev->vq[i].vring.num) {
error_report("VQ %d size 0x%x Guest index 0x%x "
"inconsistent with Host index 0x%x: delta 0x%x",
i, vdev->vq[i].vring.num,
vring_avail_idx(&vdev->vq[i]),
vdev->vq[i].last_avail_idx, nheads);
return -1;
}
} else if (vdev->vq[i].last_avail_idx) {
error_report("VQ %d address 0x0 "
"inconsistent with Host index 0x%x",
i, vdev->vq[i].last_avail_idx);
return -1;
}
if (k->load_queue) {
ret = k->load_queue(qbus->parent, i, f);
if (ret)
return ret;
}
}
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
return 0;
}
void virtio_cleanup(VirtIODevice *vdev)
{
qemu_del_vm_change_state_handler(vdev->vmstate);
g_free(vdev->config);
g_free(vdev->vq);
}
static void virtio_vmstate_change(void *opaque, int running, RunState state)
{
VirtIODevice *vdev = opaque;
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
bool backend_run = running && (vdev->status & VIRTIO_CONFIG_S_DRIVER_OK);
vdev->vm_running = running;
if (backend_run) {
virtio_set_status(vdev, vdev->status);
}
if (k->vmstate_change) {
k->vmstate_change(qbus->parent, backend_run);
}
if (!backend_run) {
virtio_set_status(vdev, vdev->status);
}
}
void virtio_init(VirtIODevice *vdev, const char *name,
uint16_t device_id, size_t config_size)
{
int i;
vdev->device_id = device_id;
vdev->status = 0;
vdev->isr = 0;
vdev->queue_sel = 0;
vdev->config_vector = VIRTIO_NO_VECTOR;
vdev->vq = g_malloc0(sizeof(VirtQueue) * VIRTIO_PCI_QUEUE_MAX);
vdev->vm_running = runstate_is_running();
for (i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
vdev->vq[i].vector = VIRTIO_NO_VECTOR;
vdev->vq[i].vdev = vdev;
vdev->vq[i].queue_index = i;
}
vdev->name = name;
vdev->config_len = config_size;
if (vdev->config_len) {
vdev->config = g_malloc0(config_size);
} else {
vdev->config = NULL;
}
vdev->vmstate = qemu_add_vm_change_state_handler(virtio_vmstate_change,
vdev);
}
hwaddr virtio_queue_get_desc_addr(VirtIODevice *vdev, int n)
{
return vdev->vq[n].vring.desc;
}
hwaddr virtio_queue_get_avail_addr(VirtIODevice *vdev, int n)
{
return vdev->vq[n].vring.avail;
}
hwaddr virtio_queue_get_used_addr(VirtIODevice *vdev, int n)
{
return vdev->vq[n].vring.used;
}
hwaddr virtio_queue_get_ring_addr(VirtIODevice *vdev, int n)
{
return vdev->vq[n].vring.desc;
}
hwaddr virtio_queue_get_desc_size(VirtIODevice *vdev, int n)
{
return sizeof(VRingDesc) * vdev->vq[n].vring.num;
}
hwaddr virtio_queue_get_avail_size(VirtIODevice *vdev, int n)
{
return offsetof(VRingAvail, ring) +
sizeof(uint64_t) * vdev->vq[n].vring.num;
}
hwaddr virtio_queue_get_used_size(VirtIODevice *vdev, int n)
{
return offsetof(VRingUsed, ring) +
sizeof(VRingUsedElem) * vdev->vq[n].vring.num;
}
hwaddr virtio_queue_get_ring_size(VirtIODevice *vdev, int n)
{
return vdev->vq[n].vring.used - vdev->vq[n].vring.desc +
virtio_queue_get_used_size(vdev, n);
}
uint16_t virtio_queue_get_last_avail_idx(VirtIODevice *vdev, int n)
{
return vdev->vq[n].last_avail_idx;
}
void virtio_queue_set_last_avail_idx(VirtIODevice *vdev, int n, uint16_t idx)
{
vdev->vq[n].last_avail_idx = idx;
}
VirtQueue *virtio_get_queue(VirtIODevice *vdev, int n)
{
return vdev->vq + n;
}
uint16_t virtio_get_queue_index(VirtQueue *vq)
{
return vq->queue_index;
}
static void virtio_queue_guest_notifier_read(EventNotifier *n)
{
VirtQueue *vq = container_of(n, VirtQueue, guest_notifier);
if (event_notifier_test_and_clear(n)) {
virtio_irq(vq);
}
}
void virtio_queue_set_guest_notifier_fd_handler(VirtQueue *vq, bool assign,
bool with_irqfd)
{
if (assign && !with_irqfd) {
event_notifier_set_handler(&vq->guest_notifier,
virtio_queue_guest_notifier_read);
} else {
event_notifier_set_handler(&vq->guest_notifier, NULL);
}
if (!assign) {
/* Test and clear notifier before closing it,
* in case poll callback didn't have time to run. */
virtio_queue_guest_notifier_read(&vq->guest_notifier);
}
}
EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq)
{
return &vq->guest_notifier;
}
static void virtio_queue_host_notifier_read(EventNotifier *n)
{
VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
if (event_notifier_test_and_clear(n)) {
virtio_queue_notify_vq(vq);
}
}
void virtio_queue_set_host_notifier_fd_handler(VirtQueue *vq, bool assign,
bool set_handler)
{
if (assign && set_handler) {
event_notifier_set_handler(&vq->host_notifier,
virtio_queue_host_notifier_read);
} else {
event_notifier_set_handler(&vq->host_notifier, NULL);
}
if (!assign) {
/* Test and clear notifier before after disabling event,
* in case poll callback didn't have time to run. */
virtio_queue_host_notifier_read(&vq->host_notifier);
}
}
EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq)
{
return &vq->host_notifier;
}
void virtio_device_set_child_bus_name(VirtIODevice *vdev, char *bus_name)
{
if (vdev->bus_name) {
g_free(vdev->bus_name);
vdev->bus_name = NULL;
}
if (bus_name) {
vdev->bus_name = g_strdup(bus_name);
}
}
static int virtio_device_init(DeviceState *qdev)
{
VirtIODevice *vdev = VIRTIO_DEVICE(qdev);
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(qdev);
assert(k->init != NULL);
if (k->init(vdev) < 0) {
return -1;
}
virtio_bus_plug_device(vdev);
return 0;
}
static int virtio_device_exit(DeviceState *qdev)
{
VirtIODevice *vdev = VIRTIO_DEVICE(qdev);
if (vdev->bus_name) {
g_free(vdev->bus_name);
vdev->bus_name = NULL;
}
return 0;
}
static void virtio_device_class_init(ObjectClass *klass, void *data)
{
/* Set the default value here. */
DeviceClass *dc = DEVICE_CLASS(klass);
dc->init = virtio_device_init;
dc->exit = virtio_device_exit;
dc->bus_type = TYPE_VIRTIO_BUS;
}
static const TypeInfo virtio_device_info = {
.name = TYPE_VIRTIO_DEVICE,
.parent = TYPE_DEVICE,
.instance_size = sizeof(VirtIODevice),
.class_init = virtio_device_class_init,
.abstract = true,
.class_size = sizeof(VirtioDeviceClass),
};
static void virtio_register_types(void)
{
type_register_static(&virtio_device_info);
}
type_init(virtio_register_types)
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_5626_0 |
crossvul-cpp_data_good_3152_2 | /*
* Copyright (C) 2014-2016 Firejail Authors
*
* This file is part of firejail 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#define _XOPEN_SOURCE 500
#include "firejail.h"
#include <ftw.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <syslog.h>
#include <errno.h>
#include <dirent.h>
#include <grp.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <sys/wait.h>
#define MAX_GROUPS 1024
// drop privileges
// - for root group or if nogroups is set, supplementary groups are not configured
void drop_privs(int nogroups) {
EUID_ROOT();
gid_t gid = getgid();
// configure supplementary groups
if (gid == 0 || nogroups) {
if (setgroups(0, NULL) < 0)
errExit("setgroups");
if (arg_debug)
printf("Username %s, no supplementary groups\n", cfg.username);
}
else {
assert(cfg.username);
gid_t groups[MAX_GROUPS];
int ngroups = MAX_GROUPS;
int rv = getgrouplist(cfg.username, gid, groups, &ngroups);
if (arg_debug && rv) {
printf("Username %s, groups ", cfg.username);
int i;
for (i = 0; i < ngroups; i++)
printf("%u, ", groups[i]);
printf("\n");
}
if (rv == -1) {
fprintf(stderr, "Warning: cannot extract supplementary group list, dropping them\n");
if (setgroups(0, NULL) < 0)
errExit("setgroups");
}
else {
rv = setgroups(ngroups, groups);
if (rv) {
fprintf(stderr, "Warning: cannot set supplementary group list, dropping them\n");
if (setgroups(0, NULL) < 0)
errExit("setgroups");
}
}
}
// set uid/gid
if (setgid(getgid()) < 0)
errExit("setgid/getgid");
if (setuid(getuid()) < 0)
errExit("setuid/getuid");
}
int mkpath_as_root(const char* path) {
assert(path && *path);
// work on a copy of the path
char *file_path = strdup(path);
if (!file_path)
errExit("strdup");
char* p;
int done = 0;
for (p=strchr(file_path+1, '/'); p; p=strchr(p+1, '/')) {
*p='\0';
if (mkdir(file_path, 0755)==-1) {
if (errno != EEXIST) {
*p='/';
free(file_path);
return -1;
}
}
else {
if (chmod(file_path, 0755) == -1)
errExit("chmod");
if (chown(file_path, 0, 0) == -1)
errExit("chown");
done = 1;
}
*p='/';
}
if (done)
fs_logger2("mkpath", path);
free(file_path);
return 0;
}
void logsignal(int s) {
if (!arg_debug)
return;
openlog("firejail", LOG_NDELAY | LOG_PID, LOG_USER);
syslog(LOG_INFO, "Signal %d caught", s);
closelog();
}
void logmsg(const char *msg) {
if (!arg_debug)
return;
openlog("firejail", LOG_NDELAY | LOG_PID, LOG_USER);
syslog(LOG_INFO, "%s\n", msg);
closelog();
}
void logargs(int argc, char **argv) {
if (!arg_debug)
return;
int i;
int len = 0;
// calculate message length
for (i = 0; i < argc; i++)
len += strlen(argv[i]) + 1; // + ' '
// build message
char msg[len + 1];
char *ptr = msg;
for (i = 0; i < argc; i++) {
sprintf(ptr, "%s ", argv[i]);
ptr += strlen(ptr);
}
// log message
logmsg(msg);
}
void logerr(const char *msg) {
if (!arg_debug)
return;
openlog("firejail", LOG_NDELAY | LOG_PID, LOG_USER);
syslog(LOG_ERR, "%s\n", msg);
closelog();
}
// return -1 if error, 0 if no error
int copy_file(const char *srcname, const char *destname, uid_t uid, gid_t gid, mode_t mode) {
assert(srcname);
assert(destname);
// open source
int src = open(srcname, O_RDONLY);
if (src < 0) {
fprintf(stderr, "Warning: cannot open %s, file not copied\n", srcname);
return -1;
}
// open destination
int dst = open(destname, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (dst < 0) {
fprintf(stderr, "Warning: cannot open %s, file not copied\n", destname);
close(src);
return -1;
}
// copy
ssize_t len;
static const int BUFLEN = 1024;
unsigned char buf[BUFLEN];
while ((len = read(src, buf, BUFLEN)) > 0) {
int done = 0;
while (done != len) {
int rv = write(dst, buf + done, len - done);
if (rv == -1) {
close(src);
close(dst);
return -1;
}
done += rv;
}
}
if (fchown(dst, uid, gid) == -1)
errExit("fchown");
if (fchmod(dst, mode) == -1)
errExit("fchmod");
close(src);
close(dst);
return 0;
}
// return -1 if error, 0 if no error
void copy_file_as_user(const char *srcname, const char *destname, uid_t uid, gid_t gid, mode_t mode) {
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
// drop privileges
drop_privs(0);
// copy, set permissions and ownership
int rv = copy_file(srcname, destname, uid, gid, mode);
if (rv)
fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n");
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
}
// return -1 if error, 0 if no error
void touch_file_as_user(const char *fname, uid_t uid, gid_t gid, mode_t mode) {
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
// drop privileges
drop_privs(0);
FILE *fp = fopen(fname, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, uid, gid, mode);
fclose(fp);
}
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
}
// return 1 if the file is a directory
int is_dir(const char *fname) {
assert(fname);
if (*fname == '\0')
return 0;
// if fname doesn't end in '/', add one
int rv;
struct stat s;
if (fname[strlen(fname) - 1] == '/')
rv = stat(fname, &s);
else {
char *tmp;
if (asprintf(&tmp, "%s/", fname) == -1) {
fprintf(stderr, "Error: cannot allocate memory, %s:%d\n", __FILE__, __LINE__);
errExit("asprintf");
}
rv = stat(tmp, &s);
free(tmp);
}
if (rv == -1)
return 0;
if (S_ISDIR(s.st_mode))
return 1;
return 0;
}
// return 1 if the file is a link
int is_link(const char *fname) {
assert(fname);
if (*fname == '\0')
return 0;
struct stat s;
if (lstat(fname, &s) == 0) {
if (S_ISLNK(s.st_mode))
return 1;
}
return 0;
}
// remove multiple spaces and return allocated memory
char *line_remove_spaces(const char *buf) {
EUID_ASSERT();
assert(buf);
if (strlen(buf) == 0)
return NULL;
// allocate memory for the new string
char *rv = malloc(strlen(buf) + 1);
if (rv == NULL)
errExit("malloc");
// remove space at start of line
const char *ptr1 = buf;
while (*ptr1 == ' ' || *ptr1 == '\t')
ptr1++;
// copy data and remove additional spaces
char *ptr2 = rv;
int state = 0;
while (*ptr1 != '\0') {
if (*ptr1 == '\n' || *ptr1 == '\r')
break;
if (state == 0) {
if (*ptr1 != ' ' && *ptr1 != '\t')
*ptr2++ = *ptr1++;
else {
*ptr2++ = ' ';
ptr1++;
state = 1;
}
}
else { // state == 1
while (*ptr1 == ' ' || *ptr1 == '\t')
ptr1++;
state = 0;
}
}
// strip last blank character if any
if (ptr2 > rv && *(ptr2 - 1) == ' ')
--ptr2;
*ptr2 = '\0';
// if (arg_debug)
// printf("Processing line #%s#\n", rv);
return rv;
}
char *split_comma(char *str) {
EUID_ASSERT();
if (str == NULL || *str == '\0')
return NULL;
char *ptr = strchr(str, ',');
if (!ptr)
return NULL;
*ptr = '\0';
ptr++;
if (*ptr == '\0')
return NULL;
return ptr;
}
int not_unsigned(const char *str) {
EUID_ASSERT();
int rv = 0;
const char *ptr = str;
while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0') {
if (!isdigit(*ptr)) {
rv = 1;
break;
}
ptr++;
}
return rv;
}
#define BUFLEN 4096
// find the first child for this parent; return 1 if error
int find_child(pid_t parent, pid_t *child) {
EUID_ASSERT();
*child = 0; // use it to flag a found child
DIR *dir;
EUID_ROOT(); // grsecurity fix
if (!(dir = opendir("/proc"))) {
// sleep 2 seconds and try again
sleep(2);
if (!(dir = opendir("/proc"))) {
fprintf(stderr, "Error: cannot open /proc directory\n");
exit(1);
}
}
struct dirent *entry;
char *end;
while (*child == 0 && (entry = readdir(dir))) {
pid_t pid = strtol(entry->d_name, &end, 10);
if (end == entry->d_name || *end)
continue;
if (pid == parent)
continue;
// open stat file
char *file;
if (asprintf(&file, "/proc/%u/status", pid) == -1) {
perror("asprintf");
exit(1);
}
FILE *fp = fopen(file, "r");
if (!fp) {
free(file);
continue;
}
// look for firejail executable name
char buf[BUFLEN];
while (fgets(buf, BUFLEN - 1, fp)) {
if (strncmp(buf, "PPid:", 5) == 0) {
char *ptr = buf + 5;
while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t')) {
ptr++;
}
if (*ptr == '\0') {
fprintf(stderr, "Error: cannot read /proc file\n");
exit(1);
}
if (parent == atoi(ptr))
*child = pid;
break; // stop reading the file
}
}
fclose(fp);
free(file);
}
closedir(dir);
EUID_USER();
return (*child)? 0:1; // 0 = found, 1 = not found
}
void extract_command_name(int index, char **argv) {
EUID_ASSERT();
assert(argv);
assert(argv[index]);
// configure command index
cfg.original_program_index = index;
char *str = strdup(argv[index]);
if (!str)
errExit("strdup");
// if we have a symbolic link, use the real path to extract the name
// if (is_link(argv[index])) {
// char*newname = realpath(argv[index], NULL);
// if (newname) {
// free(str);
// str = newname;
// }
// }
// configure command name
cfg.command_name = str;
if (!cfg.command_name)
errExit("strdup");
// restrict the command name to the first word
char *ptr = cfg.command_name;
while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0')
ptr++;
*ptr = '\0';
// remove the path: /usr/bin/firefox becomes firefox
ptr = strrchr(cfg.command_name, '/');
if (ptr) {
ptr++;
if (*ptr == '\0') {
fprintf(stderr, "Error: invalid command name\n");
exit(1);
}
char *tmp = strdup(ptr);
if (!tmp)
errExit("strdup");
// limit the command to the first '.'
char *ptr2 = tmp;
while (*ptr2 != '.' && *ptr2 != '\0')
ptr2++;
*ptr2 = '\0';
free(cfg.command_name);
cfg.command_name = tmp;
}
}
void update_map(char *mapping, char *map_file) {
int fd;
size_t j;
size_t map_len; /* Length of 'mapping' */
/* Replace commas in mapping string with newlines */
map_len = strlen(mapping);
for (j = 0; j < map_len; j++)
if (mapping[j] == ',')
mapping[j] = '\n';
fd = open(map_file, O_RDWR);
if (fd == -1) {
fprintf(stderr, "Error: cannot open %s: %s\n", map_file, strerror(errno));
exit(EXIT_FAILURE);
}
if (write(fd, mapping, map_len) != (ssize_t)map_len) {
fprintf(stderr, "Error: cannot write to %s: %s\n", map_file, strerror(errno));
exit(EXIT_FAILURE);
}
close(fd);
}
void wait_for_other(int fd) {
//****************************
// wait for the parent to be initialized
//****************************
char childstr[BUFLEN + 1];
int newfd = dup(fd);
if (newfd == -1)
errExit("dup");
FILE* stream;
stream = fdopen(newfd, "r");
*childstr = '\0';
if (fgets(childstr, BUFLEN, stream)) {
// remove \n)
char *ptr = childstr;
while(*ptr !='\0' && *ptr != '\n')
ptr++;
if (*ptr == '\0')
errExit("fgets");
*ptr = '\0';
}
else {
fprintf(stderr, "Error: cannot establish communication with the parent, exiting...\n");
exit(1);
}
if (strcmp(childstr, "arg_noroot=0") == 0)
arg_noroot = 0;
fclose(stream);
}
void notify_other(int fd) {
FILE* stream;
int newfd = dup(fd);
if (newfd == -1)
errExit("dup");
stream = fdopen(newfd, "w");
fprintf(stream, "arg_noroot=%d\n", arg_noroot);
fflush(stream);
fclose(stream);
}
// This function takes a pathname supplied by the user and expands '~' and
// '${HOME}' at the start, to refer to a path relative to the user's home
// directory (supplied).
// The return value is allocated using malloc and must be freed by the caller.
// The function returns NULL if there are any errors.
char *expand_home(const char *path, const char* homedir) {
assert(path);
assert(homedir);
// Replace home macro
char *new_name = NULL;
if (strncmp(path, "${HOME}", 7) == 0) {
if (asprintf(&new_name, "%s%s", homedir, path + 7) == -1)
errExit("asprintf");
return new_name;
}
else if (*path == '~') {
if (asprintf(&new_name, "%s%s", homedir, path + 1) == -1)
errExit("asprintf");
return new_name;
}
return strdup(path);
}
// Equivalent to the GNU version of basename, which is incompatible with
// the POSIX basename. A few lines of code saves any portability pain.
// https://www.gnu.org/software/libc/manual/html_node/Finding-Tokens-in-a-String.html#index-basename
const char *gnu_basename(const char *path) {
const char *last_slash = strrchr(path, '/');
if (!last_slash)
return path;
return last_slash+1;
}
uid_t pid_get_uid(pid_t pid) {
EUID_ASSERT();
uid_t rv = 0;
// open status file
char *file;
if (asprintf(&file, "/proc/%u/status", pid) == -1) {
perror("asprintf");
exit(1);
}
EUID_ROOT(); // grsecurity fix
FILE *fp = fopen(file, "r");
if (!fp) {
free(file);
fprintf(stderr, "Error: cannot open /proc file\n");
exit(1);
}
// extract uid
static const int PIDS_BUFLEN = 1024;
char buf[PIDS_BUFLEN];
while (fgets(buf, PIDS_BUFLEN - 1, fp)) {
if (strncmp(buf, "Uid:", 4) == 0) {
char *ptr = buf + 5;
while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t')) {
ptr++;
}
if (*ptr == '\0')
break;
rv = atoi(ptr);
break; // break regardless!
}
}
fclose(fp);
free(file);
EUID_USER(); // grsecurity fix
if (rv == 0) {
fprintf(stderr, "Error: cannot read /proc file\n");
exit(1);
}
return rv;
}
void invalid_filename(const char *fname) {
EUID_ASSERT();
assert(fname);
const char *ptr = fname;
if (arg_debug_check_filename)
printf("Checking filename %s\n", fname);
if (strncmp(ptr, "${HOME}", 7) == 0)
ptr = fname + 7;
else if (strncmp(ptr, "${PATH}", 7) == 0)
ptr = fname + 7;
else if (strcmp(fname, "${DOWNLOADS}") == 0)
return;
int len = strlen(ptr);
// file globbing ('*') is allowed
if (strcspn(ptr, "\\&!?\"'<>%^(){}[];,") != (size_t)len) {
fprintf(stderr, "Error: \"%s\" is an invalid filename\n", ptr);
exit(1);
}
}
uid_t get_group_id(const char *group) {
// find tty group id
gid_t gid = 0;
struct group *g = getgrnam(group);
if (g)
gid = g->gr_gid;
return gid;
}
static int remove_callback(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
(void) sb;
(void) typeflag;
(void) ftwbuf;
int rv = remove(fpath);
if (rv)
perror(fpath);
return rv;
}
int remove_directory(const char *path) {
// FTW_PHYS - do not follow symbolic links
return nftw(path, remove_callback, 64, FTW_DEPTH | FTW_PHYS);
}
void flush_stdin(void) {
if (isatty(STDIN_FILENO)) {
int cnt = 0;
ioctl(STDIN_FILENO, FIONREAD, &cnt);
if (cnt) {
if (!arg_quiet)
printf("Warning: removing %d bytes from stdin\n", cnt);
ioctl(STDIN_FILENO, TCFLSH, TCIFLUSH);
}
}
}
// return 1 if error
int set_perms(const char *fname, uid_t uid, gid_t gid, mode_t mode) {
assert(fname);
if (chmod(fname, mode) == -1)
return 1;
if (chown(fname, uid, gid) == -1)
return 1;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3152_2 |
crossvul-cpp_data_bad_3228_2 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3228_2 |
crossvul-cpp_data_good_3231_1 | /*
===========================================================================
Return to Castle Wolfenstein multiplayer GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (RTCW MP Source Code).
RTCW MP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW MP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW MP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
// common.c -- misc functions used in client and server
#include "q_shared.h"
#include "qcommon.h"
#include <setjmp.h>
#ifndef _WIN32
#include <netinet/in.h>
#include <sys/stat.h> // umask
#else
#include <winsock.h>
#endif
int demo_protocols[] =
{ 59, 58, 57, 0 };
#define MAX_NUM_ARGVS 50
#define MIN_DEDICATED_COMHUNKMEGS 1
#define MIN_COMHUNKMEGS 128 // JPW NERVE changed this to 42 for MP, was 56 for team arena and 75 for wolfSP
#define DEF_COMHUNKMEGS 256 // RF, increased this, some maps are exceeding 56mb // JPW NERVE changed this for multiplayer back to 42, 56 for depot/mp_cpdepot, 42 for everything else
#define DEF_COMZONEMEGS 32 // JPW NERVE cut this back too was 30
#define DEF_COMHUNKMEGS_S XSTRING(DEF_COMHUNKMEGS)
#define DEF_COMZONEMEGS_S XSTRING(DEF_COMZONEMEGS)
int com_argc;
char *com_argv[MAX_NUM_ARGVS + 1];
jmp_buf abortframe; // an ERR_DROP occured, exit the entire frame
FILE *debuglogfile;
static fileHandle_t pipefile;
static fileHandle_t logfile;
fileHandle_t com_journalFile; // events are written here
fileHandle_t com_journalDataFile; // config files are written here
cvar_t *com_speeds;
cvar_t *com_developer;
cvar_t *com_dedicated;
cvar_t *com_timescale;
cvar_t *com_fixedtime;
cvar_t *com_journal;
cvar_t *com_maxfps;
cvar_t *com_altivec;
cvar_t *com_timedemo;
cvar_t *com_sv_running;
cvar_t *com_cl_running;
cvar_t *com_logfile; // 1 = buffer log, 2 = flush after each print
cvar_t *com_pipefile;
cvar_t *com_showtrace;
cvar_t *com_fsgame;
cvar_t *com_version;
cvar_t *com_legacyversion;
cvar_t *com_blood;
cvar_t *com_buildScript; // for automated data building scripts
#ifdef CINEMATICS_INTRO
cvar_t *com_introPlayed;
#endif
cvar_t *cl_paused;
cvar_t *sv_paused;
cvar_t *cl_packetdelay;
cvar_t *sv_packetdelay;
cvar_t *com_cameraMode;
cvar_t *com_recommendedSet;
// Rafael Notebook
cvar_t *cl_notebook;
cvar_t *com_hunkused; // Ridah
cvar_t *com_ansiColor;
cvar_t *com_unfocused;
cvar_t *com_maxfpsUnfocused;
cvar_t *com_minimized;
cvar_t *com_maxfpsMinimized;
cvar_t *com_abnormalExit;
cvar_t *com_standalone;
cvar_t *com_gamename;
cvar_t *com_protocol;
#ifdef LEGACY_PROTOCOL
cvar_t *com_legacyprotocol;
#endif
cvar_t *com_basegame;
cvar_t *com_homepath;
cvar_t *com_busyWait;
#if idx64
int (*Q_VMftol)(void);
#elif id386
long (QDECL *Q_ftol)(float f);
int (QDECL *Q_VMftol)(void);
void (QDECL *Q_SnapVector)(vec3_t vec);
#endif
// com_speeds times
int time_game;
int time_frontend; // renderer frontend time
int time_backend; // renderer backend time
int com_frameTime;
int com_frameNumber;
qboolean com_errorEntered = qfalse;
qboolean com_fullyInitialized = qfalse;
qboolean com_gameRestarting = qfalse;
qboolean com_gameClientRestarting = qfalse;
char com_errorMessage[MAXPRINTMSG];
void Com_WriteConfig_f( void );
void CIN_CloseAllVideos( void );
//============================================================================
static char *rd_buffer;
static int rd_buffersize;
static void ( *rd_flush )( char *buffer );
void Com_BeginRedirect( char *buffer, int buffersize, void ( *flush )( char *) ) {
if ( !buffer || !buffersize || !flush ) {
return;
}
rd_buffer = buffer;
rd_buffersize = buffersize;
rd_flush = flush;
*rd_buffer = 0;
}
void Com_EndRedirect( void ) {
if ( rd_flush ) {
rd_flush( rd_buffer );
}
rd_buffer = NULL;
rd_buffersize = 0;
rd_flush = NULL;
}
/*
=============
Com_Printf
Both client and server can use this, and it will output
to the apropriate place.
A raw string should NEVER be passed as fmt, because of "%f" type crashers.
=============
*/
void QDECL Com_Printf( const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
static qboolean opening_qconsole = qfalse;
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof( msg ), fmt, argptr );
va_end( argptr );
if ( rd_buffer ) {
if ( ( strlen( msg ) + strlen( rd_buffer ) ) > ( rd_buffersize - 1 ) ) {
rd_flush( rd_buffer );
*rd_buffer = 0;
}
Q_strcat( rd_buffer, rd_buffersize, msg );
// show_bug.cgi?id=51
// only flush the rcon buffer when it's necessary, avoid fragmenting
//rd_flush(rd_buffer);
//*rd_buffer = 0;
return;
}
#ifndef DEDICATED
CL_ConsolePrint( msg );
#endif
// echo to dedicated console and early console
Sys_Print( msg );
// logfile
if ( com_logfile && com_logfile->integer ) {
// TTimo: only open the qconsole.log if the filesystem is in an initialized state
// also, avoid recursing in the qconsole.log opening (i.e. if fs_debug is on)
if ( !logfile && FS_Initialized() && !opening_qconsole ) {
struct tm *newtime;
time_t aclock;
opening_qconsole = qtrue;
time( &aclock );
newtime = localtime( &aclock );
logfile = FS_FOpenFileWrite( "rtcwconsole.log" );
if(logfile)
{
Com_Printf( "logfile opened on %s\n", asctime( newtime ) );
if ( com_logfile->integer > 1 )
{
// force it to not buffer so we get valid
// data even if we are crashing
FS_ForceFlush(logfile);
}
}
else
{
Com_Printf("Opening rtcwconsole.log failed!\n");
Cvar_SetValue("logfile", 0);
}
opening_qconsole = qfalse;
}
if ( logfile && FS_Initialized() ) {
FS_Write( msg, strlen( msg ), logfile );
}
}
}
/*
================
Com_DPrintf
A Com_Printf that only shows up if the "developer" cvar is set
================
*/
void QDECL Com_DPrintf( const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
if ( !com_developer || !com_developer->integer ) {
return; // don't confuse non-developers with techie stuff...
}
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof( msg ), fmt, argptr );
va_end( argptr );
Com_Printf( "%s", msg );
}
/*
=============
Com_Error
Both client and server can use this, and it will
do the appropriate thing.
=============
*/
void QDECL Com_Error( int code, const char *fmt, ... ) {
va_list argptr;
static int lastErrorTime;
static int errorCount;
int currentTime;
qboolean restartClient;
if(com_errorEntered)
Sys_Error("recursive error after: %s", com_errorMessage);
com_errorEntered = qtrue;
Cvar_Set("com_errorCode", va("%i", code));
// when we are running automated scripts, make sure we
// know if anything failed
if ( com_buildScript && com_buildScript->integer ) {
code = ERR_FATAL;
}
// if we are getting a solid stream of ERR_DROP, do an ERR_FATAL
currentTime = Sys_Milliseconds();
if ( currentTime - lastErrorTime < 100 ) {
if ( ++errorCount > 3 ) {
code = ERR_FATAL;
}
} else {
errorCount = 0;
}
lastErrorTime = currentTime;
va_start( argptr,fmt );
Q_vsnprintf (com_errorMessage, sizeof(com_errorMessage),fmt,argptr);
va_end( argptr );
if (code != ERR_DISCONNECT && code != ERR_NEED_CD)
Cvar_Set( "com_errorMessage", com_errorMessage );
restartClient = com_gameClientRestarting && !( com_cl_running && com_cl_running->integer );
com_gameRestarting = qfalse;
com_gameClientRestarting = qfalse;
if (code == ERR_DISCONNECT || code == ERR_SERVERDISCONNECT) {
VM_Forced_Unload_Start();
SV_Shutdown( "Server disconnected" );
if ( restartClient ) {
CL_Init();
}
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
// make sure we can get at our local stuff
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else if (code == ERR_DROP) {
Com_Printf( "********************\nERROR: %s\n********************\n", com_errorMessage );
VM_Forced_Unload_Start();
SV_Shutdown (va("Server crashed: %s", com_errorMessage));
if ( restartClient ) {
CL_Init();
}
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else if ( code == ERR_NEED_CD ) {
VM_Forced_Unload_Start();
SV_Shutdown( "Server didn't have CD" );
if ( restartClient ) {
CL_Init();
}
if ( com_cl_running && com_cl_running->integer ) {
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
CL_CDDialog();
} else {
Com_Printf( "Server didn't have CD\n" );
VM_Forced_Unload_Done();
}
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else {
VM_Forced_Unload_Start();
CL_Shutdown(va("Client fatal crashed: %s", com_errorMessage), qtrue, qtrue);
SV_Shutdown(va("Server fatal crashed: %s", com_errorMessage));
VM_Forced_Unload_Done();
}
Com_Shutdown();
Sys_Error( "%s", com_errorMessage );
}
/*
=============
Com_Quit_f
Both client and server can use this, and it will
do the apropriate things.
=============
*/
void Com_Quit_f( void ) {
// don't try to shutdown if we are in a recursive error
char *p = Cmd_Args( );
if ( !com_errorEntered ) {
// Some VMs might execute "quit" command directly,
// which would trigger an unload of active VM error.
// Sys_Quit will kill this process anyways, so
// a corrupt call stack makes no difference
VM_Forced_Unload_Start();
SV_Shutdown(p[0] ? p : "Server quit");
CL_Shutdown(p[0] ? p : "Client quit", qtrue, qtrue);
VM_Forced_Unload_Done();
Com_Shutdown();
FS_Shutdown( qtrue );
}
Sys_Quit();
}
/*
============================================================================
COMMAND LINE FUNCTIONS
+ characters seperate the commandLine string into multiple console
command lines.
All of these are valid:
quake3 +set test blah +map test
quake3 set test blah+map test
quake3 set test blah + map test
============================================================================
*/
#define MAX_CONSOLE_LINES 32
int com_numConsoleLines;
char *com_consoleLines[MAX_CONSOLE_LINES];
/*
==================
Com_ParseCommandLine
Break it up into multiple console lines
==================
*/
void Com_ParseCommandLine( char *commandLine ) {
com_consoleLines[0] = commandLine;
com_numConsoleLines = 1;
while ( *commandLine ) {
// look for a + separating character
// if commandLine came from a file, we might have real line seperators
if ( *commandLine == '+' || *commandLine == '\n' ) {
if ( com_numConsoleLines == MAX_CONSOLE_LINES ) {
return;
}
com_consoleLines[com_numConsoleLines] = commandLine + 1;
com_numConsoleLines++;
*commandLine = 0;
}
commandLine++;
}
}
/*
===================
Com_SafeMode
Check for "safe" on the command line, which will
skip loading of wolfconfig.cfg
===================
*/
qboolean Com_SafeMode( void ) {
int i;
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
Cmd_TokenizeString( com_consoleLines[i] );
if ( !Q_stricmp( Cmd_Argv( 0 ), "safe" )
|| !Q_stricmp( Cmd_Argv( 0 ), "cvar_restart" ) ) {
com_consoleLines[i][0] = 0;
return qtrue;
}
}
return qfalse;
}
/*
===============
Com_StartupVariable
Searches for command line parameters that are set commands.
If match is not NULL, only that cvar will be looked for.
That is necessary because cddir and basedir need to be set
before the filesystem is started, but all other sets should
be after execing the config and default.
===============
*/
void Com_StartupVariable( const char *match ) {
int i;
char *s;
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
Cmd_TokenizeString( com_consoleLines[i] );
if ( strcmp( Cmd_Argv( 0 ), "set" ) ) {
continue;
}
s = Cmd_Argv( 1 );
if(!match || !strcmp(s, match))
{
if(Cvar_Flags(s) == CVAR_NONEXISTENT)
Cvar_Get(s, Cmd_ArgsFrom(2), CVAR_USER_CREATED);
else
Cvar_Set2(s, Cmd_ArgsFrom(2), qfalse);
}
}
}
/*
=================
Com_AddStartupCommands
Adds command line parameters as script statements
Commands are seperated by + signs
Returns qtrue if any late commands were added, which
will keep the demoloop from immediately starting
=================
*/
qboolean Com_AddStartupCommands( void ) {
int i;
qboolean added;
added = qfalse;
// quote every token, so args with semicolons can work
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
if ( !com_consoleLines[i] || !com_consoleLines[i][0] ) {
continue;
}
// set commands already added with Com_StartupVariable
if ( !Q_stricmpn( com_consoleLines[i], "set ", 4 ) ) {
continue;
}
added = qtrue;
Cbuf_AddText( com_consoleLines[i] );
Cbuf_AddText( "\n" );
}
return added;
}
//============================================================================
void Info_Print( const char *s ) {
char key[BIG_INFO_KEY];
char value[BIG_INFO_VALUE];
char *o;
int l;
if ( *s == '\\' ) {
s++;
}
while ( *s )
{
o = key;
while ( *s && *s != '\\' )
*o++ = *s++;
l = o - key;
if ( l < 20 ) {
memset( o, ' ', 20 - l );
key[20] = 0;
} else {
*o = 0;
}
Com_Printf( "%s ", key );
if ( !*s ) {
Com_Printf( "MISSING VALUE\n" );
return;
}
o = value;
s++;
while ( *s && *s != '\\' )
*o++ = *s++;
*o = 0;
if ( *s ) {
s++;
}
Com_Printf( "%s\n", value );
}
}
/*
============
Com_StringContains
============
*/
char *Com_StringContains( char *str1, char *str2, int casesensitive ) {
int len, i, j;
len = strlen( str1 ) - strlen( str2 );
for ( i = 0; i <= len; i++, str1++ ) {
for ( j = 0; str2[j]; j++ ) {
if ( casesensitive ) {
if ( str1[j] != str2[j] ) {
break;
}
} else {
if ( toupper( str1[j] ) != toupper( str2[j] ) ) {
break;
}
}
}
if ( !str2[j] ) {
return str1;
}
}
return NULL;
}
/*
============
Com_Filter
============
*/
int Com_Filter( char *filter, char *name, int casesensitive ) {
char buf[MAX_TOKEN_CHARS];
char *ptr;
int i, found;
while ( *filter ) {
if ( *filter == '*' ) {
filter++;
for ( i = 0; *filter; i++ ) {
if ( *filter == '*' || *filter == '?' ) {
break;
}
buf[i] = *filter;
filter++;
}
buf[i] = '\0';
if ( strlen( buf ) ) {
ptr = Com_StringContains( name, buf, casesensitive );
if ( !ptr ) {
return qfalse;
}
name = ptr + strlen( buf );
}
} else if ( *filter == '?' ) {
filter++;
name++;
} else if ( *filter == '[' && *( filter + 1 ) == '[' ) {
filter++;
} else if ( *filter == '[' ) {
filter++;
found = qfalse;
while ( *filter && !found ) {
if ( *filter == ']' && *( filter + 1 ) != ']' ) {
break;
}
if ( *( filter + 1 ) == '-' && *( filter + 2 ) && ( *( filter + 2 ) != ']' || *( filter + 3 ) == ']' ) ) {
if ( casesensitive ) {
if ( *name >= *filter && *name <= *( filter + 2 ) ) {
found = qtrue;
}
} else {
if ( toupper( *name ) >= toupper( *filter ) &&
toupper( *name ) <= toupper( *( filter + 2 ) ) ) {
found = qtrue;
}
}
filter += 3;
} else {
if ( casesensitive ) {
if ( *filter == *name ) {
found = qtrue;
}
} else {
if ( toupper( *filter ) == toupper( *name ) ) {
found = qtrue;
}
}
filter++;
}
}
if ( !found ) {
return qfalse;
}
while ( *filter ) {
if ( *filter == ']' && *( filter + 1 ) != ']' ) {
break;
}
filter++;
}
filter++;
name++;
} else {
if ( casesensitive ) {
if ( *filter != *name ) {
return qfalse;
}
} else {
if ( toupper( *filter ) != toupper( *name ) ) {
return qfalse;
}
}
filter++;
name++;
}
}
return qtrue;
}
/*
============
Com_FilterPath
============
*/
int Com_FilterPath( char *filter, char *name, int casesensitive ) {
int i;
char new_filter[MAX_QPATH];
char new_name[MAX_QPATH];
for ( i = 0; i < MAX_QPATH - 1 && filter[i]; i++ ) {
if ( filter[i] == '\\' || filter[i] == ':' ) {
new_filter[i] = '/';
} else {
new_filter[i] = filter[i];
}
}
new_filter[i] = '\0';
for ( i = 0; i < MAX_QPATH - 1 && name[i]; i++ ) {
if ( name[i] == '\\' || name[i] == ':' ) {
new_name[i] = '/';
} else {
new_name[i] = name[i];
}
}
new_name[i] = '\0';
return Com_Filter( new_filter, new_name, casesensitive );
}
/*
================
Com_RealTime
================
*/
int Com_RealTime( qtime_t *qtime ) {
time_t t;
struct tm *tms;
t = time( NULL );
if ( !qtime ) {
return t;
}
tms = localtime( &t );
if ( tms ) {
qtime->tm_sec = tms->tm_sec;
qtime->tm_min = tms->tm_min;
qtime->tm_hour = tms->tm_hour;
qtime->tm_mday = tms->tm_mday;
qtime->tm_mon = tms->tm_mon;
qtime->tm_year = tms->tm_year;
qtime->tm_wday = tms->tm_wday;
qtime->tm_yday = tms->tm_yday;
qtime->tm_isdst = tms->tm_isdst;
}
return t;
}
/*
==============================================================================
ZONE MEMORY ALLOCATION
There is never any space between memblocks, and there will never be two
contiguous free memblocks.
The rover can be left pointing at a non-empty block
The zone calls are pretty much only used for small strings and structures,
all big things are allocated on the hunk.
==============================================================================
*/
#define ZONEID 0x1d4a11
#define MINFRAGMENT 64
typedef struct zonedebug_s {
char *label;
char *file;
int line;
int allocSize;
} zonedebug_t;
typedef struct memblock_s {
int size; // including the header and possibly tiny fragments
int tag; // a tag of 0 is a free block
struct memblock_s *next, *prev;
int id; // should be ZONEID
#ifdef ZONE_DEBUG
zonedebug_t d;
#endif
} memblock_t;
typedef struct {
int size; // total bytes malloced, including header
int used; // total bytes used
memblock_t blocklist; // start / end cap for linked list
memblock_t *rover;
} memzone_t;
// main zone for all "dynamic" memory allocation
memzone_t *mainzone;
// we also have a small zone for small allocations that would only
// fragment the main zone (think of cvar and cmd strings)
memzone_t *smallzone;
void Z_CheckHeap( void );
/*
========================
Z_ClearZone
========================
*/
void Z_ClearZone( memzone_t *zone, int size ) {
memblock_t *block;
// set the entire zone to one free block
zone->blocklist.next = zone->blocklist.prev = block =
( memblock_t * )( (byte *)zone + sizeof( memzone_t ) );
zone->blocklist.tag = 1; // in use block
zone->blocklist.id = 0;
zone->blocklist.size = 0;
zone->rover = block;
zone->size = size;
zone->used = 0;
block->prev = block->next = &zone->blocklist;
block->tag = 0; // free block
block->id = ZONEID;
block->size = size - sizeof( memzone_t );
}
/*
========================
Z_Free
========================
*/
void Z_Free( void *ptr ) {
memblock_t *block, *other;
memzone_t *zone;
if ( !ptr ) {
Com_Error( ERR_DROP, "Z_Free: NULL pointer" );
}
block = ( memblock_t * )( (byte *)ptr - sizeof( memblock_t ) );
if ( block->id != ZONEID ) {
Com_Error( ERR_FATAL, "Z_Free: freed a pointer without ZONEID" );
}
if ( block->tag == 0 ) {
Com_Error( ERR_FATAL, "Z_Free: freed a freed pointer" );
}
// if static memory
if ( block->tag == TAG_STATIC ) {
return;
}
// check the memory trash tester
if ( *( int * )( (byte *)block + block->size - 4 ) != ZONEID ) {
Com_Error( ERR_FATAL, "Z_Free: memory block wrote past end" );
}
if ( block->tag == TAG_SMALL ) {
zone = smallzone;
} else {
zone = mainzone;
}
zone->used -= block->size;
// set the block to something that should cause problems
// if it is referenced...
memset( ptr, 0xaa, block->size - sizeof( *block ) );
block->tag = 0; // mark as free
other = block->prev;
if ( !other->tag ) {
// merge with previous free block
other->size += block->size;
other->next = block->next;
other->next->prev = other;
if ( block == zone->rover ) {
zone->rover = other;
}
block = other;
}
zone->rover = block;
other = block->next;
if ( !other->tag ) {
// merge the next free block onto the end
block->size += other->size;
block->next = other->next;
block->next->prev = block;
}
}
/*
================
Z_FreeTags
================
*/
void Z_FreeTags( int tag ) {
int count;
memzone_t *zone;
if ( tag == TAG_SMALL ) {
zone = smallzone;
} else {
zone = mainzone;
}
count = 0;
// use the rover as our pointer, because
// Z_Free automatically adjusts it
zone->rover = zone->blocklist.next;
do {
if ( zone->rover->tag == tag ) {
count++;
Z_Free( ( void * )( zone->rover + 1 ) );
continue;
}
zone->rover = zone->rover->next;
} while ( zone->rover != &zone->blocklist );
}
/*
================
Z_TagMalloc
================
*/
memblock_t *debugblock; // RF, jusy so we can track a block to find out when it's getting trashed
#ifdef ZONE_DEBUG
void *Z_TagMallocDebug( int size, int tag, char *label, char *file, int line ) {
int allocSize;
#else
void *Z_TagMalloc( int size, int tag ) {
#endif
int extra;
memblock_t *start, *rover, *new, *base;
memzone_t *zone;
if ( !tag ) {
Com_Error( ERR_FATAL, "Z_TagMalloc: tried to use a 0 tag" );
}
if ( tag == TAG_SMALL ) {
zone = smallzone;
} else {
zone = mainzone;
}
#ifdef ZONE_DEBUG
allocSize = size;
#endif
//
// scan through the block list looking for the first free block
// of sufficient size
//
size += sizeof( memblock_t ); // account for size of block header
size += 4; // space for memory trash tester
size = PAD(size, sizeof(intptr_t)); // align to 32/64 bit boundary
base = rover = zone->rover;
start = base->prev;
do {
if ( rover == start ) {
// scaned all the way around the list
#ifdef ZONE_DEBUG
Z_LogHeap();
Com_Error(ERR_FATAL, "Z_Malloc: failed on allocation of %i bytes from the %s zone: %s, line: %d (%s)",
size, zone == smallzone ? "small" : "main", file, line, label);
#else
Com_Error(ERR_FATAL, "Z_Malloc: failed on allocation of %i bytes from the %s zone",
size, zone == smallzone ? "small" : "main" );
#endif
return NULL;
}
if ( rover->tag ) {
base = rover = rover->next;
} else {
rover = rover->next;
}
} while ( base->tag || base->size < size );
//
// found a block big enough
//
extra = base->size - size;
if ( extra > MINFRAGMENT ) {
// there will be a free fragment after the allocated block
new = ( memblock_t * )( (byte *)base + size );
new->size = extra;
new->tag = 0; // free block
new->prev = base;
new->id = ZONEID;
new->next = base->next;
new->next->prev = new;
base->next = new;
base->size = size;
}
base->tag = tag; // no longer a free block
zone->rover = base->next; // next allocation will start looking here
zone->used += base->size; //
base->id = ZONEID;
#ifdef ZONE_DEBUG
base->d.label = label;
base->d.file = file;
base->d.line = line;
base->d.allocSize = allocSize;
#endif
// marker for memory trash testing
*( int * )( (byte *)base + base->size - 4 ) = ZONEID;
return ( void * )( (byte *)base + sizeof( memblock_t ) );
}
/*
========================
Z_Malloc
========================
*/
#ifdef ZONE_DEBUG
void *Z_MallocDebug( int size, char *label, char *file, int line ) {
#else
void *Z_Malloc( int size ) {
#endif
void *buf;
//Z_CheckHeap (); // DEBUG
#ifdef ZONE_DEBUG
buf = Z_TagMallocDebug( size, TAG_GENERAL, label, file, line );
#else
buf = Z_TagMalloc( size, TAG_GENERAL );
#endif
Com_Memset( buf, 0, size );
return buf;
}
#ifdef ZONE_DEBUG
void *S_MallocDebug( int size, char *label, char *file, int line ) {
return Z_TagMallocDebug( size, TAG_SMALL, label, file, line );
}
#else
void *S_Malloc( int size ) {
return Z_TagMalloc( size, TAG_SMALL );
}
#endif
/*
========================
Z_CheckHeap
========================
*/
void Z_CheckHeap( void ) {
memblock_t *block;
for ( block = mainzone->blocklist.next ; ; block = block->next ) {
if ( block->next == &mainzone->blocklist ) {
break; // all blocks have been hit
}
if ( (byte *)block + block->size != (byte *)block->next ) {
Com_Error( ERR_FATAL, "Z_CheckHeap: block size does not touch the next block" );
}
if ( block->next->prev != block ) {
Com_Error( ERR_FATAL, "Z_CheckHeap: next block doesn't have proper back link" );
}
if ( !block->tag && !block->next->tag ) {
Com_Error( ERR_FATAL, "Z_CheckHeap: two consecutive free blocks" );
}
}
}
/*
========================
Z_LogZoneHeap
========================
*/
void Z_LogZoneHeap( memzone_t *zone, char *name ) {
#ifdef ZONE_DEBUG
char dump[32], *ptr;
int i, j;
#endif
memblock_t *block;
char buf[4096];
int size, allocSize, numBlocks;
if ( !logfile || !FS_Initialized() ) {
return;
}
size = numBlocks = 0;
#ifdef ZONE_DEBUG
allocSize = 0;
#endif
Com_sprintf( buf, sizeof( buf ), "\r\n================\r\n%s log\r\n================\r\n", name );
FS_Write( buf, strlen( buf ), logfile );
for ( block = zone->blocklist.next ; block->next != &zone->blocklist; block = block->next ) {
if ( block->tag ) {
#ifdef ZONE_DEBUG
ptr = ( (char *) block ) + sizeof( memblock_t );
j = 0;
for ( i = 0; i < 20 && i < block->d.allocSize; i++ ) {
if ( ptr[i] >= 32 && ptr[i] < 127 ) {
dump[j++] = ptr[i];
} else {
dump[j++] = '_';
}
}
dump[j] = '\0';
Com_sprintf( buf, sizeof( buf ), "size = %8d: %s, line: %d (%s) [%s]\r\n", block->d.allocSize, block->d.file, block->d.line, block->d.label, dump );
FS_Write( buf, strlen( buf ), logfile );
allocSize += block->d.allocSize;
#endif
size += block->size;
numBlocks++;
}
}
#ifdef ZONE_DEBUG
// subtract debug memory
size -= numBlocks * sizeof( zonedebug_t );
#else
allocSize = numBlocks * sizeof( memblock_t ); // + 32 bit alignment
#endif
Com_sprintf( buf, sizeof( buf ), "%d %s memory in %d blocks\r\n", size, name, numBlocks );
FS_Write( buf, strlen( buf ), logfile );
Com_sprintf( buf, sizeof( buf ), "%d %s memory overhead\r\n", size - allocSize, name );
FS_Write( buf, strlen( buf ), logfile );
}
/*
========================
Z_LogHeap
========================
*/
void Z_LogHeap( void ) {
Z_LogZoneHeap( mainzone, "MAIN" );
Z_LogZoneHeap( smallzone, "SMALL" );
}
// static mem blocks to reduce a lot of small zone overhead
typedef struct memstatic_s {
memblock_t b;
byte mem[2];
} memstatic_t;
memstatic_t emptystring =
{ {( sizeof( memblock_t ) + 2 + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'\0', '\0'} };
memstatic_t numberstring[] = {
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'0', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'1', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'2', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'3', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'4', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'5', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'6', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'7', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'8', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'9', '\0'} }
};
/*
========================
CopyString
NOTE: never write over the memory CopyString returns because
memory from a memstatic_t might be returned
========================
*/
char *CopyString( const char *in ) {
char *out;
if ( !in[0] ) {
return ( (char *)&emptystring ) + sizeof( memblock_t );
} else if ( !in[1] ) {
if ( in[0] >= '0' && in[0] <= '9' ) {
return ( (char *)&numberstring[in[0] - '0'] ) + sizeof( memblock_t );
}
}
out = S_Malloc( strlen( in ) + 1 );
strcpy( out, in );
return out;
}
/*
==============================================================================
Goals:
reproducable without history effects -- no out of memory errors on weird map to map changes
allow restarting of the client without fragmentation
minimize total pages in use at run time
minimize total pages needed during load time
Single block of memory with stack allocators coming from both ends towards the middle.
One side is designated the temporary memory allocator.
Temporary memory can be allocated and freed in any order.
A highwater mark is kept of the most in use at any time.
When there is no temporary memory allocated, the permanent and temp sides
can be switched, allowing the already touched temp memory to be used for
permanent storage.
Temp memory must never be allocated on two ends at once, or fragmentation
could occur.
If we have any in-use temp memory, additional temp allocations must come from
that side.
If not, we can choose to make either side the new temp side and push future
permanent allocations to the other side. Permanent allocations should be
kept on the side that has the current greatest wasted highwater mark.
==============================================================================
*/
#define HUNK_MAGIC 0x89537892
#define HUNK_FREE_MAGIC 0x89537893
typedef struct {
int magic;
int size;
} hunkHeader_t;
typedef struct {
int mark;
int permanent;
int temp;
int tempHighwater;
} hunkUsed_t;
typedef struct hunkblock_s {
int size;
byte printed;
struct hunkblock_s *next;
char *label;
char *file;
int line;
} hunkblock_t;
static hunkblock_t *hunkblocks;
static hunkUsed_t hunk_low, hunk_high;
static hunkUsed_t *hunk_permanent, *hunk_temp;
static byte *s_hunkData = NULL;
static int s_hunkTotal;
static int s_zoneTotal;
static int s_smallZoneTotal;
/*
=================
Com_Meminfo_f
=================
*/
void Com_Meminfo_f( void ) {
memblock_t *block;
int zoneBytes, zoneBlocks;
int smallZoneBytes, smallZoneBlocks;
int botlibBytes, rendererBytes;
int unused;
zoneBytes = 0;
botlibBytes = 0;
rendererBytes = 0;
zoneBlocks = 0;
for ( block = mainzone->blocklist.next ; ; block = block->next ) {
if ( Cmd_Argc() != 1 ) {
Com_Printf( "block:%p size:%7i tag:%3i\n",
(void *)block, block->size, block->tag);
}
if ( block->tag ) {
zoneBytes += block->size;
zoneBlocks++;
if ( block->tag == TAG_BOTLIB ) {
botlibBytes += block->size;
} else if ( block->tag == TAG_RENDERER ) {
rendererBytes += block->size;
}
}
if ( block->next == &mainzone->blocklist ) {
break; // all blocks have been hit
}
if ( (byte *)block + block->size != (byte *)block->next ) {
Com_Printf( "ERROR: block size does not touch the next block\n" );
}
if ( block->next->prev != block ) {
Com_Printf( "ERROR: next block doesn't have proper back link\n" );
}
if ( !block->tag && !block->next->tag ) {
Com_Printf( "ERROR: two consecutive free blocks\n" );
}
}
smallZoneBytes = 0;
smallZoneBlocks = 0;
for ( block = smallzone->blocklist.next ; ; block = block->next ) {
if ( block->tag ) {
smallZoneBytes += block->size;
smallZoneBlocks++;
}
if ( block->next == &smallzone->blocklist ) {
break; // all blocks have been hit
}
}
Com_Printf( "%8i bytes total hunk\n", s_hunkTotal );
Com_Printf( "%8i bytes total zone\n", s_zoneTotal );
Com_Printf( "\n" );
Com_Printf( "%8i low mark\n", hunk_low.mark );
Com_Printf( "%8i low permanent\n", hunk_low.permanent );
if ( hunk_low.temp != hunk_low.permanent ) {
Com_Printf( "%8i low temp\n", hunk_low.temp );
}
Com_Printf( "%8i low tempHighwater\n", hunk_low.tempHighwater );
Com_Printf( "\n" );
Com_Printf( "%8i high mark\n", hunk_high.mark );
Com_Printf( "%8i high permanent\n", hunk_high.permanent );
if ( hunk_high.temp != hunk_high.permanent ) {
Com_Printf( "%8i high temp\n", hunk_high.temp );
}
Com_Printf( "%8i high tempHighwater\n", hunk_high.tempHighwater );
Com_Printf( "\n" );
Com_Printf( "%8i total hunk in use\n", hunk_low.permanent + hunk_high.permanent );
unused = 0;
if ( hunk_low.tempHighwater > hunk_low.permanent ) {
unused += hunk_low.tempHighwater - hunk_low.permanent;
}
if ( hunk_high.tempHighwater > hunk_high.permanent ) {
unused += hunk_high.tempHighwater - hunk_high.permanent;
}
Com_Printf( "%8i unused highwater\n", unused );
Com_Printf( "\n" );
Com_Printf( "%8i bytes in %i zone blocks\n", zoneBytes, zoneBlocks );
Com_Printf( " %8i bytes in dynamic botlib\n", botlibBytes );
Com_Printf( " %8i bytes in dynamic renderer\n", rendererBytes );
Com_Printf( " %8i bytes in dynamic other\n", zoneBytes - ( botlibBytes + rendererBytes ) );
Com_Printf( " %8i bytes in small Zone memory\n", smallZoneBytes );
}
/*
===============
Com_TouchMemory
Touch all known used data to make sure it is paged in
===============
*/
void Com_TouchMemory( void ) {
int start, end;
int i, j;
int sum;
memblock_t *block;
Z_CheckHeap();
start = Sys_Milliseconds();
sum = 0;
j = hunk_low.permanent >> 2;
for ( i = 0 ; i < j ; i += 64 ) { // only need to touch each page
sum += ( (int *)s_hunkData )[i];
}
i = ( s_hunkTotal - hunk_high.permanent ) >> 2;
j = hunk_high.permanent >> 2;
for ( ; i < j ; i += 64 ) { // only need to touch each page
sum += ( (int *)s_hunkData )[i];
}
for ( block = mainzone->blocklist.next ; ; block = block->next ) {
if ( block->tag ) {
j = block->size >> 2;
for ( i = 0 ; i < j ; i += 64 ) { // only need to touch each page
sum += ( (int *)block )[i];
}
}
if ( block->next == &mainzone->blocklist ) {
break; // all blocks have been hit
}
}
end = Sys_Milliseconds();
Com_Printf( "Com_TouchMemory: %i msec\n", end - start );
}
/*
=================
Com_InitZoneMemory
=================
*/
void Com_InitSmallZoneMemory( void ) {
s_smallZoneTotal = 512 * 1024;
smallzone = calloc( s_smallZoneTotal, 1 );
if ( !smallzone ) {
Com_Error( ERR_FATAL, "Small zone data failed to allocate %1.1f megs", (float)s_smallZoneTotal / ( 1024 * 1024 ) );
}
Z_ClearZone( smallzone, s_smallZoneTotal );
}
/*
void Com_InitZoneMemory( void ) {
cvar_t *cv;
s_smallZoneTotal = 512 * 1024;
smallzone = malloc( s_smallZoneTotal );
if ( !smallzone ) {
Com_Error( ERR_FATAL, "Small zone data failed to allocate %1.1f megs", (float)s_smallZoneTotal / (1024*1024) );
}
Z_ClearZone( smallzone, s_smallZoneTotal );
// allocate the random block zone
cv = Cvar_Get( "com_zoneMegs", DEF_COMZONEMEGS, CVAR_LATCH | CVAR_ARCHIVE );
if ( cv->integer < 16 ) {
s_zoneTotal = 1024 * 1024 * 16;
} else {
s_zoneTotal = cv->integer * 1024 * 1024;
}
mainzone = malloc( s_zoneTotal );
if ( !mainzone ) {
Com_Error( ERR_FATAL, "Zone data failed to allocate %i megs", s_zoneTotal / (1024*1024) );
}
Z_ClearZone( mainzone, s_zoneTotal );
}
*/
void Com_InitZoneMemory( void ) {
cvar_t *cv;
// Please note: com_zoneMegs can only be set on the command line, and
// not in wolfconfig_mp.cfg or Com_StartupVariable, as they haven't been
// executed by this point. It's a chicken and egg problem. We need the
// memory manager configured to handle those places where you would
// configure the memory manager.
// allocate the random block zone
cv = Cvar_Get( "com_zoneMegs", DEF_COMZONEMEGS_S, CVAR_LATCH | CVAR_ARCHIVE );
if ( cv->integer < DEF_COMZONEMEGS ) {
s_zoneTotal = 1024 * 1024 * DEF_COMZONEMEGS;
} else {
s_zoneTotal = cv->integer * 1024 * 1024;
}
mainzone = calloc( s_zoneTotal, 1 );
if ( !mainzone ) {
Com_Error( ERR_FATAL, "Zone data failed to allocate %i megs", s_zoneTotal / ( 1024 * 1024 ) );
}
Z_ClearZone( mainzone, s_zoneTotal );
}
/*
=================
Hunk_Log
=================
*/
void Hunk_Log( void ) {
hunkblock_t *block;
char buf[4096];
int size, numBlocks;
if ( !logfile || !FS_Initialized() ) {
return;
}
size = 0;
numBlocks = 0;
Com_sprintf( buf, sizeof( buf ), "\r\n================\r\nHunk log\r\n================\r\n" );
FS_Write( buf, strlen( buf ), logfile );
for ( block = hunkblocks ; block; block = block->next ) {
#ifdef HUNK_DEBUG
Com_sprintf( buf, sizeof( buf ), "size = %8d: %s, line: %d (%s)\r\n", block->size, block->file, block->line, block->label );
FS_Write( buf, strlen( buf ), logfile );
#endif
size += block->size;
numBlocks++;
}
Com_sprintf( buf, sizeof( buf ), "%d Hunk memory\r\n", size );
FS_Write( buf, strlen( buf ), logfile );
Com_sprintf( buf, sizeof( buf ), "%d hunk blocks\r\n", numBlocks );
FS_Write( buf, strlen( buf ), logfile );
}
/*
=================
Hunk_SmallLog
=================
*/
void Hunk_SmallLog( void ) {
hunkblock_t *block, *block2;
char buf[4096];
int size, locsize, numBlocks;
if ( !logfile || !FS_Initialized() ) {
return;
}
for ( block = hunkblocks ; block; block = block->next ) {
block->printed = qfalse;
}
size = 0;
numBlocks = 0;
Com_sprintf( buf, sizeof( buf ), "\r\n================\r\nHunk Small log\r\n================\r\n" );
FS_Write( buf, strlen( buf ), logfile );
for ( block = hunkblocks; block; block = block->next ) {
if ( block->printed ) {
continue;
}
locsize = block->size;
for ( block2 = block->next; block2; block2 = block2->next ) {
if ( block->line != block2->line ) {
continue;
}
if ( Q_stricmp( block->file, block2->file ) ) {
continue;
}
size += block2->size;
locsize += block2->size;
block2->printed = qtrue;
}
#ifdef HUNK_DEBUG
Com_sprintf( buf, sizeof( buf ), "size = %8d: %s, line: %d (%s)\r\n", locsize, block->file, block->line, block->label );
FS_Write( buf, strlen( buf ), logfile );
#endif
size += block->size;
numBlocks++;
}
Com_sprintf( buf, sizeof( buf ), "%d Hunk memory\r\n", size );
FS_Write( buf, strlen( buf ), logfile );
Com_sprintf( buf, sizeof( buf ), "%d hunk blocks\r\n", numBlocks );
FS_Write( buf, strlen( buf ), logfile );
}
/*
=================
Com_InitHunkMemory
=================
*/
void Com_InitHunkMemory( void ) {
cvar_t *cv;
int nMinAlloc;
char *pMsg = NULL;
// make sure the file system has allocated and "not" freed any temp blocks
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( FS_LoadStack() != 0 ) {
Com_Error( ERR_FATAL, "Hunk initialization failed. File system load stack not zero" );
}
// allocate the stack based hunk allocator
cv = Cvar_Get( "com_hunkMegs", DEF_COMHUNKMEGS_S, CVAR_LATCH | CVAR_ARCHIVE );
// if we are not dedicated min allocation is 56, otherwise min is 1
if ( com_dedicated && com_dedicated->integer ) {
nMinAlloc = MIN_DEDICATED_COMHUNKMEGS;
pMsg = "Minimum com_hunkMegs for a dedicated server is %i, allocating %i megs.\n";
} else {
nMinAlloc = MIN_COMHUNKMEGS;
pMsg = "Minimum com_hunkMegs is %i, allocating %i megs.\n";
}
if ( cv->integer < nMinAlloc ) {
s_hunkTotal = 1024 * 1024 * nMinAlloc;
Com_Printf( pMsg, nMinAlloc, s_hunkTotal / ( 1024 * 1024 ) );
} else {
s_hunkTotal = cv->integer * 1024 * 1024;
}
s_hunkData = malloc( s_hunkTotal + 31 );
if ( !s_hunkData ) {
Com_Error( ERR_FATAL, "Hunk data failed to allocate %i megs", s_hunkTotal / ( 1024 * 1024 ) );
}
// cacheline align
s_hunkData = (byte *) ( ( (intptr_t)s_hunkData + 31 ) & ~31 );
Hunk_Clear();
Cmd_AddCommand( "meminfo", Com_Meminfo_f );
#ifdef ZONE_DEBUG
Cmd_AddCommand( "zonelog", Z_LogHeap );
#endif
#ifdef HUNK_DEBUG
Cmd_AddCommand( "hunklog", Hunk_Log );
Cmd_AddCommand( "hunksmalllog", Hunk_SmallLog );
#endif
}
/*
====================
Hunk_MemoryRemaining
====================
*/
int Hunk_MemoryRemaining( void ) {
int low, high;
low = hunk_low.permanent > hunk_low.temp ? hunk_low.permanent : hunk_low.temp;
high = hunk_high.permanent > hunk_high.temp ? hunk_high.permanent : hunk_high.temp;
return s_hunkTotal - ( low + high );
}
/*
===================
Hunk_SetMark
The server calls this after the level and game VM have been loaded
===================
*/
void Hunk_SetMark( void ) {
hunk_low.mark = hunk_low.permanent;
hunk_high.mark = hunk_high.permanent;
}
/*
=================
Hunk_ClearToMark
The client calls this before starting a vid_restart or snd_restart
=================
*/
void Hunk_ClearToMark( void ) {
hunk_low.permanent = hunk_low.temp = hunk_low.mark;
hunk_high.permanent = hunk_high.temp = hunk_high.mark;
}
/*
=================
Hunk_CheckMark
=================
*/
qboolean Hunk_CheckMark( void ) {
if ( hunk_low.mark || hunk_high.mark ) {
return qtrue;
}
return qfalse;
}
void CL_ShutdownCGame( void );
void CL_ShutdownUI( void );
void SV_ShutdownGameProgs( void );
/*
=================
Hunk_Clear
The server calls this before shutting down or loading a new map
=================
*/
void Hunk_Clear( void ) {
#ifndef DEDICATED
CL_ShutdownCGame();
CL_ShutdownUI();
#endif
SV_ShutdownGameProgs();
#ifndef DEDICATED
CIN_CloseAllVideos();
#endif
hunk_low.mark = 0;
hunk_low.permanent = 0;
hunk_low.temp = 0;
hunk_low.tempHighwater = 0;
hunk_high.mark = 0;
hunk_high.permanent = 0;
hunk_high.temp = 0;
hunk_high.tempHighwater = 0;
hunk_permanent = &hunk_low;
hunk_temp = &hunk_high;
Cvar_Set( "com_hunkused", va( "%i", hunk_low.permanent + hunk_high.permanent ) );
Com_Printf( "Hunk_Clear: reset the hunk ok\n" );
VM_Clear(); // (SA) FIXME:TODO: was commented out in wolf
#ifdef HUNK_DEBUG
hunkblocks = NULL;
#endif
}
static void Hunk_SwapBanks( void ) {
hunkUsed_t *swap;
// can't swap banks if there is any temp already allocated
if ( hunk_temp->temp != hunk_temp->permanent ) {
return;
}
// if we have a larger highwater mark on this side, start making
// our permanent allocations here and use the other side for temp
if ( hunk_temp->tempHighwater - hunk_temp->permanent >
hunk_permanent->tempHighwater - hunk_permanent->permanent ) {
swap = hunk_temp;
hunk_temp = hunk_permanent;
hunk_permanent = swap;
}
}
/*
=================
Hunk_Alloc
Allocate permanent (until the hunk is cleared) memory
=================
*/
#ifdef HUNK_DEBUG
void *Hunk_AllocDebug( int size, ha_pref preference, char *label, char *file, int line ) {
#else
void *Hunk_Alloc( int size, ha_pref preference ) {
#endif
void *buf;
if ( s_hunkData == NULL ) {
Com_Error( ERR_FATAL, "Hunk_Alloc: Hunk memory system not initialized" );
}
Hunk_SwapBanks();
#ifdef HUNK_DEBUG
size += sizeof( hunkblock_t );
#endif
// round to cacheline
size = ( size + 31 ) & ~31;
if ( hunk_low.temp + hunk_high.temp + size > s_hunkTotal ) {
#ifdef HUNK_DEBUG
Hunk_Log();
Hunk_SmallLog();
Com_Error(ERR_DROP, "Hunk_Alloc failed on %i: %s, line: %d (%s)", size, file, line, label);
#else
Com_Error(ERR_DROP, "Hunk_Alloc failed on %i", size);
#endif
}
if ( hunk_permanent == &hunk_low ) {
buf = ( void * )( s_hunkData + hunk_permanent->permanent );
hunk_permanent->permanent += size;
} else {
hunk_permanent->permanent += size;
buf = ( void * )( s_hunkData + s_hunkTotal - hunk_permanent->permanent );
}
hunk_permanent->temp = hunk_permanent->permanent;
memset( buf, 0, size );
#ifdef HUNK_DEBUG
{
hunkblock_t *block;
block = (hunkblock_t *) buf;
block->size = size - sizeof( hunkblock_t );
block->file = file;
block->label = label;
block->line = line;
block->next = hunkblocks;
hunkblocks = block;
buf = ( (byte *) buf ) + sizeof( hunkblock_t );
}
#endif
// Ridah, update the com_hunkused cvar in increments, so we don't update it too often, since this cvar call isn't very efficent
if ( ( hunk_low.permanent + hunk_high.permanent ) > com_hunkused->integer + 10000 ) {
Cvar_Set( "com_hunkused", va( "%i", hunk_low.permanent + hunk_high.permanent ) );
}
return buf;
}
/*
=================
Hunk_AllocateTempMemory
This is used by the file loading system.
Multiple files can be loaded in temporary memory.
When the files-in-use count reaches zero, all temp memory will be deleted
=================
*/
void *Hunk_AllocateTempMemory( int size ) {
void *buf;
hunkHeader_t *hdr;
// return a Z_Malloc'd block if the hunk has not been initialized
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( s_hunkData == NULL ) {
return Z_Malloc( size );
}
Hunk_SwapBanks();
size = PAD(size, sizeof(intptr_t)) + sizeof( hunkHeader_t );
if ( hunk_temp->temp + hunk_permanent->permanent + size > s_hunkTotal ) {
Com_Error( ERR_DROP, "Hunk_AllocateTempMemory: failed on %i", size );
}
if ( hunk_temp == &hunk_low ) {
buf = ( void * )( s_hunkData + hunk_temp->temp );
hunk_temp->temp += size;
} else {
hunk_temp->temp += size;
buf = ( void * )( s_hunkData + s_hunkTotal - hunk_temp->temp );
}
if ( hunk_temp->temp > hunk_temp->tempHighwater ) {
hunk_temp->tempHighwater = hunk_temp->temp;
}
hdr = (hunkHeader_t *)buf;
buf = ( void * )( hdr + 1 );
hdr->magic = HUNK_MAGIC;
hdr->size = size;
// don't bother clearing, because we are going to load a file over it
return buf;
}
/*
==================
Hunk_FreeTempMemory
==================
*/
void Hunk_FreeTempMemory( void *buf ) {
hunkHeader_t *hdr;
// free with Z_Free if the hunk has not been initialized
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( s_hunkData == NULL ) {
Z_Free( buf );
return;
}
hdr = ( (hunkHeader_t *)buf ) - 1;
if ( hdr->magic != HUNK_MAGIC ) {
Com_Error( ERR_FATAL, "Hunk_FreeTempMemory: bad magic" );
}
hdr->magic = HUNK_FREE_MAGIC;
// this only works if the files are freed in stack order,
// otherwise the memory will stay around until Hunk_ClearTempMemory
if ( hunk_temp == &hunk_low ) {
if ( hdr == ( void * )( s_hunkData + hunk_temp->temp - hdr->size ) ) {
hunk_temp->temp -= hdr->size;
} else {
Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
}
} else {
if ( hdr == ( void * )( s_hunkData + s_hunkTotal - hunk_temp->temp ) ) {
hunk_temp->temp -= hdr->size;
} else {
Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
}
}
}
/*
=================
Hunk_ClearTempMemory
The temp space is no longer needed. If we have left more
touched but unused memory on this side, have future
permanent allocs use this side.
=================
*/
void Hunk_ClearTempMemory( void ) {
if ( s_hunkData != NULL ) {
hunk_temp->temp = hunk_temp->permanent;
}
}
/*
===================================================================
EVENTS AND JOURNALING
In addition to these events, .cfg files are also copied to the
journaled file
===================================================================
*/
#define MAX_PUSHED_EVENTS 1024
static int com_pushedEventsHead = 0;
static int com_pushedEventsTail = 0;
static sysEvent_t com_pushedEvents[MAX_PUSHED_EVENTS];
/*
=================
Com_InitJournaling
=================
*/
void Com_InitJournaling( void ) {
Com_StartupVariable( "journal" );
com_journal = Cvar_Get( "journal", "0", CVAR_INIT );
if ( !com_journal->integer ) {
return;
}
if ( com_journal->integer == 1 ) {
Com_Printf( "Journaling events\n" );
com_journalFile = FS_FOpenFileWrite( "journal.dat" );
com_journalDataFile = FS_FOpenFileWrite( "journaldata.dat" );
} else if ( com_journal->integer == 2 ) {
Com_Printf( "Replaying journaled events\n" );
FS_FOpenFileRead( "journal.dat", &com_journalFile, qtrue );
FS_FOpenFileRead( "journaldata.dat", &com_journalDataFile, qtrue );
}
if ( !com_journalFile || !com_journalDataFile ) {
Cvar_Set( "com_journal", "0" );
com_journalFile = 0;
com_journalDataFile = 0;
Com_Printf( "Couldn't open journal files\n" );
}
}
/*
========================================================================
EVENT LOOP
========================================================================
*/
#define MAX_QUEUED_EVENTS 256
#define MASK_QUEUED_EVENTS ( MAX_QUEUED_EVENTS - 1 )
static sysEvent_t eventQueue[ MAX_QUEUED_EVENTS ];
static int eventHead = 0;
static int eventTail = 0;
/*
================
Com_QueueEvent
A time of 0 will get the current time
Ptr should either be null, or point to a block of data that can
be freed by the game later.
================
*/
void Com_QueueEvent( int time, sysEventType_t type, int value, int value2, int ptrLength, void *ptr )
{
sysEvent_t *ev;
ev = &eventQueue[ eventHead & MASK_QUEUED_EVENTS ];
if ( eventHead - eventTail >= MAX_QUEUED_EVENTS )
{
Com_Printf("Com_QueueEvent: overflow\n");
// we are discarding an event, but don't leak memory
if ( ev->evPtr )
{
Z_Free( ev->evPtr );
}
eventTail++;
}
eventHead++;
if ( time == 0 )
{
time = Sys_Milliseconds();
}
ev->evTime = time;
ev->evType = type;
ev->evValue = value;
ev->evValue2 = value2;
ev->evPtrLength = ptrLength;
ev->evPtr = ptr;
}
/*
================
Com_GetSystemEvent
================
*/
sysEvent_t Com_GetSystemEvent( void )
{
sysEvent_t ev;
char *s;
// return if we have data
if ( eventHead > eventTail )
{
eventTail++;
return eventQueue[ ( eventTail - 1 ) & MASK_QUEUED_EVENTS ];
}
// check for console commands
s = Sys_ConsoleInput();
if ( s )
{
char *b;
int len;
len = strlen( s ) + 1;
b = Z_Malloc( len );
strcpy( b, s );
Com_QueueEvent( 0, SE_CONSOLE, 0, 0, len, b );
}
// return if we have data
if ( eventHead > eventTail )
{
eventTail++;
return eventQueue[ ( eventTail - 1 ) & MASK_QUEUED_EVENTS ];
}
// create an empty event to return
memset( &ev, 0, sizeof( ev ) );
ev.evTime = Sys_Milliseconds();
return ev;
}
/*
=================
Com_GetRealEvent
=================
*/
sysEvent_t Com_GetRealEvent( void ) {
int r;
sysEvent_t ev;
// either get an event from the system or the journal file
if ( com_journal->integer == 2 ) {
r = FS_Read( &ev, sizeof( ev ), com_journalFile );
if ( r != sizeof( ev ) ) {
Com_Error( ERR_FATAL, "Error reading from journal file" );
}
if ( ev.evPtrLength ) {
ev.evPtr = Z_Malloc( ev.evPtrLength );
r = FS_Read( ev.evPtr, ev.evPtrLength, com_journalFile );
if ( r != ev.evPtrLength ) {
Com_Error( ERR_FATAL, "Error reading from journal file" );
}
}
} else {
ev = Com_GetSystemEvent();
// write the journal value out if needed
if ( com_journal->integer == 1 ) {
r = FS_Write( &ev, sizeof( ev ), com_journalFile );
if ( r != sizeof( ev ) ) {
Com_Error( ERR_FATAL, "Error writing to journal file" );
}
if ( ev.evPtrLength ) {
r = FS_Write( ev.evPtr, ev.evPtrLength, com_journalFile );
if ( r != ev.evPtrLength ) {
Com_Error( ERR_FATAL, "Error writing to journal file" );
}
}
}
}
return ev;
}
/*
=================
Com_InitPushEvent
=================
*/
void Com_InitPushEvent( void ) {
// clear the static buffer array
// this requires SE_NONE to be accepted as a valid but NOP event
memset( com_pushedEvents, 0, sizeof( com_pushedEvents ) );
// reset counters while we are at it
// beware: GetEvent might still return an SE_NONE from the buffer
com_pushedEventsHead = 0;
com_pushedEventsTail = 0;
}
/*
=================
Com_PushEvent
=================
*/
void Com_PushEvent( sysEvent_t *event ) {
sysEvent_t *ev;
static int printedWarning = 0;
ev = &com_pushedEvents[ com_pushedEventsHead & ( MAX_PUSHED_EVENTS - 1 ) ];
if ( com_pushedEventsHead - com_pushedEventsTail >= MAX_PUSHED_EVENTS ) {
// don't print the warning constantly, or it can give time for more...
if ( !printedWarning ) {
printedWarning = qtrue;
Com_Printf( "WARNING: Com_PushEvent overflow\n" );
}
if ( ev->evPtr ) {
Z_Free( ev->evPtr );
}
com_pushedEventsTail++;
} else {
printedWarning = qfalse;
}
*ev = *event;
com_pushedEventsHead++;
}
/*
=================
Com_GetEvent
=================
*/
sysEvent_t Com_GetEvent( void ) {
if ( com_pushedEventsHead > com_pushedEventsTail ) {
com_pushedEventsTail++;
return com_pushedEvents[ ( com_pushedEventsTail - 1 ) & ( MAX_PUSHED_EVENTS - 1 ) ];
}
return Com_GetRealEvent();
}
/*
=================
Com_RunAndTimeServerPacket
=================
*/
void Com_RunAndTimeServerPacket( netadr_t *evFrom, msg_t *buf ) {
int t1, t2, msec;
t1 = 0;
if ( com_speeds->integer ) {
t1 = Sys_Milliseconds();
}
SV_PacketEvent( *evFrom, buf );
if ( com_speeds->integer ) {
t2 = Sys_Milliseconds();
msec = t2 - t1;
if ( com_speeds->integer == 3 ) {
Com_Printf( "SV_PacketEvent time: %i\n", msec );
}
}
}
/*
=================
Com_EventLoop
Returns last event time
=================
*/
int Com_EventLoop( void ) {
sysEvent_t ev;
netadr_t evFrom;
byte bufData[MAX_MSGLEN];
msg_t buf;
MSG_Init( &buf, bufData, sizeof( bufData ) );
while ( 1 ) {
ev = Com_GetEvent();
// if no more events are available
if ( ev.evType == SE_NONE ) {
// manually send packet events for the loopback channel
while ( NET_GetLoopPacket( NS_CLIENT, &evFrom, &buf ) ) {
CL_PacketEvent( evFrom, &buf );
}
while ( NET_GetLoopPacket( NS_SERVER, &evFrom, &buf ) ) {
// if the server just shut down, flush the events
if ( com_sv_running->integer ) {
Com_RunAndTimeServerPacket( &evFrom, &buf );
}
}
return ev.evTime;
}
switch(ev.evType)
{
case SE_KEY:
CL_KeyEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_CHAR:
CL_CharEvent( ev.evValue );
break;
case SE_MOUSE:
CL_MouseEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_JOYSTICK_AXIS:
CL_JoystickEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_CONSOLE:
Cbuf_AddText( (char *)ev.evPtr );
Cbuf_AddText( "\n" );
break;
default:
Com_Error( ERR_FATAL, "Com_EventLoop: bad event type %i", ev.evType );
break;
}
// free any block data
if ( ev.evPtr ) {
Z_Free( ev.evPtr );
}
}
return 0; // never reached
}
/*
================
Com_Milliseconds
Can be used for profiling, but will be journaled accurately
================
*/
int Com_Milliseconds( void ) {
sysEvent_t ev;
// get events and push them until we get a null event with the current time
do {
ev = Com_GetRealEvent();
if ( ev.evType != SE_NONE ) {
Com_PushEvent( &ev );
}
} while ( ev.evType != SE_NONE );
return ev.evTime;
}
//============================================================================
/*
=============
Com_Error_f
Just throw a fatal error to
test error shutdown procedures
=============
*/
static void __attribute__((__noreturn__)) Com_Error_f (void) {
if ( Cmd_Argc() > 1 ) {
Com_Error( ERR_DROP, "Testing drop error" );
} else {
Com_Error( ERR_FATAL, "Testing fatal error" );
}
}
/*
=============
Com_Freeze_f
Just freeze in place for a given number of seconds to test
error recovery
=============
*/
static void Com_Freeze_f( void ) {
float s;
int start, now;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "freeze <seconds>\n" );
return;
}
s = atof( Cmd_Argv( 1 ) );
start = Com_Milliseconds();
while ( 1 ) {
now = Com_Milliseconds();
if ( ( now - start ) * 0.001 > s ) {
break;
}
}
}
/*
=================
Com_Crash_f
A way to force a bus error for development reasons
=================
*/
static void Com_Crash_f( void ) {
* ( volatile int * ) 0 = 0x12345678;
}
/*
==================
Com_Setenv_f
For controlling environment variables
==================
*/
void Com_Setenv_f(void)
{
int argc = Cmd_Argc();
char *arg1 = Cmd_Argv(1);
if(argc > 2)
{
char *arg2 = Cmd_ArgsFrom(2);
Sys_SetEnv(arg1, arg2);
}
else if(argc == 2)
{
char *env = getenv(arg1);
if(env)
Com_Printf("%s=%s\n", arg1, env);
else
Com_Printf("%s undefined\n", arg1);
}
}
/*
==================
Com_ExecuteCfg
For controlling environment variables
==================
*/
void Com_ExecuteCfg(void)
{
// DHM - Nerve
#ifndef UPDATE_SERVER
Cbuf_ExecuteText(EXEC_NOW, "exec default.cfg\n");
if ( FS_ReadFile( "language.cfg", NULL ) > 0 ) {
Cbuf_ExecuteText(EXEC_APPEND, "exec language.cfg\n");
} else if ( FS_ReadFile( "Language.cfg", NULL ) > 0 ) {
Cbuf_ExecuteText(EXEC_APPEND, "exec Language.cfg\n");
}
Cbuf_Execute(); // Always execute after exec to prevent text buffer overflowing
if(!Com_SafeMode())
{
// skip the wolfconfig_mp.cfg and autoexec.cfg if "safe" is on the command line
Cbuf_ExecuteText(EXEC_NOW, "exec " Q3CONFIG_CFG "\n");
Cbuf_Execute();
Cbuf_ExecuteText(EXEC_NOW, "exec autoexec.cfg\n");
Cbuf_Execute();
}
#endif
}
/*
==================
Com_GameRestart
Change to a new mod properly with cleaning up cvars before switching.
==================
*/
void Com_GameRestart(int checksumFeed, qboolean disconnect)
{
// make sure no recursion can be triggered
if(!com_gameRestarting && com_fullyInitialized)
{
com_gameRestarting = qtrue;
com_gameClientRestarting = com_cl_running->integer;
// Kill server if we have one
if(com_sv_running->integer)
SV_Shutdown("Game directory changed");
if(com_gameClientRestarting)
{
if(disconnect)
CL_Disconnect(qfalse);
CL_Shutdown("Game directory changed", disconnect, qfalse);
}
FS_Restart(checksumFeed);
// Clean out any user and VM created cvars
Cvar_Restart(qtrue);
Com_ExecuteCfg();
if(disconnect)
{
// We don't want to change any network settings if gamedir
// change was triggered by a connect to server because the
// new network settings might make the connection fail.
NET_Restart_f();
}
if(com_gameClientRestarting)
{
CL_Init();
CL_StartHunkUsers(qfalse);
}
com_gameRestarting = qfalse;
com_gameClientRestarting = qfalse;
}
}
/*
==================
Com_GameRestart_f
Expose possibility to change current running mod to the user
==================
*/
void Com_GameRestart_f(void)
{
if(!FS_FilenameCompare(Cmd_Argv(1), com_basegame->string))
{
// This is the standard base game. Servers and clients should
// use "" and not the standard basegame name because this messes
// up pak file negotiation and lots of other stuff
Cvar_Set("fs_game", "");
}
else
Cvar_Set("fs_game", Cmd_Argv(1));
Com_GameRestart(0, qtrue);
}
#ifndef STANDALONE
// TTimo: centralizing the cl_cdkey stuff after I discovered a buffer overflow problem with the dedicated server version
// not sure it's necessary to have different defaults for regular and dedicated, but I don't want to take the risk
#ifndef DEDICATED
char cl_cdkey[34] = " ";
#else
char cl_cdkey[34] = "123456789";
#endif
/*
=================
Com_ReadCDKey
=================
*/
qboolean CL_CDKeyValidate( const char *key, const char *checksum );
void Com_ReadCDKey( const char *filename ) {
fileHandle_t f;
char buffer[33];
char fbuffer[MAX_OSPATH];
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename);
FS_SV_FOpenFileRead( fbuffer, &f );
if ( !f ) {
Q_strncpyz( cl_cdkey, " ", 17 );
return;
}
Com_Memset( buffer, 0, sizeof( buffer ) );
FS_Read( buffer, 16, f );
FS_FCloseFile( f );
if ( CL_CDKeyValidate( buffer, NULL ) ) {
Q_strncpyz( cl_cdkey, buffer, 17 );
} else {
Q_strncpyz( cl_cdkey, " ", 17 );
}
}
/*
=================
Com_AppendCDKey
=================
*/
void Com_AppendCDKey( const char *filename ) {
fileHandle_t f;
char buffer[33];
char fbuffer[MAX_OSPATH];
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename);
FS_SV_FOpenFileRead( fbuffer, &f );
if ( !f ) {
Q_strncpyz( &cl_cdkey[16], " ", 17 );
return;
}
Com_Memset( buffer, 0, sizeof( buffer ) );
FS_Read( buffer, 16, f );
FS_FCloseFile( f );
if ( CL_CDKeyValidate( buffer, NULL ) ) {
strcat( &cl_cdkey[16], buffer );
} else {
Q_strncpyz( &cl_cdkey[16], " ", 17 );
}
}
#ifndef DEDICATED
/*
=================
Com_WriteCDKey
=================
*/
static void Com_WriteCDKey( const char *filename, const char *ikey ) {
fileHandle_t f;
char fbuffer[MAX_OSPATH];
char key[17];
#ifndef _WIN32
mode_t savedumask;
#endif
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename);
Q_strncpyz( key, ikey, 17 );
if ( !CL_CDKeyValidate( key, NULL ) ) {
return;
}
#ifndef _WIN32
savedumask = umask(0077);
#endif
f = FS_SV_FOpenFileWrite( fbuffer );
if ( !f ) {
Com_Printf ("Couldn't write CD key to %s.\n", fbuffer );
goto out;
}
FS_Write( key, 16, f );
FS_Printf( f, "\n// generated by RTCW, do not modify\r\n" );
FS_Printf( f, "// Do not give this file to ANYONE.\r\n" );
#ifdef __APPLE__
FS_Printf( f, "// Aspyr will NOT ask you to send this file to them.\r\n" );
#else
FS_Printf( f, "// id Software and Activision will NOT ask you to send this file to them.\r\n" );
#endif
FS_FCloseFile( f );
out:
#ifndef _WIN32
umask(savedumask);
#else
;
#endif
}
#endif
#endif // STANDALONE
void Com_SetRecommended( void ) {
cvar_t *cv;
qboolean goodVideo;
qboolean goodCPU;
// will use this for recommended settings as well.. do i outside the lower check so it gets done even with command line stuff
cv = Cvar_Get( "r_highQualityVideo", "1", CVAR_ARCHIVE );
goodVideo = ( cv && cv->integer );
goodCPU = Sys_GetHighQualityCPU();
if ( goodVideo && goodCPU ) {
Com_Printf( "Found high quality video and CPU\n" );
Cbuf_AddText( "exec highVidhighCPU.cfg\n" );
} else if ( goodVideo && !goodCPU ) {
Cbuf_AddText( "exec highVidlowCPU.cfg\n" );
Com_Printf( "Found high quality video and low quality CPU\n" );
} else if ( !goodVideo && goodCPU ) {
Cbuf_AddText( "exec lowVidhighCPU.cfg\n" );
Com_Printf( "Found low quality video and high quality CPU\n" );
} else {
Cbuf_AddText( "exec lowVidlowCPU.cfg\n" );
Com_Printf( "Found low quality video and low quality CPU\n" );
}
// (SA) set the cvar so the menu will reflect this on first run
// Cvar_Set("ui_glCustom", "999"); // 'recommended'
}
static void Com_DetectAltivec(void)
{
// Only detect if user hasn't forcibly disabled it.
if (com_altivec->integer) {
static qboolean altivec = qfalse;
static qboolean detected = qfalse;
if (!detected) {
altivec = ( Sys_GetProcessorFeatures( ) & CF_ALTIVEC );
detected = qtrue;
}
if (!altivec) {
Cvar_Set( "com_altivec", "0" ); // we don't have it! Disable support!
}
}
}
/*
=================
Com_DetectSSE
Find out whether we have SSE support for Q_ftol function
=================
*/
#if id386 || idx64
static void Com_DetectSSE(void)
{
#if !idx64
cpuFeatures_t feat;
feat = Sys_GetProcessorFeatures();
if(feat & CF_SSE)
{
if(feat & CF_SSE2)
Q_SnapVector = qsnapvectorsse;
else
Q_SnapVector = qsnapvectorx87;
Q_ftol = qftolsse;
#endif
Q_VMftol = qvmftolsse;
Com_Printf("SSE instruction set enabled\n");
#if !idx64
}
else
{
Q_ftol = qftolx87;
Q_VMftol = qvmftolx87;
Q_SnapVector = qsnapvectorx87;
Com_Printf("SSE instruction set not available\n");
}
#endif
}
#else
#define Com_DetectSSE()
#endif
/*
=================
Com_InitRand
Seed the random number generator, if possible with an OS supplied random seed.
=================
*/
static void Com_InitRand(void)
{
unsigned int seed;
if(Sys_RandomBytes((byte *) &seed, sizeof(seed)))
srand(seed);
else
srand(time(NULL));
}
/*
=================
Com_Init
=================
*/
void Com_Init( char *commandLine ) {
char *s;
char *t;
int qport;
// TTimo gcc warning: variable `safeMode' might be clobbered by `longjmp' or `vfork'
volatile qboolean safeMode = qtrue;
Com_Printf( "%s %s %s\n", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
if ( setjmp( abortframe ) ) {
Sys_Error( "Error during initialization" );
}
// Clear queues
Com_Memset( &eventQueue[ 0 ], 0, MAX_QUEUED_EVENTS * sizeof( sysEvent_t ) );
// initialize the weak pseudo-random number generator for use later.
Com_InitRand();
// do this before anything else decides to push events
Com_InitPushEvent();
Com_InitSmallZoneMemory();
Cvar_Init();
// prepare enough of the subsystems to handle
// cvar and command buffer management
Com_ParseCommandLine( commandLine );
// Swap_Init();
Cbuf_Init();
Com_DetectSSE();
// override anything from the config files with command line args
Com_StartupVariable( NULL );
Com_InitZoneMemory();
Cmd_Init ();
// get the developer cvar set as early as possible
com_developer = Cvar_Get("developer", "0", CVAR_TEMP);
// done early so bind command exists
CL_InitKeyCommands();
com_standalone = Cvar_Get("com_standalone", "0", CVAR_ROM);
com_basegame = Cvar_Get("com_basegame", BASEGAME, CVAR_INIT);
com_homepath = Cvar_Get("com_homepath", "", CVAR_INIT);
if(!com_basegame->string[0])
Cvar_ForceReset("com_basegame");
FS_InitFilesystem();
Com_InitJournaling();
// Add some commands here already so users can use them from config files
Cmd_AddCommand ("setenv", Com_Setenv_f);
if (com_developer && com_developer->integer)
{
Cmd_AddCommand ("error", Com_Error_f);
Cmd_AddCommand ("crash", Com_Crash_f);
Cmd_AddCommand ("freeze", Com_Freeze_f);
}
Cmd_AddCommand ("quit", Com_Quit_f);
Cmd_AddCommand ("changeVectors", MSG_ReportChangeVectors_f );
Cmd_AddCommand ("writeconfig", Com_WriteConfig_f );
Cmd_SetCommandCompletionFunc( "writeconfig", Cmd_CompleteCfgName );
Cmd_AddCommand("game_restart", Com_GameRestart_f);
Com_ExecuteCfg();
// override anything from the config files with command line args
Com_StartupVariable( NULL );
// get dedicated here for proper hunk megs initialization
#ifdef UPDATE_SERVER
com_dedicated = Cvar_Get( "dedicated", "1", CVAR_LATCH );
Cvar_CheckRange( com_dedicated, 1, 2, qtrue );
#elif DEDICATED
// TTimo: default to internet dedicated, not LAN dedicated
com_dedicated = Cvar_Get( "dedicated", "2", CVAR_INIT );
Cvar_CheckRange( com_dedicated, 2, 2, qtrue );
#else
com_dedicated = Cvar_Get( "dedicated", "0", CVAR_LATCH );
Cvar_CheckRange( com_dedicated, 0, 2, qtrue );
#endif
// allocate the stack based hunk allocator
Com_InitHunkMemory();
// if any archived cvars are modified after this, we will trigger a writing
// of the config file
cvar_modifiedFlags &= ~CVAR_ARCHIVE;
//
// init commands and vars
//
com_altivec = Cvar_Get ("com_altivec", "1", CVAR_ARCHIVE);
com_maxfps = Cvar_Get( "com_maxfps", "76", CVAR_ARCHIVE | CVAR_LATCH );
com_blood = Cvar_Get( "com_blood", "1", CVAR_ARCHIVE );
com_logfile = Cvar_Get( "logfile", "0", CVAR_TEMP );
com_timescale = Cvar_Get( "timescale", "1", CVAR_CHEAT | CVAR_SYSTEMINFO );
com_fixedtime = Cvar_Get( "fixedtime", "0", CVAR_CHEAT );
com_showtrace = Cvar_Get( "com_showtrace", "0", CVAR_CHEAT );
com_speeds = Cvar_Get( "com_speeds", "0", 0 );
com_timedemo = Cvar_Get( "timedemo", "0", CVAR_CHEAT );
com_cameraMode = Cvar_Get( "com_cameraMode", "0", CVAR_CHEAT );
cl_paused = Cvar_Get( "cl_paused", "0", CVAR_ROM );
sv_paused = Cvar_Get( "sv_paused", "0", CVAR_ROM );
cl_packetdelay = Cvar_Get ("cl_packetdelay", "0", CVAR_CHEAT);
sv_packetdelay = Cvar_Get ("sv_packetdelay", "0", CVAR_CHEAT);
com_sv_running = Cvar_Get( "sv_running", "0", CVAR_ROM );
com_cl_running = Cvar_Get( "cl_running", "0", CVAR_ROM );
com_buildScript = Cvar_Get( "com_buildScript", "0", 0 );
com_ansiColor = Cvar_Get( "com_ansiColor", "0", CVAR_ARCHIVE );
com_unfocused = Cvar_Get( "com_unfocused", "0", CVAR_ROM );
com_maxfpsUnfocused = Cvar_Get( "com_maxfpsUnfocused", "0", CVAR_ARCHIVE );
com_minimized = Cvar_Get( "com_minimized", "0", CVAR_ROM );
com_maxfpsMinimized = Cvar_Get( "com_maxfpsMinimized", "0", CVAR_ARCHIVE );
com_abnormalExit = Cvar_Get( "com_abnormalExit", "0", CVAR_ROM );
com_busyWait = Cvar_Get("com_busyWait", "0", CVAR_ARCHIVE);
Cvar_Get("com_errorMessage", "", CVAR_ROM | CVAR_NORESTART);
#ifdef CINEMATICS_INTRO
com_introPlayed = Cvar_Get( "com_introplayed", "0", CVAR_ARCHIVE );
#endif
com_recommendedSet = Cvar_Get( "com_recommendedSet", "0", CVAR_ARCHIVE );
s = va( "%s %s %s", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
t = va( "%s %s %s", OLDVERSION, PLATFORM_STRING, PRODUCT_DATE );
com_fsgame = Cvar_Get( "fs_game", "", CVAR_INIT | CVAR_SYSTEMINFO );
com_legacyversion = Cvar_Get( "com_legacyversion", "0", CVAR_ARCHIVE );
if ( strcmp(com_fsgame->string,"banimod") == 0 || strcmp(com_fsgame->string,"bani") == 0 || com_legacyversion->integer ) {
com_version = Cvar_Get( "version", t, CVAR_ROM | CVAR_SERVERINFO );
} else {
com_version = Cvar_Get( "version", s, CVAR_ROM | CVAR_SERVERINFO );
}
com_gamename = Cvar_Get("com_gamename", GAMENAME_FOR_MASTER, CVAR_SERVERINFO | CVAR_INIT);
com_protocol = Cvar_Get("com_protocol", va("%i", PROTOCOL_VERSION), CVAR_SERVERINFO | CVAR_INIT);
#ifdef LEGACY_PROTOCOL
com_legacyprotocol = Cvar_Get("com_legacyprotocol", va("%i", PROTOCOL_LEGACY_VERSION), CVAR_INIT);
// Keep for compatibility with old mods / mods that haven't updated yet.
if(com_legacyprotocol->integer > 0)
Cvar_Get("protocol", com_legacyprotocol->string, CVAR_ROM);
else
#endif
Cvar_Get("protocol", com_protocol->string, CVAR_ROM);
com_hunkused = Cvar_Get( "com_hunkused", "0", 0 );
Sys_Init();
Sys_InitPIDFile( FS_GetCurrentGameDir() );
// Pick a random port value
Com_RandomBytes( (byte*)&qport, sizeof(int) );
Netchan_Init( qport & 0xffff );
VM_Init();
SV_Init();
com_dedicated->modified = qfalse;
#ifndef DEDICATED
CL_Init();
#endif
// set com_frameTime so that if a map is started on the
// command line it will still be able to count on com_frameTime
// being random enough for a serverid
com_frameTime = Com_Milliseconds();
// add + commands from command line
if ( !Com_AddStartupCommands() ) {
// if the user didn't give any commands, run default action
}
// start in full screen ui mode
Cvar_Set( "r_uiFullScreen", "1" );
CL_StartHunkUsers( qfalse );
// NERVE - SMF - force recommendedSet and don't do vid_restart if in safe mode
if ( !com_recommendedSet->integer && !safeMode ) {
Com_SetRecommended();
Cbuf_ExecuteText( EXEC_APPEND, "vid_restart\n" );
}
Cvar_Set( "com_recommendedSet", "1" );
if ( !com_dedicated->integer ) {
#ifdef CINEMATICS_LOGO
Cbuf_AddText( "cinematic " CINEMATICS_LOGO "\n" );
#endif
#ifdef CINEMATICS_INTRO
if ( !com_introPlayed->integer ) {
Cvar_Set( com_introPlayed->name, "1" );
Cvar_Set( "nextmap", "cinematic " CINEMATICS_INTRO );
}
#endif
}
com_fullyInitialized = qtrue;
// always set the cvar, but only print the info if it makes sense.
Com_DetectAltivec();
#if idppc
Com_Printf ("Altivec support is %s\n", com_altivec->integer ? "enabled" : "disabled");
#endif
com_pipefile = Cvar_Get( "com_pipefile", "", CVAR_ARCHIVE|CVAR_LATCH );
if( com_pipefile->string[0] )
{
pipefile = FS_FCreateOpenPipeFile( com_pipefile->string );
}
Com_Printf ("--- Common Initialization Complete ---\n");
}
/*
===============
Com_ReadFromPipe
Read whatever is in com_pipefile, if anything, and execute it
===============
*/
void Com_ReadFromPipe( void )
{
static char buf[MAX_STRING_CHARS];
static int accu = 0;
int read;
if( !pipefile )
return;
while( ( read = FS_Read( buf + accu, sizeof( buf ) - accu - 1, pipefile ) ) > 0 )
{
char *brk = NULL;
int i;
for( i = accu; i < accu + read; ++i )
{
if( buf[ i ] == '\0' )
buf[ i ] = '\n';
if( buf[ i ] == '\n' || buf[ i ] == '\r' )
brk = &buf[ i + 1 ];
}
buf[ accu + read ] = '\0';
accu += read;
if( brk )
{
char tmp = *brk;
*brk = '\0';
Cbuf_ExecuteText( EXEC_APPEND, buf );
*brk = tmp;
accu -= brk - buf;
memmove( buf, brk, accu + 1 );
}
else if( accu >= sizeof( buf ) - 1 ) // full
{
Cbuf_ExecuteText( EXEC_APPEND, buf );
accu = 0;
}
}
}
//==================================================================
void Com_WriteConfigToFile( const char *filename ) {
fileHandle_t f;
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf( "Couldn't write %s.\n", filename );
return;
}
FS_Printf( f, "// generated by RTCW, do not modify\n" );
Key_WriteBindings( f );
Cvar_WriteVariables( f );
FS_FCloseFile( f );
}
/*
===============
Com_WriteConfiguration
Writes key bindings and archived cvars to config file if modified
===============
*/
void Com_WriteConfiguration( void ) {
#if !defined(DEDICATED) && !defined(STANDALONE)
cvar_t *fs;
#endif
// if we are quiting without fully initializing, make sure
// we don't write out anything
if ( !com_fullyInitialized ) {
return;
}
if ( !( cvar_modifiedFlags & CVAR_ARCHIVE ) ) {
return;
}
cvar_modifiedFlags &= ~CVAR_ARCHIVE;
Com_WriteConfigToFile( Q3CONFIG_CFG );
// not needed for dedicated or standalone
#if !defined(DEDICATED) && !defined(STANDALONE)
fs = Cvar_Get( "fs_game", "", CVAR_INIT | CVAR_SYSTEMINFO );
if(!com_standalone->integer)
{
if (UI_usesUniqueCDKey() && fs && fs->string[0] != 0) {
Com_WriteCDKey( fs->string, &cl_cdkey[16] );
} else {
Com_WriteCDKey( BASEGAME, cl_cdkey );
}
}
#endif
}
/*
===============
Com_WriteConfig_f
Write the config file to a specific name
===============
*/
void Com_WriteConfig_f( void ) {
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: writeconfig <filename>\n" );
return;
}
if (!COM_CompareExtension(filename, ".cfg"))
{
Com_Printf("Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n");
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
Com_Printf( "Writing %s.\n", filename );
Com_WriteConfigToFile( filename );
}
/*
================
Com_ModifyMsec
================
*/
int Com_ModifyMsec( int msec ) {
int clampTime;
//
// modify time for debugging values
//
if ( com_fixedtime->integer ) {
msec = com_fixedtime->integer;
} else if ( com_timescale->value ) {
msec *= com_timescale->value;
// } else if (com_cameraMode->integer) {
// msec *= com_timescale->value;
}
// don't let it scale below 1 msec
if ( msec < 1 && com_timescale->value ) {
msec = 1;
}
if ( com_dedicated->integer ) {
// dedicated servers don't want to clamp for a much longer
// period, because it would mess up all the client's views
// of time.
if ( com_sv_running->integer && msec > 500 && msec < 500000 ) {
Com_Printf( "Hitch warning: %i msec frame time\n", msec );
}
clampTime = 5000;
} else
if ( !com_sv_running->integer ) {
// clients of remote servers do not want to clamp time, because
// it would skew their view of the server's time temporarily
clampTime = 5000;
} else {
// for local single player gaming
// we may want to clamp the time to prevent players from
// flying off edges when something hitches.
clampTime = 200;
}
if ( msec > clampTime ) {
msec = clampTime;
}
return msec;
}
/*
=================
Com_TimeVal
=================
*/
int Com_TimeVal(int minMsec)
{
int timeVal;
timeVal = Sys_Milliseconds() - com_frameTime;
if(timeVal >= minMsec)
timeVal = 0;
else
timeVal = minMsec - timeVal;
return timeVal;
}
/*
=================
Com_Frame
=================
*/
void Com_Frame( void ) {
int msec, minMsec;
int timeVal, timeValSV;
static int lastTime = 0, bias = 0;
int timeBeforeFirstEvents;
int timeBeforeServer;
int timeBeforeEvents;
int timeBeforeClient;
int timeAfter;
if ( setjmp( abortframe ) ) {
return; // an ERR_DROP was thrown
}
timeBeforeFirstEvents = 0;
timeBeforeServer = 0;
timeBeforeEvents = 0;
timeBeforeClient = 0;
timeAfter = 0;
// DHM - Nerve :: Don't write config on Update Server
#ifndef UPDATE_SERVER
// write config file if anything changed
Com_WriteConfiguration();
#endif
//
// main event loop
//
if ( com_speeds->integer ) {
timeBeforeFirstEvents = Sys_Milliseconds();
}
// Figure out how much time we have
if(!com_timedemo->integer)
{
if(com_dedicated->integer)
minMsec = SV_FrameMsec();
else
{
if(com_minimized->integer && com_maxfpsMinimized->integer > 0)
minMsec = 1000 / com_maxfpsMinimized->integer;
else if(com_unfocused->integer && com_maxfpsUnfocused->integer > 0)
minMsec = 1000 / com_maxfpsUnfocused->integer;
else if(com_maxfps->integer > 0)
minMsec = 1000 / com_maxfps->integer;
else
minMsec = 1;
timeVal = com_frameTime - lastTime;
bias += timeVal - minMsec;
if(bias > minMsec)
bias = minMsec;
// Adjust minMsec if previous frame took too long to render so
// that framerate is stable at the requested value.
minMsec -= bias;
}
}
else
minMsec = 1;
do
{
if(com_sv_running->integer)
{
timeValSV = SV_SendQueuedPackets();
timeVal = Com_TimeVal(minMsec);
if(timeValSV < timeVal)
timeVal = timeValSV;
}
else
timeVal = Com_TimeVal(minMsec);
if(com_busyWait->integer || timeVal < 1)
NET_Sleep(0);
else
NET_Sleep(timeVal - 1);
} while(Com_TimeVal(minMsec));
lastTime = com_frameTime;
com_frameTime = Com_EventLoop();
msec = com_frameTime - lastTime;
Cbuf_Execute();
if (com_altivec->modified)
{
Com_DetectAltivec();
com_altivec->modified = qfalse;
}
// mess with msec if needed
msec = Com_ModifyMsec(msec);
//
// server side
//
if ( com_speeds->integer ) {
timeBeforeServer = Sys_Milliseconds();
}
SV_Frame( msec );
// if "dedicated" has been modified, start up
// or shut down the client system.
// Do this after the server may have started,
// but before the client tries to auto-connect
if ( com_dedicated->modified ) {
// get the latched value
Cvar_Get( "dedicated", "0", 0 );
com_dedicated->modified = qfalse;
if ( !com_dedicated->integer ) {
SV_Shutdown( "dedicated set to 0" );
CL_FlushMemory();
}
}
#ifndef DEDICATED
//
// client system
//
//
// run event loop a second time to get server to client packets
// without a frame of latency
//
if ( com_speeds->integer ) {
timeBeforeEvents = Sys_Milliseconds ();
}
Com_EventLoop();
Cbuf_Execute ();
//
// client side
//
if ( com_speeds->integer ) {
timeBeforeClient = Sys_Milliseconds ();
}
CL_Frame( msec );
if ( com_speeds->integer ) {
timeAfter = Sys_Milliseconds ();
}
#else
if ( com_speeds->integer ) {
timeAfter = Sys_Milliseconds ();
timeBeforeEvents = timeAfter;
timeBeforeClient = timeAfter;
}
#endif
NET_FlushPacketQueue();
//
// report timing information
//
if ( com_speeds->integer ) {
int all, sv, ev, cl;
all = timeAfter - timeBeforeServer;
sv = timeBeforeEvents - timeBeforeServer;
ev = timeBeforeServer - timeBeforeFirstEvents + timeBeforeClient - timeBeforeEvents;
cl = timeAfter - timeBeforeClient;
sv -= time_game;
cl -= time_frontend + time_backend;
Com_Printf( "frame:%i all:%3i sv:%3i ev:%3i cl:%3i gm:%3i rf:%3i bk:%3i\n",
com_frameNumber, all, sv, ev, cl, time_game, time_frontend, time_backend );
}
//
// trace optimization tracking
//
if ( com_showtrace->integer ) {
extern int c_traces, c_brush_traces, c_patch_traces;
extern int c_pointcontents;
Com_Printf( "%4i traces (%ib %ip) %4i points\n", c_traces,
c_brush_traces, c_patch_traces, c_pointcontents );
c_traces = 0;
c_brush_traces = 0;
c_patch_traces = 0;
c_pointcontents = 0;
}
Com_ReadFromPipe( );
com_frameNumber++;
}
/*
=================
Com_Shutdown
=================
*/
void Com_Shutdown( void ) {
// write config file if anything changed
Com_WriteConfiguration();
if ( logfile ) {
FS_FCloseFile( logfile );
logfile = 0;
}
if ( com_journalFile ) {
FS_FCloseFile( com_journalFile );
com_journalFile = 0;
}
if( pipefile ) {
FS_FCloseFile( pipefile );
FS_HomeRemove( com_pipefile->string );
}
}
/*
===========================================
command line completion
===========================================
*/
/*
==================
Field_Clear
==================
*/
void Field_Clear( field_t *edit ) {
memset( edit->buffer, 0, MAX_EDIT_LINE );
edit->cursor = 0;
edit->scroll = 0;
}
static const char *completionString;
static char shortestMatch[MAX_TOKEN_CHARS];
static int matchCount;
// field we are working on, passed to Field_AutoComplete(&g_consoleCommand for instance)
static field_t *completionField;
/*
===============
FindMatches
===============
*/
static void FindMatches( const char *s ) {
int i;
if ( Q_stricmpn( s, completionString, strlen( completionString ) ) ) {
return;
}
matchCount++;
if ( matchCount == 1 ) {
Q_strncpyz( shortestMatch, s, sizeof( shortestMatch ) );
return;
}
// cut shortestMatch to the amount common with s
for ( i = 0 ; shortestMatch[i] ; i++ ) {
if ( i >= strlen( s ) ) {
shortestMatch[i] = 0;
break;
}
if ( tolower( shortestMatch[i] ) != tolower( s[i] ) ) {
shortestMatch[i] = 0;
}
}
}
/*
===============
PrintMatches
===============
*/
static void PrintMatches( const char *s ) {
if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
Com_Printf( " %s\n", s );
}
}
/*
===============
PrintCvarMatches
===============
*/
static void PrintCvarMatches( const char *s ) {
char value[ TRUNCATE_LENGTH ];
if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
Com_TruncateLongString( value, Cvar_VariableString( s ) );
Com_Printf( " %s = \"%s\"\n", s, value );
}
}
/*
===============
Field_FindFirstSeparator
===============
*/
static char *Field_FindFirstSeparator( char *s )
{
int i;
for( i = 0; i < strlen( s ); i++ )
{
if( s[ i ] == ';' )
return &s[ i ];
}
return NULL;
}
/*
===============
Field_Complete
===============
*/
static qboolean Field_Complete( void )
{
int completionOffset;
if( matchCount == 0 )
return qtrue;
completionOffset = strlen( completionField->buffer ) - strlen( completionString );
Q_strncpyz( &completionField->buffer[ completionOffset ], shortestMatch,
sizeof( completionField->buffer ) - completionOffset );
completionField->cursor = strlen( completionField->buffer );
if( matchCount == 1 )
{
Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " );
completionField->cursor++;
return qtrue;
}
Com_Printf( "]%s\n", completionField->buffer );
return qfalse;
}
#ifndef DEDICATED
/*
===============
Field_CompleteKeyname
===============
*/
void Field_CompleteKeyname( void )
{
matchCount = 0;
shortestMatch[ 0 ] = 0;
Key_KeynameCompletion( FindMatches );
if( !Field_Complete( ) )
Key_KeynameCompletion( PrintMatches );
}
#endif
/*
===============
Field_CompleteFilename
===============
*/
void Field_CompleteFilename( const char *dir,
const char *ext, qboolean stripExt, qboolean allowNonPureFilesOnDisk )
{
matchCount = 0;
shortestMatch[ 0 ] = 0;
FS_FilenameCompletion( dir, ext, stripExt, FindMatches, allowNonPureFilesOnDisk );
if( !Field_Complete( ) )
FS_FilenameCompletion( dir, ext, stripExt, PrintMatches, allowNonPureFilesOnDisk );
}
/*
===============
Field_CompleteCommand
===============
*/
void Field_CompleteCommand( char *cmd,
qboolean doCommands, qboolean doCvars )
{
int completionArgument = 0;
// Skip leading whitespace and quotes
cmd = Com_SkipCharset( cmd, " \"" );
Cmd_TokenizeStringIgnoreQuotes( cmd );
completionArgument = Cmd_Argc( );
// If there is trailing whitespace on the cmd
if( *( cmd + strlen( cmd ) - 1 ) == ' ' )
{
completionString = "";
completionArgument++;
}
else
completionString = Cmd_Argv( completionArgument - 1 );
#ifndef DEDICATED
// Unconditionally add a '\' to the start of the buffer
if( completionField->buffer[ 0 ] &&
completionField->buffer[ 0 ] != '\\' )
{
if( completionField->buffer[ 0 ] != '/' )
{
// Buffer is full, refuse to complete
if( strlen( completionField->buffer ) + 1 >=
sizeof( completionField->buffer ) )
return;
memmove( &completionField->buffer[ 1 ],
&completionField->buffer[ 0 ],
strlen( completionField->buffer ) + 1 );
completionField->cursor++;
}
completionField->buffer[ 0 ] = '\\';
}
#endif
if( completionArgument > 1 )
{
const char *baseCmd = Cmd_Argv( 0 );
char *p;
#ifndef DEDICATED
// This should always be true
if( baseCmd[ 0 ] == '\\' || baseCmd[ 0 ] == '/' )
baseCmd++;
#endif
if( ( p = Field_FindFirstSeparator( cmd ) ) )
Field_CompleteCommand( p + 1, qtrue, qtrue ); // Compound command
else
Cmd_CompleteArgument( baseCmd, cmd, completionArgument );
}
else
{
if( completionString[0] == '\\' || completionString[0] == '/' )
completionString++;
matchCount = 0;
shortestMatch[ 0 ] = 0;
if( strlen( completionString ) == 0 )
return;
if( doCommands )
Cmd_CommandCompletion( FindMatches );
if( doCvars )
Cvar_CommandCompletion( FindMatches );
if( !Field_Complete( ) )
{
// run through again, printing matches
if( doCommands )
Cmd_CommandCompletion( PrintMatches );
if( doCvars )
Cvar_CommandCompletion( PrintCvarMatches );
}
}
}
/*
===============
Field_AutoComplete
Perform Tab expansion
===============
*/
void Field_AutoComplete( field_t *field )
{
completionField = field;
Field_CompleteCommand( completionField->buffer, qtrue, qtrue );
}
/*
==================
Com_RandomBytes
fills string array with len random bytes, peferably from the OS randomizer
==================
*/
void Com_RandomBytes( byte *string, int len )
{
int i;
if( Sys_RandomBytes( string, len ) )
return;
Com_Printf( "Com_RandomBytes: using weak randomization\n" );
for( i = 0; i < len; i++ )
string[i] = (unsigned char)( rand() % 256 );
}
/*
==================
Com_IsVoipTarget
Returns non-zero if given clientNum is enabled in voipTargets, zero otherwise.
If clientNum is negative return if any bit is set.
==================
*/
qboolean Com_IsVoipTarget(uint8_t *voipTargets, int voipTargetsSize, int clientNum)
{
int index;
if(clientNum < 0)
{
for(index = 0; index < voipTargetsSize; index++)
{
if(voipTargets[index])
return qtrue;
}
return qfalse;
}
index = clientNum >> 3;
if(index < voipTargetsSize)
return (voipTargets[index] & (1 << (clientNum & 0x07)));
return qfalse;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3231_1 |
crossvul-cpp_data_bad_3151_2 | /*
* Copyright (C) 2014-2016 Firejail Authors
*
* This file is part of firejail 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "firejail.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <syslog.h>
#include <errno.h>
#include <dirent.h>
#include <grp.h>
#include <ftw.h>
#include <sys/ioctl.h>
#include <termios.h>
#define MAX_GROUPS 1024
// drop privileges
// - for root group or if nogroups is set, supplementary groups are not configured
void drop_privs(int nogroups) {
gid_t gid = getgid();
// configure supplementary groups
if (gid == 0 || nogroups) {
if (setgroups(0, NULL) < 0)
errExit("setgroups");
if (arg_debug)
printf("Username %s, no supplementary groups\n", cfg.username);
}
else {
assert(cfg.username);
gid_t groups[MAX_GROUPS];
int ngroups = MAX_GROUPS;
int rv = getgrouplist(cfg.username, gid, groups, &ngroups);
if (arg_debug && rv) {
printf("Username %s, groups ", cfg.username);
int i;
for (i = 0; i < ngroups; i++)
printf("%u, ", groups[i]);
printf("\n");
}
if (rv == -1) {
fprintf(stderr, "Warning: cannot extract supplementary group list, dropping them\n");
if (setgroups(0, NULL) < 0)
errExit("setgroups");
}
else {
rv = setgroups(ngroups, groups);
if (rv) {
fprintf(stderr, "Warning: cannot set supplementary group list, dropping them\n");
if (setgroups(0, NULL) < 0)
errExit("setgroups");
}
}
}
// set uid/gid
if (setgid(getgid()) < 0)
errExit("setgid/getgid");
if (setuid(getuid()) < 0)
errExit("setuid/getuid");
}
int mkpath_as_root(const char* path) {
assert(path && *path);
// work on a copy of the path
char *file_path = strdup(path);
if (!file_path)
errExit("strdup");
char* p;
int done = 0;
for (p=strchr(file_path+1, '/'); p; p=strchr(p+1, '/')) {
*p='\0';
if (mkdir(file_path, 0755)==-1) {
if (errno != EEXIST) {
*p='/';
free(file_path);
return -1;
}
}
else {
if (chmod(file_path, 0755) == -1)
errExit("chmod");
if (chown(file_path, 0, 0) == -1)
errExit("chown");
done = 1;
}
*p='/';
}
if (done)
fs_logger2("mkpath", path);
free(file_path);
return 0;
}
void logsignal(int s) {
if (!arg_debug)
return;
openlog("firejail", LOG_NDELAY | LOG_PID, LOG_USER);
syslog(LOG_INFO, "Signal %d caught", s);
closelog();
}
void logmsg(const char *msg) {
if (!arg_debug)
return;
openlog("firejail", LOG_NDELAY | LOG_PID, LOG_USER);
syslog(LOG_INFO, "%s\n", msg);
closelog();
}
void logargs(int argc, char **argv) {
if (!arg_debug)
return;
int i;
int len = 0;
// calculate message length
for (i = 0; i < argc; i++)
len += strlen(argv[i]) + 1; // + ' '
// build message
char msg[len + 1];
char *ptr = msg;
for (i = 0; i < argc; i++) {
sprintf(ptr, "%s ", argv[i]);
ptr += strlen(ptr);
}
// log message
logmsg(msg);
}
void logerr(const char *msg) {
if (!arg_debug)
return;
openlog("firejail", LOG_NDELAY | LOG_PID, LOG_USER);
syslog(LOG_ERR, "%s\n", msg);
closelog();
}
// return -1 if error, 0 if no error
int copy_file(const char *srcname, const char *destname) {
assert(srcname);
assert(destname);
// open source
int src = open(srcname, O_RDONLY);
if (src < 0) {
fprintf(stderr, "Warning: cannot open %s, file not copied\n", srcname);
return -1;
}
// open destination
int dst = open(destname, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (dst < 0) {
fprintf(stderr, "Warning: cannot open %s, file not copied\n", destname);
close(src);
return -1;
}
// copy
ssize_t len;
static const int BUFLEN = 1024;
unsigned char buf[BUFLEN];
while ((len = read(src, buf, BUFLEN)) > 0) {
int done = 0;
while (done != len) {
int rv = write(dst, buf + done, len - done);
if (rv == -1) {
close(src);
close(dst);
return -1;
}
done += rv;
}
}
close(src);
close(dst);
return 0;
}
// return 1 if the file is a directory
int is_dir(const char *fname) {
assert(fname);
if (*fname == '\0')
return 0;
// if fname doesn't end in '/', add one
int rv;
struct stat s;
if (fname[strlen(fname) - 1] == '/')
rv = stat(fname, &s);
else {
char *tmp;
if (asprintf(&tmp, "%s/", fname) == -1) {
fprintf(stderr, "Error: cannot allocate memory, %s:%d\n", __FILE__, __LINE__);
errExit("asprintf");
}
rv = stat(tmp, &s);
free(tmp);
}
if (rv == -1)
return 0;
if (S_ISDIR(s.st_mode))
return 1;
return 0;
}
// return 1 if the file is a link
int is_link(const char *fname) {
assert(fname);
if (*fname == '\0')
return 0;
struct stat s;
if (lstat(fname, &s) == 0) {
if (S_ISLNK(s.st_mode))
return 1;
}
return 0;
}
// remove multiple spaces and return allocated memory
char *line_remove_spaces(const char *buf) {
assert(buf);
if (strlen(buf) == 0)
return NULL;
// allocate memory for the new string
char *rv = malloc(strlen(buf) + 1);
if (rv == NULL)
errExit("malloc");
// remove space at start of line
const char *ptr1 = buf;
while (*ptr1 == ' ' || *ptr1 == '\t')
ptr1++;
// copy data and remove additional spaces
char *ptr2 = rv;
int state = 0;
while (*ptr1 != '\0') {
if (*ptr1 == '\n' || *ptr1 == '\r')
break;
if (state == 0) {
if (*ptr1 != ' ' && *ptr1 != '\t')
*ptr2++ = *ptr1++;
else {
*ptr2++ = ' ';
ptr1++;
state = 1;
}
}
else { // state == 1
while (*ptr1 == ' ' || *ptr1 == '\t')
ptr1++;
state = 0;
}
}
// strip last blank character if any
if (ptr2 > rv && *(ptr2 - 1) == ' ')
--ptr2;
*ptr2 = '\0';
// if (arg_debug)
// printf("Processing line #%s#\n", rv);
return rv;
}
char *split_comma(char *str) {
if (str == NULL || *str == '\0')
return NULL;
char *ptr = strchr(str, ',');
if (!ptr)
return NULL;
*ptr = '\0';
ptr++;
if (*ptr == '\0')
return NULL;
return ptr;
}
int not_unsigned(const char *str) {
int rv = 0;
const char *ptr = str;
while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0') {
if (!isdigit(*ptr)) {
rv = 1;
break;
}
ptr++;
}
return rv;
}
#define BUFLEN 4096
// find the first child for this parent; return 1 if error
int find_child(pid_t parent, pid_t *child) {
*child = 0; // use it to flag a found child
DIR *dir;
if (!(dir = opendir("/proc"))) {
// sleep 2 seconds and try again
sleep(2);
if (!(dir = opendir("/proc"))) {
fprintf(stderr, "Error: cannot open /proc directory\n");
exit(1);
}
}
struct dirent *entry;
char *end;
while (*child == 0 && (entry = readdir(dir))) {
pid_t pid = strtol(entry->d_name, &end, 10);
if (end == entry->d_name || *end)
continue;
if (pid == parent)
continue;
// open stat file
char *file;
if (asprintf(&file, "/proc/%u/status", pid) == -1) {
perror("asprintf");
exit(1);
}
FILE *fp = fopen(file, "r");
if (!fp) {
free(file);
continue;
}
// look for firejail executable name
char buf[BUFLEN];
while (fgets(buf, BUFLEN - 1, fp)) {
if (strncmp(buf, "PPid:", 5) == 0) {
char *ptr = buf + 5;
while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t')) {
ptr++;
}
if (*ptr == '\0') {
fprintf(stderr, "Error: cannot read /proc file\n");
exit(1);
}
if (parent == atoi(ptr))
*child = pid;
break; // stop reading the file
}
}
fclose(fp);
free(file);
}
closedir(dir);
return (*child)? 0:1; // 0 = found, 1 = not found
}
void extract_command_name(int index, char **argv) {
assert(argv);
assert(argv[index]);
// configure command index
cfg.original_program_index = index;
char *str = strdup(argv[index]);
if (!str)
errExit("strdup");
// if we have a symbolic link, use the real path to extract the name
if (is_link(argv[index])) {
char*newname = realpath(argv[index], NULL);
if (newname) {
free(str);
str = newname;
}
}
// configure command name
cfg.command_name = str;
if (!cfg.command_name)
errExit("strdup");
// restrict the command name to the first word
char *ptr = cfg.command_name;
while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0')
ptr++;
*ptr = '\0';
// remove the path: /usr/bin/firefox becomes firefox
ptr = strrchr(cfg.command_name, '/');
if (ptr) {
ptr++;
if (*ptr == '\0') {
fprintf(stderr, "Error: invalid command name\n");
exit(1);
}
char *tmp = strdup(ptr);
if (!tmp)
errExit("strdup");
// limit the command to the first '.'
char *ptr2 = tmp;
while (*ptr2 != '.' && *ptr2 != '\0')
ptr2++;
*ptr2 = '\0';
free(cfg.command_name);
cfg.command_name = tmp;
}
}
void update_map(char *mapping, char *map_file) {
int fd;
size_t j;
size_t map_len; /* Length of 'mapping' */
/* Replace commas in mapping string with newlines */
map_len = strlen(mapping);
for (j = 0; j < map_len; j++)
if (mapping[j] == ',')
mapping[j] = '\n';
fd = open(map_file, O_RDWR);
if (fd == -1) {
fprintf(stderr, "Error: cannot open %s: %s\n", map_file, strerror(errno));
exit(EXIT_FAILURE);
}
if (write(fd, mapping, map_len) != (ssize_t)map_len) {
fprintf(stderr, "Error: cannot write to %s: %s\n", map_file, strerror(errno));
exit(EXIT_FAILURE);
}
close(fd);
}
void wait_for_other(int fd) {
//****************************
// wait for the parent to be initialized
//****************************
char childstr[BUFLEN + 1];
int newfd = dup(fd);
if (newfd == -1)
errExit("dup");
FILE* stream;
stream = fdopen(newfd, "r");
*childstr = '\0';
if (fgets(childstr, BUFLEN, stream)) {
// remove \n)
char *ptr = childstr;
while(*ptr !='\0' && *ptr != '\n')
ptr++;
if (*ptr == '\0')
errExit("fgets");
*ptr = '\0';
}
else {
fprintf(stderr, "Error: cannot establish communication with the parent, exiting...\n");
exit(1);
}
fclose(stream);
}
void notify_other(int fd) {
FILE* stream;
int newfd = dup(fd);
if (newfd == -1)
errExit("dup");
stream = fdopen(newfd, "w");
fprintf(stream, "%u\n", getpid());
fflush(stream);
fclose(stream);
}
// This function takes a pathname supplied by the user and expands '~' and
// '${HOME}' at the start, to refer to a path relative to the user's home
// directory (supplied).
// The return value is allocated using malloc and must be freed by the caller.
// The function returns NULL if there are any errors.
char *expand_home(const char *path, const char* homedir)
{
assert(path);
assert(homedir);
// Replace home macro
char *new_name = NULL;
if (strncmp(path, "${HOME}", 7) == 0) {
if (asprintf(&new_name, "%s%s", homedir, path + 7) == -1)
errExit("asprintf");
return new_name;
}
else if (strncmp(path, "~/", 2) == 0) {
if (asprintf(&new_name, "%s%s", homedir, path + 1) == -1)
errExit("asprintf");
return new_name;
}
return strdup(path);
}
// Equivalent to the GNU version of basename, which is incompatible with
// the POSIX basename. A few lines of code saves any portability pain.
// https://www.gnu.org/software/libc/manual/html_node/Finding-Tokens-in-a-String.html#index-basename
const char *gnu_basename(const char *path)
{
const char *last_slash = strrchr(path, '/');
if (!last_slash)
return path;
return last_slash+1;
}
uid_t pid_get_uid(pid_t pid) {
uid_t rv = 0;
// open status file
char *file;
if (asprintf(&file, "/proc/%u/status", pid) == -1) {
perror("asprintf");
exit(1);
}
FILE *fp = fopen(file, "r");
if (!fp) {
free(file);
fprintf(stderr, "Error: cannot open /proc file\n");
exit(1);
}
// extract uid
static const int PIDS_BUFLEN = 1024;
char buf[PIDS_BUFLEN];
while (fgets(buf, PIDS_BUFLEN - 1, fp)) {
if (strncmp(buf, "Uid:", 4) == 0) {
char *ptr = buf + 5;
while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t')) {
ptr++;
}
if (*ptr == '\0')
break;
rv = atoi(ptr);
break; // break regardless!
}
}
fclose(fp);
free(file);
if (rv == 0) {
fprintf(stderr, "Error: cannot read /proc file\n");
exit(1);
}
return rv;
}
void invalid_filename(const char *fname) {
assert(fname);
const char *ptr = fname;
if (arg_debug_check_filename)
printf("Checking filename %s\n", fname);
if (strncmp(ptr, "${HOME}", 7) == 0)
ptr = fname + 7;
else if (strncmp(ptr, "${PATH}", 7) == 0)
ptr = fname + 7;
else if (strcmp(fname, "${DOWNLOADS}") == 0)
return;
int len = strlen(ptr);
// file globbing ('*') is allowed
if (strcspn(ptr, "\\&!?\"'<>%^(){}[];,") != (size_t)len) {
fprintf(stderr, "Error: \"%s\" is an invalid filename\n", ptr);
exit(1);
}
}
static int remove_callback(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
(void) sb;
(void) typeflag;
(void) ftwbuf;
int rv = remove(fpath);
if (rv)
perror(fpath);
return rv;
}
int remove_directory(const char *path) {
// FTW_PHYS - do not follow symbolic links
return nftw(path, remove_callback, 64, FTW_DEPTH | FTW_PHYS);
}
void flush_stdin(void) {
if (isatty(STDIN_FILENO)) {
int cnt = 0;
ioctl(STDIN_FILENO, FIONREAD, &cnt);
if (cnt) {
if (!arg_quiet)
printf("Warning: removing %d bytes from stdin\n", cnt);
ioctl(STDIN_FILENO, TCFLSH, TCIFLUSH);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3151_2 |
crossvul-cpp_data_good_3150_0 | /*
* Copyright (C) 2014-2016 Firejail Authors
*
* This file is part of firejail 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "firejail.h"
#include <sys/mount.h>
#include <linux/limits.h>
#include <glob.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <grp.h>
#include <ftw.h>
static void skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
// zsh
if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) {
// copy skel files
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat
fprintf(stderr, "Error: invalid %s file\n", fname);
exit(1);
}
if (stat("/etc/skel/.zshrc", &s) == 0) {
copy_file_as_user("/etc/skel/.zshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.zshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
// csh
else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) {
// copy skel files
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat
fprintf(stderr, "Error: invalid %s file\n", fname);
exit(1);
}
if (stat("/etc/skel/.cshrc", &s) == 0) {
copy_file_as_user("/etc/skel/.cshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.cshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
// bash etc.
else {
// copy skel files
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat
fprintf(stderr, "Error: invalid %s file\n", fname);
exit(1);
}
if (stat("/etc/skel/.bashrc", &s) == 0) {
copy_file_as_user("/etc/skel/.bashrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.bashrc");
}
free(fname);
}
}
static int store_xauthority(void) {
// put a copy of .Xauthority in XAUTHORITY_FILE
fs_build_mnt_dir();
char *src;
char *dest = RUN_XAUTHORITY_FILE;
// create an empty file as root, and change ownership to user
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0600);
fclose(fp);
}
if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Warning: invalid .Xauthority file\n");
return 0;
}
copy_file_as_user(src, dest, getuid(), getgid(), 0600);
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
static int store_asoundrc(void) {
// put a copy of .Xauthority in XAUTHORITY_FILE
fs_build_mnt_dir();
char *src;
char *dest = RUN_ASOUNDRC_FILE;
// create an empty file as root, and change ownership to user
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0644);
fclose(fp);
}
if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
// make sure the real path of the file is inside the home directory
/* coverity[toctou] */
char* rp = realpath(src, NULL);
if (!rp) {
fprintf(stderr, "Error: Cannot access %s\n", src);
exit(1);
}
if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n");
exit(1);
}
free(rp);
}
copy_file_as_user(src, dest, getuid(), getgid(), 0644);
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
static void copy_xauthority(void) {
// copy XAUTHORITY_FILE in the new home directory
char *src = RUN_XAUTHORITY_FILE ;
char *dest;
if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
// if destination is a symbolic link, exit the sandbox!!!
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR);
fs_logger2("clone", dest);
// delete the temporary file
unlink(src);
}
static void copy_asoundrc(void) {
// copy XAUTHORITY_FILE in the new home directory
char *src = RUN_ASOUNDRC_FILE ;
char *dest;
if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
// if destination is a symbolic link, exit the sandbox!!!
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR);
fs_logger2("clone", dest);
// delete the temporary file
unlink(src);
}
// private mode (--private=homedir):
// mount homedir on top of /home/user,
// tmpfs on top of /root in nonroot mode,
// set skel files,
// restore .Xauthority
void fs_private_homedir(void) {
char *homedir = cfg.homedir;
char *private_homedir = cfg.home_private;
assert(homedir);
assert(private_homedir);
int xflag = store_xauthority();
int aflag = store_asoundrc();
uid_t u = getuid();
gid_t g = getgid();
struct stat s;
if (stat(homedir, &s) == -1) {
fprintf(stderr, "Error: cannot find user home directory\n");
exit(1);
}
// mount bind private_homedir on top of homedir
if (arg_debug)
printf("Mount-bind %s on top of %s\n", private_homedir, homedir);
if (mount(private_homedir, homedir, NULL, MS_NOSUID | MS_NODEV | MS_BIND | MS_REC, NULL) < 0)
errExit("mount bind");
fs_logger3("mount-bind", private_homedir, cfg.homedir);
fs_logger2("whitelist", cfg.homedir);
// preserve mode and ownership
// if (chown(homedir, s.st_uid, s.st_gid) == -1)
// errExit("mount-bind chown");
// if (chmod(homedir, s.st_mode) == -1)
// errExit("mount-bind chmod");
if (u != 0) {
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting home directory");
fs_logger("tmpfs /root");
}
else {
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
fs_logger("tmpfs /home");
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
// private mode (--private):
// mount tmpfs over /home/user,
// tmpfs on top of /root in nonroot mode,
// set skel files,
// restore .Xauthority
void fs_private(void) {
char *homedir = cfg.homedir;
assert(homedir);
uid_t u = getuid();
gid_t g = getgid();
int xflag = store_xauthority();
int aflag = store_asoundrc();
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
fs_logger("tmpfs /home");
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting root directory");
fs_logger("tmpfs /root");
if (u != 0) {
// create /home/user
if (arg_debug)
printf("Create a new user directory\n");
if (mkdir(homedir, S_IRWXU) == -1) {
if (mkpath_as_root(homedir) == -1)
errExit("mkpath");
if (mkdir(homedir, S_IRWXU) == -1)
errExit("mkdir");
}
if (chown(homedir, u, g) < 0)
errExit("chown");
fs_logger2("mkdir", homedir);
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
// check new private home directory (--private= option) - exit if it fails
void fs_check_private_dir(void) {
EUID_ASSERT();
invalid_filename(cfg.home_private);
// Expand the home directory
char *tmp = expand_home(cfg.home_private, cfg.homedir);
cfg.home_private = realpath(tmp, NULL);
free(tmp);
if (!cfg.home_private
|| !is_dir(cfg.home_private)
|| is_link(cfg.home_private)
|| strstr(cfg.home_private, "..")) {
fprintf(stderr, "Error: invalid private directory\n");
exit(1);
}
// check home directory and chroot home directory have the same owner
struct stat s2;
int rv = stat(cfg.home_private, &s2);
if (rv < 0) {
fprintf(stderr, "Error: cannot find %s directory\n", cfg.home_private);
exit(1);
}
struct stat s1;
rv = stat(cfg.homedir, &s1);
if (rv < 0) {
fprintf(stderr, "Error: cannot find %s directory, full path name required\n", cfg.homedir);
exit(1);
}
if (s1.st_uid != s2.st_uid) {
printf("Error: --private directory should be owned by the current user\n");
exit(1);
}
}
//***********************************************************************************
// --private-home
//***********************************************************************************
#define PRIVATE_COPY_LIMIT (500 * 1024 *1024)
static int size_limit_reached = 0;
static unsigned file_cnt = 0;
static unsigned size_cnt = 0;
static char *check_dir_or_file(const char *name);
int fs_copydir(const char *path, const struct stat *st, int ftype, struct FTW *sftw) {
(void) st;
(void) sftw;
if (size_limit_reached)
return 0;
struct stat s;
char *dest;
if (asprintf(&dest, "%s%s", RUN_HOME_DIR, path + strlen(cfg.homedir)) == -1)
errExit("asprintf");
// don't copy it if we already have the file
if (stat(dest, &s) == 0) {
free(dest);
return 0;
}
// extract mode and ownership
if (stat(path, &s) != 0) {
free(dest);
return 0;
}
// check uid
if (s.st_uid != firejail_uid || s.st_gid != firejail_gid) {
free(dest);
return 0;
}
if ((s.st_size + size_cnt) > PRIVATE_COPY_LIMIT) {
size_limit_reached = 1;
free(dest);
return 0;
}
file_cnt++;
size_cnt += s.st_size;
if(ftype == FTW_F)
copy_file(path, dest, firejail_uid, firejail_gid, s.st_mode);
else if (ftype == FTW_D) {
if (mkdir(dest, s.st_mode) == -1)
errExit("mkdir");
if (chmod(dest, s.st_mode) < 0) {
fprintf(stderr, "Error: cannot change mode for %s\n", path);
exit(1);
}
if (chown(dest, firejail_uid, firejail_gid) < 0) {
fprintf(stderr, "Error: cannot change ownership for %s\n", path);
exit(1);
}
#if 0
struct stat s2;
if (stat(dest, &s2) == 0) {
printf("%s\t", dest);
printf((S_ISDIR(s.st_mode)) ? "d" : "-");
printf((s.st_mode & S_IRUSR) ? "r" : "-");
printf((s.st_mode & S_IWUSR) ? "w" : "-");
printf((s.st_mode & S_IXUSR) ? "x" : "-");
printf((s.st_mode & S_IRGRP) ? "r" : "-");
printf((s.st_mode & S_IWGRP) ? "w" : "-");
printf((s.st_mode & S_IXGRP) ? "x" : "-");
printf((s.st_mode & S_IROTH) ? "r" : "-");
printf((s.st_mode & S_IWOTH) ? "w" : "-");
printf((s.st_mode & S_IXOTH) ? "x" : "-");
printf("\n");
}
#endif
fs_logger2("clone", path);
}
free(dest);
return(0);
}
static void duplicate(char *name) {
char *fname = check_dir_or_file(name);
if (arg_debug)
printf("Private home: duplicating %s\n", fname);
assert(strncmp(fname, cfg.homedir, strlen(cfg.homedir)) == 0);
struct stat s;
if (stat(fname, &s) == -1) {
free(fname);
return;
}
if(nftw(fname, fs_copydir, 1, FTW_PHYS) != 0) {
fprintf(stderr, "Error: unable to copy template dir\n");
exit(1);
}
fs_logger_print(); // save the current log
free(fname);
}
static char *check_dir_or_file(const char *name) {
assert(name);
struct stat s;
// basic checks
invalid_filename(name);
if (arg_debug)
printf("Private home: checking %s\n", name);
// expand home directory
char *fname = expand_home(name, cfg.homedir);
if (!fname) {
fprintf(stderr, "Error: file %s not found.\n", name);
exit(1);
}
// If it doesn't start with '/', it must be relative to homedir
if (fname[0] != '/') {
char* tmp;
if (asprintf(&tmp, "%s/%s", cfg.homedir, fname) == -1)
errExit("asprintf");
free(fname);
fname = tmp;
}
// check the file is in user home directory
char *rname = realpath(fname, NULL);
if (!rname) {
fprintf(stderr, "Error: invalid file %s\n", name);
exit(1);
}
if (strncmp(rname, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: file %s is not in user home directory\n", name);
exit(1);
}
// a full home directory is not allowed
if (strcmp(rname, cfg.homedir) == 0) {
fprintf(stderr, "Error: invalid directory %s\n", rname);
exit(1);
}
// only top files and directories in user home are allowed
char *ptr = rname + strlen(cfg.homedir);
if (*ptr == '\0') {
fprintf(stderr, "Error: invalid file %s\n", name);
exit(1);
}
ptr++;
ptr = strchr(ptr, '/');
if (ptr) {
if (*ptr != '\0') {
fprintf(stderr, "Error: only top files and directories in user home are allowed\n");
exit(1);
}
}
if (stat(fname, &s) == -1) {
fprintf(stderr, "Error: file %s not found.\n", fname);
exit(1);
}
// check uid
uid_t uid = getuid();
gid_t gid = getgid();
if (s.st_uid != uid || s.st_gid != gid) {
fprintf(stderr, "Error: only files or directories created by the current user are allowed.\n");
exit(1);
}
// dir or regular file
if (S_ISDIR(s.st_mode) || S_ISREG(s.st_mode)) {
free(fname);
return rname; // regular exit from the function
}
fprintf(stderr, "Error: invalid file type, %s.\n", fname);
exit(1);
}
// check directory list specified by user (--private-home option) - exit if it fails
void fs_check_home_list(void) {
if (strstr(cfg.home_private_keep, "..")) {
fprintf(stderr, "Error: invalid private-home list\n");
exit(1);
}
char *dlist = strdup(cfg.home_private_keep);
if (!dlist)
errExit("strdup");
char *ptr = strtok(dlist, ",");
char *tmp = check_dir_or_file(ptr);
free(tmp);
while ((ptr = strtok(NULL, ",")) != NULL) {
tmp = check_dir_or_file(ptr);
free(tmp);
}
free(dlist);
}
// private mode (--private-home=list):
// mount homedir on top of /home/user,
// tmpfs on top of /root in nonroot mode,
// tmpfs on top of /tmp in root mode,
// set skel files,
// restore .Xauthority
void fs_private_home_list(void) {
char *homedir = cfg.homedir;
char *private_list = cfg.home_private_keep;
assert(homedir);
assert(private_list);
int xflag = store_xauthority();
int aflag = store_asoundrc();
uid_t u = firejail_uid;
gid_t g = firejail_gid;
struct stat s;
if (stat(homedir, &s) == -1) {
fprintf(stderr, "Error: cannot find user home directory\n");
exit(1);
}
// create /run/firejail/mnt/home directory
fs_build_mnt_dir();
int rv = mkdir(RUN_HOME_DIR, 0755);
if (rv == -1)
errExit("mkdir");
if (chown(RUN_HOME_DIR, u, g) < 0)
errExit("chown");
if (chmod(RUN_HOME_DIR, 0755) < 0)
errExit("chmod");
ASSERT_PERMS(RUN_HOME_DIR, u, g, 0755);
fs_logger_print(); // save the current log
// copy the list of files in the new home directory
// using a new child process without root privileges
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
if (arg_debug)
printf("Copying files in the new home:\n");
// drop privileges
if (setgroups(0, NULL) < 0)
errExit("setgroups");
if (setgid(getgid()) < 0)
errExit("setgid/getgid");
if (setuid(getuid()) < 0)
errExit("setuid/getuid");
// copy the list of files in the new home directory
char *dlist = strdup(cfg.home_private_keep);
if (!dlist)
errExit("strdup");
char *ptr = strtok(dlist, ",");
duplicate(ptr);
while ((ptr = strtok(NULL, ",")) != NULL)
duplicate(ptr);
if (!arg_quiet) {
if (size_limit_reached)
fprintf(stderr, "Warning: private-home copy limit of %u MB reached, not all the files were copied\n",
PRIVATE_COPY_LIMIT / (1024 *1024));
else
printf("Private home: %u files, total size %u bytes\n", file_cnt, size_cnt);
}
fs_logger_print(); // save the current log
free(dlist);
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
if (arg_debug)
printf("Mount-bind %s on top of %s\n", RUN_HOME_DIR, homedir);
if (mount(RUN_HOME_DIR, homedir, NULL, MS_BIND|MS_REC, NULL) < 0)
errExit("mount bind");
if (u != 0) {
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting home directory");
}
else {
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3150_0 |
crossvul-cpp_data_good_3233_3 | /*
===========================================================================
Return to Castle Wolfenstein single player GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein single player GPL Source Code (RTCW SP Source Code).
RTCW SP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW SP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
// cl_main.c -- client main loop
#include "client.h"
#include <limits.h>
#include "../sys/sys_local.h"
#include "../sys/sys_loadlib.h"
#ifdef USE_MUMBLE
#include "libmumblelink.h"
#endif
#ifdef USE_MUMBLE
cvar_t *cl_useMumble;
cvar_t *cl_mumbleScale;
#endif
#ifdef USE_VOIP
cvar_t *cl_voipUseVAD;
cvar_t *cl_voipVADThreshold;
cvar_t *cl_voipSend;
cvar_t *cl_voipSendTarget;
cvar_t *cl_voipGainDuringCapture;
cvar_t *cl_voipCaptureMult;
cvar_t *cl_voipShowMeter;
cvar_t *cl_voipProtocol;
cvar_t *cl_voip;
#endif
#ifdef USE_RENDERER_DLOPEN
cvar_t *cl_renderer;
#endif
cvar_t *cl_nodelta;
cvar_t *cl_debugMove;
cvar_t *cl_noprint;
#ifdef UPDATE_SERVER_NAME
cvar_t *cl_motd;
#endif
cvar_t *rcon_client_password;
cvar_t *rconAddress;
cvar_t *cl_timeout;
cvar_t *cl_maxpackets;
cvar_t *cl_packetdup;
cvar_t *cl_timeNudge;
cvar_t *cl_showTimeDelta;
cvar_t *cl_freezeDemo;
cvar_t *cl_shownet = NULL; // NERVE - SMF - This is referenced in msg.c and we need to make sure it is NULL
cvar_t *cl_showSend;
cvar_t *cl_timedemo;
cvar_t *cl_timedemoLog;
cvar_t *cl_autoRecordDemo;
cvar_t *cl_aviFrameRate;
cvar_t *cl_aviMotionJpeg;
cvar_t *cl_avidemo;
cvar_t *cl_forceavidemo;
cvar_t *cl_freelook;
cvar_t *cl_sensitivity;
cvar_t *cl_mouseAccel;
cvar_t *cl_mouseAccelOffset;
cvar_t *cl_mouseAccelStyle;
cvar_t *cl_showMouseRate;
cvar_t *m_pitch;
cvar_t *m_yaw;
cvar_t *m_forward;
cvar_t *m_side;
cvar_t *m_filter;
cvar_t *j_pitch;
cvar_t *j_yaw;
cvar_t *j_forward;
cvar_t *j_side;
cvar_t *j_up;
cvar_t *j_pitch_axis;
cvar_t *j_yaw_axis;
cvar_t *j_forward_axis;
cvar_t *j_side_axis;
cvar_t *j_up_axis;
cvar_t *cl_activeAction;
cvar_t *cl_motdString;
cvar_t *cl_allowDownload;
cvar_t *cl_conXOffset;
cvar_t *cl_inGameVideo;
cvar_t *cl_serverStatusResendTime;
cvar_t *cl_missionStats;
cvar_t *cl_waitForFire;
// NERVE - SMF - localization
cvar_t *cl_language;
cvar_t *cl_debugTranslation;
// -NERVE - SMF
cvar_t *cl_lanForcePackets;
cvar_t *cl_guidServerUniq;
cvar_t *cl_consoleKeys;
cvar_t *cl_rate;
clientActive_t cl;
clientConnection_t clc;
clientStatic_t cls;
vm_t *cgvm;
char cl_reconnectArgs[MAX_OSPATH];
char cl_oldGame[MAX_QPATH];
qboolean cl_oldGameSet;
// Structure containing functions exported from refresh DLL
refexport_t re;
#ifdef USE_RENDERER_DLOPEN
static void *rendererLib = NULL;
#endif
ping_t cl_pinglist[MAX_PINGREQUESTS];
typedef struct serverStatus_s
{
char string[BIG_INFO_STRING];
netadr_t address;
int time, startTime;
qboolean pending;
qboolean print;
qboolean retrieved;
} serverStatus_t;
serverStatus_t cl_serverStatusList[MAX_SERVERSTATUSREQUESTS];
static int noGameRestart = qfalse;
extern void SV_BotFrame( int time );
void CL_CheckForResend( void );
void CL_ShowIP_f( void );
void CL_ServerStatus_f( void );
void CL_ServerStatusResponse( netadr_t from, msg_t *msg );
/*
==============
CL_EndgameMenu
Called by Com_Error when a game has ended and is dropping out to main menu in the "endgame" menu ('credits' right now)
==============
*/
void CL_EndgameMenu( void ) {
cls.endgamemenu = qtrue; // start it next frame
}
/*
===============
CL_CDDialog
Called by Com_Error when a cd is needed
===============
*/
void CL_CDDialog( void ) {
cls.cddialog = qtrue; // start it next frame
}
#ifdef USE_MUMBLE
static
void CL_UpdateMumble(void)
{
vec3_t pos, forward, up;
float scale = cl_mumbleScale->value;
float tmp;
if(!cl_useMumble->integer)
return;
// !!! FIXME: not sure if this is even close to correct.
AngleVectors( cl.snap.ps.viewangles, forward, NULL, up);
pos[0] = cl.snap.ps.origin[0] * scale;
pos[1] = cl.snap.ps.origin[2] * scale;
pos[2] = cl.snap.ps.origin[1] * scale;
tmp = forward[1];
forward[1] = forward[2];
forward[2] = tmp;
tmp = up[1];
up[1] = up[2];
up[2] = tmp;
if(cl_useMumble->integer > 1) {
fprintf(stderr, "%f %f %f, %f %f %f, %f %f %f\n",
pos[0], pos[1], pos[2],
forward[0], forward[1], forward[2],
up[0], up[1], up[2]);
}
mumble_update_coordinates(pos, forward, up);
}
#endif
#ifdef USE_VOIP
static
void CL_UpdateVoipIgnore(const char *idstr, qboolean ignore)
{
if ((*idstr >= '0') && (*idstr <= '9')) {
const int id = atoi(idstr);
if ((id >= 0) && (id < MAX_CLIENTS)) {
clc.voipIgnore[id] = ignore;
CL_AddReliableCommand(va("voip %s %d",
ignore ? "ignore" : "unignore", id), qfalse);
Com_Printf("VoIP: %s ignoring player #%d\n",
ignore ? "Now" : "No longer", id);
return;
}
}
Com_Printf("VoIP: invalid player ID#\n");
}
static
void CL_UpdateVoipGain(const char *idstr, float gain)
{
if ((*idstr >= '0') && (*idstr <= '9')) {
const int id = atoi(idstr);
if (gain < 0.0f)
gain = 0.0f;
if ((id >= 0) && (id < MAX_CLIENTS)) {
clc.voipGain[id] = gain;
Com_Printf("VoIP: player #%d gain now set to %f\n", id, gain);
}
}
}
void CL_Voip_f( void )
{
const char *cmd = Cmd_Argv(1);
const char *reason = NULL;
if (clc.state != CA_ACTIVE)
reason = "Not connected to a server";
else if (!clc.voipCodecInitialized)
reason = "Voip codec not initialized";
else if (!clc.voipEnabled)
reason = "Server doesn't support VoIP";
else if (!clc.demoplaying && (Cvar_VariableValue("g_gametype") == GT_SINGLE_PLAYER || Cvar_VariableValue("ui_singlePlayerActive")))
reason = "running in single-player mode";
if (reason != NULL) {
Com_Printf("VoIP: command ignored: %s\n", reason);
return;
}
if (strcmp(cmd, "ignore") == 0) {
CL_UpdateVoipIgnore(Cmd_Argv(2), qtrue);
} else if (strcmp(cmd, "unignore") == 0) {
CL_UpdateVoipIgnore(Cmd_Argv(2), qfalse);
} else if (strcmp(cmd, "gain") == 0) {
if (Cmd_Argc() > 3) {
CL_UpdateVoipGain(Cmd_Argv(2), atof(Cmd_Argv(3)));
} else if (Q_isanumber(Cmd_Argv(2))) {
int id = atoi(Cmd_Argv(2));
if (id >= 0 && id < MAX_CLIENTS) {
Com_Printf("VoIP: current gain for player #%d "
"is %f\n", id, clc.voipGain[id]);
} else {
Com_Printf("VoIP: invalid player ID#\n");
}
} else {
Com_Printf("usage: voip gain <playerID#> [value]\n");
}
} else if (strcmp(cmd, "muteall") == 0) {
Com_Printf("VoIP: muting incoming voice\n");
CL_AddReliableCommand("voip muteall", qfalse);
clc.voipMuteAll = qtrue;
} else if (strcmp(cmd, "unmuteall") == 0) {
Com_Printf("VoIP: unmuting incoming voice\n");
CL_AddReliableCommand("voip unmuteall", qfalse);
clc.voipMuteAll = qfalse;
} else {
Com_Printf("usage: voip [un]ignore <playerID#>\n"
" voip [un]muteall\n"
" voip gain <playerID#> [value]\n");
}
}
static
void CL_VoipNewGeneration(void)
{
// don't have a zero generation so new clients won't match, and don't
// wrap to negative so MSG_ReadLong() doesn't "fail."
clc.voipOutgoingGeneration++;
if (clc.voipOutgoingGeneration <= 0)
clc.voipOutgoingGeneration = 1;
clc.voipPower = 0.0f;
clc.voipOutgoingSequence = 0;
opus_encoder_ctl(clc.opusEncoder, OPUS_RESET_STATE);
}
/*
===============
CL_VoipParseTargets
sets clc.voipTargets according to cl_voipSendTarget
Generally we don't want who's listening to change during a transmission,
so this is only called when the key is first pressed
===============
*/
void CL_VoipParseTargets(void)
{
const char *target = cl_voipSendTarget->string;
char *end;
int val;
Com_Memset(clc.voipTargets, 0, sizeof(clc.voipTargets));
clc.voipFlags &= ~VOIP_SPATIAL;
while(target)
{
while(*target == ',' || *target == ' ')
target++;
if(!*target)
break;
if(isdigit(*target))
{
val = strtol(target, &end, 10);
target = end;
}
else
{
if(!Q_stricmpn(target, "all", 3))
{
Com_Memset(clc.voipTargets, ~0, sizeof(clc.voipTargets));
return;
}
if(!Q_stricmpn(target, "spatial", 7))
{
clc.voipFlags |= VOIP_SPATIAL;
target += 7;
continue;
}
else
{
if(!Q_stricmpn(target, "attacker", 8))
{
val = VM_Call(cgvm, CG_LAST_ATTACKER);
target += 8;
}
else if(!Q_stricmpn(target, "crosshair", 9))
{
val = VM_Call(cgvm, CG_CROSSHAIR_PLAYER);
target += 9;
}
else
{
while(*target && *target != ',' && *target != ' ')
target++;
continue;
}
if(val < 0)
continue;
}
}
if(val < 0 || val >= MAX_CLIENTS)
{
Com_Printf(S_COLOR_YELLOW "WARNING: VoIP "
"target %d is not a valid client "
"number\n", val);
continue;
}
clc.voipTargets[val / 8] |= 1 << (val % 8);
}
}
/*
===============
CL_CaptureVoip
Record more audio from the hardware if required and encode it into Opus
data for later transmission.
===============
*/
static
void CL_CaptureVoip(void)
{
const float audioMult = cl_voipCaptureMult->value;
const qboolean useVad = (cl_voipUseVAD->integer != 0);
qboolean initialFrame = qfalse;
qboolean finalFrame = qfalse;
#if USE_MUMBLE
// if we're using Mumble, don't try to handle VoIP transmission ourselves.
if (cl_useMumble->integer)
return;
#endif
// If your data rate is too low, you'll get Connection Interrupted warnings
// when VoIP packets arrive, even if you have a broadband connection.
// This might work on rates lower than 25000, but for safety's sake, we'll
// just demand it. Who doesn't have at least a DSL line now, anyhow? If
// you don't, you don't need VoIP. :)
if (cl_voip->modified || cl_rate->modified) {
if ((cl_voip->integer) && (cl_rate->integer < 25000)) {
Com_Printf(S_COLOR_YELLOW "Your network rate is too slow for VoIP.\n");
Com_Printf("Set 'Data Rate' to 'LAN/Cable/xDSL' in 'Setup/System/Network'.\n");
Com_Printf("Until then, VoIP is disabled.\n");
Cvar_Set("cl_voip", "0");
}
Cvar_Set("cl_voipProtocol", cl_voip->integer ? "opus" : "");
cl_voip->modified = qfalse;
cl_rate->modified = qfalse;
}
if (!clc.voipCodecInitialized)
return; // just in case this gets called at a bad time.
if (clc.voipOutgoingDataSize > 0)
return; // packet is pending transmission, don't record more yet.
if (cl_voipUseVAD->modified) {
Cvar_Set("cl_voipSend", (useVad) ? "1" : "0");
cl_voipUseVAD->modified = qfalse;
}
if ((useVad) && (!cl_voipSend->integer))
Cvar_Set("cl_voipSend", "1"); // lots of things reset this.
if (cl_voipSend->modified) {
qboolean dontCapture = qfalse;
if (clc.state != CA_ACTIVE)
dontCapture = qtrue; // not connected to a server.
else if (!clc.voipEnabled)
dontCapture = qtrue; // server doesn't support VoIP.
else if (clc.demoplaying)
dontCapture = qtrue; // playing back a demo.
else if ( cl_voip->integer == 0 )
dontCapture = qtrue; // client has VoIP support disabled.
else if ( audioMult == 0.0f )
dontCapture = qtrue; // basically silenced incoming audio.
cl_voipSend->modified = qfalse;
if(dontCapture)
{
Cvar_Set("cl_voipSend", "0");
return;
}
if (cl_voipSend->integer) {
initialFrame = qtrue;
} else {
finalFrame = qtrue;
}
}
// try to get more audio data from the sound card...
if (initialFrame) {
S_MasterGain(Com_Clamp(0.0f, 1.0f, cl_voipGainDuringCapture->value));
S_StartCapture();
CL_VoipNewGeneration();
CL_VoipParseTargets();
}
if ((cl_voipSend->integer) || (finalFrame)) { // user wants to capture audio?
int samples = S_AvailableCaptureSamples();
const int packetSamples = (finalFrame) ? VOIP_MAX_FRAME_SAMPLES : VOIP_MAX_PACKET_SAMPLES;
// enough data buffered in audio hardware to process yet?
if (samples >= packetSamples) {
// audio capture is always MONO16.
static int16_t sampbuffer[VOIP_MAX_PACKET_SAMPLES];
float voipPower = 0.0f;
int voipFrames;
int i, bytes;
if (samples > VOIP_MAX_PACKET_SAMPLES)
samples = VOIP_MAX_PACKET_SAMPLES;
// !!! FIXME: maybe separate recording from encoding, so voipPower
// !!! FIXME: updates faster than 4Hz?
samples -= samples % VOIP_MAX_FRAME_SAMPLES;
if (samples != 120 && samples != 240 && samples != 480 && samples != 960 && samples != 1920 && samples != 2880 ) {
Com_Printf("Voip: bad number of samples %d\n", samples);
return;
}
voipFrames = samples / VOIP_MAX_FRAME_SAMPLES;
S_Capture(samples, (byte *) sampbuffer); // grab from audio card.
// check the "power" of this packet...
for (i = 0; i < samples; i++) {
const float flsamp = (float) sampbuffer[i];
const float s = fabs(flsamp);
voipPower += s * s;
sampbuffer[i] = (int16_t) ((flsamp) * audioMult);
}
// encode raw audio samples into Opus data...
bytes = opus_encode(clc.opusEncoder, sampbuffer, samples,
(unsigned char *) clc.voipOutgoingData,
sizeof (clc.voipOutgoingData));
if ( bytes <= 0 ) {
Com_DPrintf("VoIP: Error encoding %d samples\n", samples);
bytes = 0;
}
clc.voipPower = (voipPower / (32768.0f * 32768.0f *
((float) samples))) * 100.0f;
if ((useVad) && (clc.voipPower < cl_voipVADThreshold->value)) {
CL_VoipNewGeneration(); // no "talk" for at least 1/4 second.
} else {
clc.voipOutgoingDataSize = bytes;
clc.voipOutgoingDataFrames = voipFrames;
Com_DPrintf("VoIP: Send %d frames, %d bytes, %f power\n",
voipFrames, bytes, clc.voipPower);
#if 0
static FILE *encio = NULL;
if (encio == NULL) encio = fopen("voip-outgoing-encoded.bin", "wb");
if (encio != NULL) { fwrite(clc.voipOutgoingData, bytes, 1, encio); fflush(encio); }
static FILE *decio = NULL;
if (decio == NULL) decio = fopen("voip-outgoing-decoded.bin", "wb");
if (decio != NULL) { fwrite(sampbuffer, voipFrames * VOIP_MAX_FRAME_SAMPLES * 2, 1, decio); fflush(decio); }
#endif
}
}
}
// User requested we stop recording, and we've now processed the last of
// any previously-buffered data. Pause the capture device, etc.
if (finalFrame) {
S_StopCapture();
S_MasterGain(1.0f);
clc.voipPower = 0.0f; // force this value so it doesn't linger.
}
}
#endif
/*
=======================================================================
CLIENT RELIABLE COMMAND COMMUNICATION
=======================================================================
*/
/*
======================
CL_AddReliableCommand
The given command will be transmitted to the server, and is gauranteed to
not have future usercmd_t executed before it is executed
======================
*/
void CL_AddReliableCommand(const char *cmd, qboolean isDisconnectCmd)
{
int unacknowledged = clc.reliableSequence - clc.reliableAcknowledge;
// if we would be losing an old command that hasn't been acknowledged,
// we must drop the connection
// also leave one slot open for the disconnect command in this case.
if ((isDisconnectCmd && unacknowledged > MAX_RELIABLE_COMMANDS) ||
(!isDisconnectCmd && unacknowledged >= MAX_RELIABLE_COMMANDS))
{
if(com_errorEntered)
return;
else
Com_Error(ERR_DROP, "Client command overflow");
}
Q_strncpyz(clc.reliableCommands[++clc.reliableSequence & (MAX_RELIABLE_COMMANDS - 1)],
cmd, sizeof(*clc.reliableCommands));
}
/*
=======================================================================
CLIENT SIDE DEMO RECORDING
=======================================================================
*/
/*
====================
CL_WriteDemoMessage
Dumps the current net message, prefixed by the length
====================
*/
void CL_WriteDemoMessage( msg_t *msg, int headerBytes ) {
int len, swlen;
// write the packet sequence
len = clc.serverMessageSequence;
swlen = LittleLong( len );
FS_Write( &swlen, 4, clc.demofile );
// skip the packet sequencing information
len = msg->cursize - headerBytes;
swlen = LittleLong( len );
FS_Write( &swlen, 4, clc.demofile );
FS_Write( msg->data + headerBytes, len, clc.demofile );
}
/*
====================
CL_StopRecording_f
stop recording a demo
====================
*/
void CL_StopRecord_f( void ) {
int len;
if ( !clc.demorecording ) {
Com_Printf( "Not recording a demo.\n" );
return;
}
// finish up
len = -1;
FS_Write( &len, 4, clc.demofile );
FS_Write( &len, 4, clc.demofile );
FS_FCloseFile( clc.demofile );
clc.demofile = 0;
clc.demorecording = qfalse;
Com_Printf( "Stopped demo.\n" );
}
/*
==================
CL_DemoFilename
==================
*/
void CL_DemoFilename( int number, char *fileName, int fileNameSize ) {
int a,b,c,d;
if(number < 0 || number > 9999)
number = 9999;
a = number / 1000;
number -= a * 1000;
b = number / 100;
number -= b * 100;
c = number / 10;
number -= c * 10;
d = number;
Com_sprintf( fileName, fileNameSize, "demo%i%i%i%i"
, a, b, c, d );
}
/*
====================
CL_Record_f
record <demoname>
Begins recording a demo from the current position
====================
*/
static char demoName[MAX_QPATH]; // compiler bug workaround
void CL_Record_f( void ) {
char name[MAX_OSPATH];
byte bufData[MAX_MSGLEN];
msg_t buf;
int i;
int len;
entityState_t *ent;
entityState_t nullstate;
char *s;
if ( Cmd_Argc() > 2 ) {
Com_Printf( "record <demoname>\n" );
return;
}
if ( clc.demorecording ) {
Com_Printf( "Already recording.\n" );
return;
}
if ( clc.state != CA_ACTIVE ) {
Com_Printf( "You must be in a level to record.\n" );
return;
}
// sync 0 doesn't prevent recording, so not forcing it off .. everyone does g_sync 1 ; record ; g_sync 0 ..
if ( NET_IsLocalAddress( clc.serverAddress ) && !Cvar_VariableValue( "g_synchronousClients" ) ) {
Com_Printf (S_COLOR_YELLOW "WARNING: You should set 'g_synchronousClients 1' for smoother demo recording\n");
}
if ( Cmd_Argc() == 2 ) {
s = Cmd_Argv( 1 );
Q_strncpyz( demoName, s, sizeof( demoName ) );
#ifdef LEGACY_PROTOCOL
if(clc.compat)
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_legacyprotocol->integer);
else
#endif
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_protocol->integer);
} else {
int number;
// scan for a free demo name
for ( number = 0 ; number <= 9999 ; number++ ) {
CL_DemoFilename( number, demoName, sizeof( demoName ) );
#ifdef LEGACY_PROTOCOL
if(clc.compat)
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_legacyprotocol->integer);
else
#endif
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_protocol->integer);
if (!FS_FileExists(name))
break; // file doesn't exist
}
}
// open the demo file
Com_Printf( "recording to %s.\n", name );
clc.demofile = FS_FOpenFileWrite( name );
if ( !clc.demofile ) {
Com_Printf( "ERROR: couldn't open.\n" );
return;
}
clc.demorecording = qtrue;
Q_strncpyz( clc.demoName, demoName, sizeof( clc.demoName ) );
// don't start saving messages until a non-delta compressed message is received
clc.demowaiting = qtrue;
// write out the gamestate message
MSG_Init( &buf, bufData, sizeof( bufData ) );
MSG_Bitstream( &buf );
// NOTE, MRE: all server->client messages now acknowledge
MSG_WriteLong( &buf, clc.reliableSequence );
MSG_WriteByte( &buf, svc_gamestate );
MSG_WriteLong( &buf, clc.serverCommandSequence );
// configstrings
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
if ( !cl.gameState.stringOffsets[i] ) {
continue;
}
s = cl.gameState.stringData + cl.gameState.stringOffsets[i];
MSG_WriteByte( &buf, svc_configstring );
MSG_WriteShort( &buf, i );
MSG_WriteBigString( &buf, s );
}
// baselines
Com_Memset( &nullstate, 0, sizeof( nullstate ) );
for ( i = 0; i < MAX_GENTITIES ; i++ ) {
ent = &cl.entityBaselines[i];
if ( !ent->number ) {
continue;
}
MSG_WriteByte( &buf, svc_baseline );
MSG_WriteDeltaEntity( &buf, &nullstate, ent, qtrue );
}
MSG_WriteByte( &buf, svc_EOF );
// finished writing the gamestate stuff
// write the client num
MSG_WriteLong( &buf, clc.clientNum );
// write the checksum feed
MSG_WriteLong( &buf, clc.checksumFeed );
// finished writing the client packet
MSG_WriteByte( &buf, svc_EOF );
// write it to the demo file
len = LittleLong( clc.serverMessageSequence - 1 );
FS_Write( &len, 4, clc.demofile );
len = LittleLong( buf.cursize );
FS_Write( &len, 4, clc.demofile );
FS_Write( buf.data, buf.cursize, clc.demofile );
// the rest of the demo file will be copied from net messages
}
/*
=======================================================================
CLIENT SIDE DEMO PLAYBACK
=======================================================================
*/
/*
=================
CL_DemoFrameDurationSDev
=================
*/
static float CL_DemoFrameDurationSDev( void )
{
int i;
int numFrames;
float mean = 0.0f;
float variance = 0.0f;
if( ( clc.timeDemoFrames - 1 ) > MAX_TIMEDEMO_DURATIONS )
numFrames = MAX_TIMEDEMO_DURATIONS;
else
numFrames = clc.timeDemoFrames - 1;
for( i = 0; i < numFrames; i++ )
mean += clc.timeDemoDurations[ i ];
mean /= numFrames;
for( i = 0; i < numFrames; i++ )
{
float x = clc.timeDemoDurations[ i ];
variance += ( ( x - mean ) * ( x - mean ) );
}
variance /= numFrames;
return sqrt( variance );
}
/*
=================
CL_DemoCompleted
=================
*/
void CL_DemoCompleted( void )
{
char buffer[ MAX_STRING_CHARS ];
if( cl_timedemo && cl_timedemo->integer )
{
int time;
time = Sys_Milliseconds() - clc.timeDemoStart;
if( time > 0 )
{
// Millisecond times are frame durations:
// minimum/average/maximum/std deviation
Com_sprintf( buffer, sizeof( buffer ),
"%i frames %3.1f seconds %3.1f fps %d.0/%.1f/%d.0/%.1f ms\n",
clc.timeDemoFrames,
time/1000.0,
clc.timeDemoFrames*1000.0 / time,
clc.timeDemoMinDuration,
time / (float)clc.timeDemoFrames,
clc.timeDemoMaxDuration,
CL_DemoFrameDurationSDev( ) );
Com_Printf( "%s", buffer );
// Write a log of all the frame durations
if( cl_timedemoLog && strlen( cl_timedemoLog->string ) > 0 )
{
int i;
int numFrames;
fileHandle_t f;
if( ( clc.timeDemoFrames - 1 ) > MAX_TIMEDEMO_DURATIONS )
numFrames = MAX_TIMEDEMO_DURATIONS;
else
numFrames = clc.timeDemoFrames - 1;
f = FS_FOpenFileWrite( cl_timedemoLog->string );
if( f )
{
FS_Printf( f, "# %s", buffer );
for( i = 0; i < numFrames; i++ )
FS_Printf( f, "%d\n", clc.timeDemoDurations[ i ] );
FS_FCloseFile( f );
Com_Printf( "%s written\n", cl_timedemoLog->string );
}
else
{
Com_Printf( "Couldn't open %s for writing\n",
cl_timedemoLog->string );
}
}
}
}
CL_Disconnect( qtrue );
CL_NextDemo();
}
/*
=================
CL_ReadDemoMessage
=================
*/
void CL_ReadDemoMessage( void ) {
int r;
msg_t buf;
byte bufData[ MAX_MSGLEN ];
int s;
if ( !clc.demofile ) {
CL_DemoCompleted();
return;
}
// get the sequence number
r = FS_Read( &s, 4, clc.demofile );
if ( r != 4 ) {
CL_DemoCompleted();
return;
}
clc.serverMessageSequence = LittleLong( s );
// init the message
MSG_Init( &buf, bufData, sizeof( bufData ) );
// get the length
r = FS_Read( &buf.cursize, 4, clc.demofile );
if ( r != 4 ) {
CL_DemoCompleted();
return;
}
buf.cursize = LittleLong( buf.cursize );
if ( buf.cursize == -1 ) {
CL_DemoCompleted();
return;
}
if ( buf.cursize > buf.maxsize ) {
Com_Error( ERR_DROP, "CL_ReadDemoMessage: demoMsglen > MAX_MSGLEN" );
}
r = FS_Read( buf.data, buf.cursize, clc.demofile );
if ( r != buf.cursize ) {
Com_Printf( "Demo file was truncated.\n" );
CL_DemoCompleted();
return;
}
clc.lastPacketTime = cls.realtime;
buf.readcount = 0;
CL_ParseServerMessage( &buf );
}
/*
====================
CL_WalkDemoExt
====================
*/
static int CL_WalkDemoExt(char *arg, char *name, int *demofile)
{
int i = 0;
*demofile = 0;
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer > 0)
{
Com_sprintf(name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, com_legacyprotocol->integer);
FS_FOpenFileRead(name, demofile, qtrue);
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return com_legacyprotocol->integer;
}
}
if(com_protocol->integer != com_legacyprotocol->integer)
#endif
{
Com_sprintf(name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, com_protocol->integer);
FS_FOpenFileRead(name, demofile, qtrue);
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return com_protocol->integer;
}
}
Com_Printf("Not found: %s\n", name);
while(demo_protocols[i])
{
#ifdef LEGACY_PROTOCOL
if(demo_protocols[i] == com_legacyprotocol->integer)
continue;
#endif
if(demo_protocols[i] == com_protocol->integer)
continue;
Com_sprintf (name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, demo_protocols[i]);
FS_FOpenFileRead( name, demofile, qtrue );
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return demo_protocols[i];
}
else
Com_Printf("Not found: %s\n", name);
i++;
}
return -1;
}
/*
====================
CL_CompleteDemoName
====================
*/
static void CL_CompleteDemoName( char *args, int argNum )
{
if( argNum == 2 )
{
char demoExt[ 16 ];
Com_sprintf(demoExt, sizeof(demoExt), ".%s%d", DEMOEXT, com_protocol->integer);
Field_CompleteFilename( "demos", demoExt, qtrue, qtrue );
}
}
/*
====================
CL_PlayDemo_f
demo <demoname>
====================
*/
void CL_PlayDemo_f( void ) {
char name[MAX_OSPATH];
char *arg, *ext_test;
int protocol, i;
char retry[MAX_OSPATH];
if (Cmd_Argc() != 2) {
Com_Printf ("demo <demoname>\n");
return;
}
// make sure a local server is killed
// 2 means don't force disconnect of local client
Cvar_Set( "sv_killserver", "2" );
// open the demo file
arg = Cmd_Argv(1);
CL_Disconnect( qtrue );
// check for an extension .DEMOEXT_?? (?? is protocol)
ext_test = strrchr(arg, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMOEXT, ARRAY_LEN(DEMOEXT) - 1))
{
protocol = atoi(ext_test + ARRAY_LEN(DEMOEXT));
for(i = 0; demo_protocols[i]; i++)
{
if(demo_protocols[i] == protocol)
break;
}
if(demo_protocols[i] || protocol == com_protocol->integer
#ifdef LEGACY_PROTOCOL
|| protocol == com_legacyprotocol->integer
#endif
)
{
Com_sprintf(name, sizeof(name), "demos/%s", arg);
FS_FOpenFileRead(name, &clc.demofile, qtrue);
}
else
{
int len;
Com_Printf("Protocol %d not supported for demos\n", protocol);
len = ext_test - arg;
if(len >= ARRAY_LEN(retry))
len = ARRAY_LEN(retry) - 1;
Q_strncpyz(retry, arg, len + 1);
retry[len] = '\0';
protocol = CL_WalkDemoExt(retry, name, &clc.demofile);
}
}
else
protocol = CL_WalkDemoExt(arg, name, &clc.demofile);
if (!clc.demofile) {
Com_Error( ERR_DROP, "couldn't open %s", name);
return;
}
Q_strncpyz( clc.demoName, arg, sizeof( clc.demoName ) );
Con_Close();
clc.state = CA_CONNECTED;
clc.demoplaying = qtrue;
Q_strncpyz( clc.servername, arg, sizeof( clc.servername ) );
#ifdef LEGACY_PROTOCOL
if(protocol <= com_legacyprotocol->integer)
clc.compat = qtrue;
else
clc.compat = qfalse;
#endif
// read demo messages until connected
while ( clc.state >= CA_CONNECTED && clc.state < CA_PRIMED ) {
CL_ReadDemoMessage();
}
// don't get the first snapshot this frame, to prevent the long
// time from the gamestate load from messing causing a time skip
clc.firstDemoFrameSkipped = qfalse;
}
/*
====================
CL_StartDemoLoop
Closing the main menu will restart the demo loop
====================
*/
void CL_StartDemoLoop( void ) {
// start the demo loop again
Cbuf_AddText( "d1\n" );
Key_SetCatcher( 0 );
}
/*
==================
CL_NextDemo
Called when a demo or cinematic finishes
If the "nextdemo" cvar is set, that command will be issued
==================
*/
void CL_NextDemo( void ) {
char v[MAX_STRING_CHARS];
Q_strncpyz( v, Cvar_VariableString( "nextdemo" ), sizeof( v ) );
v[MAX_STRING_CHARS - 1] = 0;
Com_DPrintf( "CL_NextDemo: %s\n", v );
if ( !v[0] ) {
return;
}
Cvar_Set( "nextdemo","" );
Cbuf_AddText( v );
Cbuf_AddText( "\n" );
Cbuf_Execute();
}
//======================================================================
/*
=====================
CL_ShutdownAll
=====================
*/
void CL_ShutdownAll(qboolean shutdownRef)
{
if(CL_VideoRecording())
CL_CloseAVI();
if(clc.demorecording)
CL_StopRecord_f();
#ifdef USE_CURL
CL_cURL_Shutdown();
#endif
// clear sounds
S_DisableSounds();
// shutdown CGame
CL_ShutdownCGame();
// shutdown UI
CL_ShutdownUI();
// shutdown the renderer
if(shutdownRef)
CL_ShutdownRef();
else if(re.Shutdown)
re.Shutdown(qfalse); // don't destroy window or context
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.rendererStarted = qfalse;
cls.soundRegistered = qfalse;
}
/*
=================
CL_ClearMemory
Called by Com_GameRestart
=================
*/
void CL_ClearMemory(qboolean shutdownRef)
{
// shutdown all the client stuff
CL_ShutdownAll(shutdownRef);
// if not running a server clear the whole hunk
if ( !com_sv_running->integer ) {
// clear the whole hunk
Hunk_Clear();
// clear collision map data
CM_ClearMap();
} else {
// clear all the client data on the hunk
Hunk_ClearToMark();
}
}
/*
=================
CL_FlushMemory
Called by CL_MapLoading, CL_Connect_f, CL_PlayDemo_f, and CL_ParseGamestate the only
ways a client gets into a game
Also called by Com_Error
=================
*/
void CL_FlushMemory(void)
{
CL_ClearMemory(qfalse);
CL_StartHunkUsers(qfalse);
}
/*
=====================
CL_MapLoading
A local server is starting to load a map, so update the
screen to let the user know about it, then dump all client
memory on the hunk from cgame, ui, and renderer
=====================
*/
void CL_MapLoading( void ) {
if ( com_dedicated->integer ) {
clc.state = CA_DISCONNECTED;
Key_SetCatcher( KEYCATCH_CONSOLE );
return;
}
if ( !com_cl_running->integer ) {
return;
}
Con_Close();
Key_SetCatcher( 0 );
// if we are already connected to the local host, stay connected
if ( clc.state >= CA_CONNECTED && !Q_stricmp( clc.servername, "localhost" ) ) {
clc.state = CA_CONNECTED; // so the connect screen is drawn
Com_Memset( cls.updateInfoString, 0, sizeof( cls.updateInfoString ) );
Com_Memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) );
Com_Memset( &cl.gameState, 0, sizeof( cl.gameState ) );
clc.lastPacketSentTime = -9999;
SCR_UpdateScreen();
} else {
// clear nextmap so the cinematic shutdown doesn't execute it
Cvar_Set( "nextmap", "" );
CL_Disconnect( qtrue );
Q_strncpyz( clc.servername, "localhost", sizeof(clc.servername) );
clc.state = CA_CHALLENGING; // so the connect screen is drawn
Key_SetCatcher( 0 );
SCR_UpdateScreen();
clc.connectTime = -RETRANSMIT_TIMEOUT;
NET_StringToAdr( clc.servername, &clc.serverAddress, NA_UNSPEC);
// we don't need a challenge on the localhost
CL_CheckForResend();
}
// make sure sound is quiet
// S_FadeAllSounds( 0, 0 );
}
/*
=====================
CL_ClearState
Called before parsing a gamestate
=====================
*/
void CL_ClearState( void ) {
S_StopAllSounds();
memset( &cl, 0, sizeof( cl ) );
}
/*
====================
CL_UpdateGUID
update cl_guid using QKEY_FILE and optional prefix
====================
*/
static void CL_UpdateGUID( const char *prefix, int prefix_len )
{
fileHandle_t f;
int len;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
if( len != QKEY_SIZE )
Cvar_Set( "cl_guid", "" );
else
Cvar_Set( "cl_guid", Com_MD5File( QKEY_FILE, QKEY_SIZE,
prefix, prefix_len ) );
}
static void CL_OldGame(void)
{
if(cl_oldGameSet)
{
// change back to previous fs_game
cl_oldGameSet = qfalse;
Cvar_Set2("fs_game", cl_oldGame, qtrue);
FS_ConditionalRestart(clc.checksumFeed, qfalse);
}
}
/*
=====================
CL_Disconnect
Called when a connection, demo, or cinematic is being terminated.
Goes from a connected state to either a menu state or a console state
Sends a disconnect message to the server
This is also called on Com_Error and Com_Quit, so it shouldn't cause any errors
=====================
*/
void CL_Disconnect( qboolean showMainMenu ) {
if ( !com_cl_running || !com_cl_running->integer ) {
return;
}
// shutting down the client so enter full screen ui mode
Cvar_Set( "r_uiFullScreen", "1" );
if ( clc.demorecording ) {
CL_StopRecord_f();
}
if ( clc.download ) {
FS_FCloseFile( clc.download );
clc.download = 0;
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
#ifdef USE_MUMBLE
if (cl_useMumble->integer && mumble_islinked()) {
Com_Printf("Mumble: Unlinking from Mumble application\n");
mumble_unlink();
}
#endif
#ifdef USE_VOIP
if (cl_voipSend->integer) {
int tmp = cl_voipUseVAD->integer;
cl_voipUseVAD->integer = 0; // disable this for a moment.
clc.voipOutgoingDataSize = 0; // dump any pending VoIP transmission.
Cvar_Set("cl_voipSend", "0");
CL_CaptureVoip(); // clean up any state...
cl_voipUseVAD->integer = tmp;
}
if (clc.voipCodecInitialized) {
int i;
opus_encoder_destroy(clc.opusEncoder);
for (i = 0; i < MAX_CLIENTS; i++) {
opus_decoder_destroy(clc.opusDecoder[i]);
}
clc.voipCodecInitialized = qfalse;
}
Cmd_RemoveCommand ("voip");
#endif
if ( clc.demofile ) {
FS_FCloseFile( clc.demofile );
clc.demofile = 0;
}
if ( uivm && showMainMenu ) {
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NONE );
}
SCR_StopCinematic();
S_ClearSoundBuffer();
// send a disconnect message to the server
// send it a few times in case one is dropped
if ( clc.state >= CA_CONNECTED ) {
CL_AddReliableCommand("disconnect", qtrue);
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
// Remove pure paks
FS_PureServerSetLoadedPaks("", "");
FS_PureServerSetReferencedPaks( "", "" );
CL_ClearState();
// wipe the client connection
Com_Memset( &clc, 0, sizeof( clc ) );
clc.state = CA_DISCONNECTED;
// allow cheats locally
#ifndef WOLF_SP_DEMO
// except for demo
Cvar_Set( "sv_cheats", "1" );
#endif
// not connected to a pure server anymore
cl_connectedToPureServer = qfalse;
#ifdef USE_VOIP
// not connected to voip server anymore.
clc.voipEnabled = qfalse;
#endif
// Stop recording any video
if( CL_VideoRecording( ) ) {
// Finish rendering current frame
SCR_UpdateScreen( );
CL_CloseAVI( );
}
CL_UpdateGUID( NULL, 0 );
if(!noGameRestart)
CL_OldGame();
else
noGameRestart = qfalse;
}
/*
===================
CL_ForwardCommandToServer
adds the current command line as a clientCommand
things like godmode, noclip, etc, are commands directed to the server,
so when they are typed in at the console, they will need to be forwarded.
===================
*/
void CL_ForwardCommandToServer( const char *string ) {
char *cmd;
cmd = Cmd_Argv( 0 );
// ignore key up commands
if ( cmd[0] == '-' ) {
return;
}
if ( clc.demoplaying || clc.state < CA_CONNECTED || cmd[0] == '+' ) {
Com_Printf ("Unknown command \"%s" S_COLOR_WHITE "\"\n", cmd);
return;
}
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand(string, qfalse);
} else {
CL_AddReliableCommand(cmd, qfalse);
}
}
/*
===================
CL_RequestMotd
===================
*/
void CL_RequestMotd( void ) {
#ifdef UPDATE_SERVER_NAME
char info[MAX_INFO_STRING];
if ( !cl_motd->integer ) {
return;
}
Com_Printf( "Resolving %s\n", UPDATE_SERVER_NAME );
if ( !NET_StringToAdr( UPDATE_SERVER_NAME, &cls.updateServer, NA_IP ) ) {
Com_Printf( "Couldn't resolve address\n" );
return;
}
cls.updateServer.port = BigShort( PORT_UPDATE );
Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", UPDATE_SERVER_NAME,
cls.updateServer.ip[0], cls.updateServer.ip[1],
cls.updateServer.ip[2], cls.updateServer.ip[3],
BigShort( cls.updateServer.port ) );
info[0] = 0;
Com_sprintf( cls.updateChallenge, sizeof( cls.updateChallenge ), "%i", rand() );
Info_SetValueForKey( info, "challenge", cls.updateChallenge );
Info_SetValueForKey( info, "renderer", cls.glconfig.renderer_string );
Info_SetValueForKey( info, "version", com_version->string );
NET_OutOfBandPrint( NS_CLIENT, cls.updateServer, "getmotd \"%s\"\n", info );
#endif
}
/*
===================
CL_RequestAuthorization
Authorization server protocol
-----------------------------
All commands are text in Q3 out of band packets (leading 0xff 0xff 0xff 0xff).
Whenever the client tries to get a challenge from the server it wants to
connect to, it also blindly fires off a packet to the authorize server:
getKeyAuthorize <challenge> <cdkey>
cdkey may be "demo"
#OLD The authorize server returns a:
#OLD
#OLD keyAthorize <challenge> <accept | deny>
#OLD
#OLD A client will be accepted if the cdkey is valid and it has not been used by any other IP
#OLD address in the last 15 minutes.
The server sends a:
getIpAuthorize <challenge> <ip>
The authorize server returns a:
ipAuthorize <challenge> <accept | deny | demo | unknown >
A client will be accepted if a valid cdkey was sent by that ip (only) in the last 15 minutes.
If no response is received from the authorize server after two tries, the client will be let
in anyway.
===================
*/
#ifndef STANDALONE
#ifdef USE_AUTHORIZE_SERVER
void CL_RequestAuthorization( void ) {
char nums[64];
int i, j, l;
cvar_t *fs;
if ( !cls.authorizeServer.port ) {
Com_Printf( "Resolving %s\n", AUTHORIZE_SERVER_NAME );
if ( !NET_StringToAdr( AUTHORIZE_SERVER_NAME, &cls.authorizeServer, NA_IP ) ) {
Com_Printf( "Couldn't resolve address\n" );
return;
}
cls.authorizeServer.port = BigShort( PORT_AUTHORIZE );
Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", AUTHORIZE_SERVER_NAME,
cls.authorizeServer.ip[0], cls.authorizeServer.ip[1],
cls.authorizeServer.ip[2], cls.authorizeServer.ip[3],
BigShort( cls.authorizeServer.port ) );
}
if ( cls.authorizeServer.type == NA_BAD ) {
return;
}
// only grab the alphanumeric values from the cdkey, to avoid any dashes or spaces
j = 0;
l = strlen( cl_cdkey );
if ( l > 32 ) {
l = 32;
}
for ( i = 0 ; i < l ; i++ ) {
if ( ( cl_cdkey[i] >= '0' && cl_cdkey[i] <= '9' )
|| ( cl_cdkey[i] >= 'a' && cl_cdkey[i] <= 'z' )
|| ( cl_cdkey[i] >= 'A' && cl_cdkey[i] <= 'Z' ) ) {
nums[j] = cl_cdkey[i];
j++;
}
}
nums[j] = 0;
fs = Cvar_Get( "cl_anonymous", "0", CVAR_INIT | CVAR_SYSTEMINFO );
NET_OutOfBandPrint(NS_CLIENT, cls.authorizeServer, "getKeyAuthorize %i %s", fs->integer, nums );
}
#endif
#endif
/*
======================================================================
CONSOLE COMMANDS
======================================================================
*/
/*
==================
CL_ForwardToServer_f
==================
*/
void CL_ForwardToServer_f( void ) {
if ( clc.state != CA_ACTIVE || clc.demoplaying ) {
Com_Printf( "Not connected to a server.\n" );
return;
}
// don't forward the first argument
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand(Cmd_Args(), qfalse);
}
}
/*
==================
CL_Disconnect_f
==================
*/
void CL_Disconnect_f( void ) {
SCR_StopCinematic();
// RF, make sure loading variables are turned off
Cvar_Set( "savegame_loading", "0" );
Cvar_Set( "g_reloading", "0" );
if ( clc.state != CA_DISCONNECTED && clc.state != CA_CINEMATIC ) {
Com_Error( ERR_DISCONNECT, "Disconnected from server" );
}
}
/*
================
CL_Reconnect_f
================
*/
void CL_Reconnect_f( void ) {
if ( !strlen( cl_reconnectArgs ) )
return;
Cbuf_AddText( va("connect %s\n", cl_reconnectArgs ) );
}
/*
================
CL_Connect_f
================
*/
void CL_Connect_f( void ) {
char *server;
const char *serverString;
int argc = Cmd_Argc();
netadrtype_t family = NA_UNSPEC;
if ( argc != 2 && argc != 3 ) {
Com_Printf( "usage: connect [-4|-6] server\n");
return;
}
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
// save arguments for reconnect
Q_strncpyz( cl_reconnectArgs, Cmd_Args(), sizeof( cl_reconnectArgs ) );
// starting to load a map so we get out of full screen ui mode
Cvar_Set( "r_uiFullScreen", "0" );
// fire a message off to the motd server
CL_RequestMotd();
// clear any previous "server full" type messages
clc.serverMessage[0] = 0;
if ( com_sv_running->integer && !strcmp( server, "localhost" ) ) {
// if running a local server, kill it
SV_Shutdown( "Server quit" );
}
// make sure a local server is killed
Cvar_Set( "sv_killserver", "1" );
SV_Frame( 0 );
noGameRestart = qtrue;
CL_Disconnect( qtrue );
Con_Close();
Q_strncpyz( clc.servername, server, sizeof(clc.servername) );
if (!NET_StringToAdr(clc.servername, &clc.serverAddress, family) ) {
Com_Printf( "Bad server address\n" );
clc.state = CA_DISCONNECTED;
return;
}
if ( clc.serverAddress.port == 0 ) {
clc.serverAddress.port = BigShort( PORT_SERVER );
}
serverString = NET_AdrToStringwPort(clc.serverAddress);
Com_Printf( "%s resolved to %s\n", clc.servername, serverString);
if( cl_guidServerUniq->integer )
CL_UpdateGUID( serverString, strlen( serverString ) );
else
CL_UpdateGUID( NULL, 0 );
// if we aren't playing on a lan, we need to authenticate
// with the cd key
if(NET_IsLocalAddress(clc.serverAddress))
clc.state = CA_CHALLENGING;
else
{
clc.state = CA_CONNECTING;
// Set a client challenge number that ideally is mirrored back by the server.
clc.challenge = ((rand() << 16) ^ rand()) ^ Com_Milliseconds();
}
Key_SetCatcher( 0 );
clc.connectTime = -99999; // CL_CheckForResend() will fire immediately
clc.connectPacketCount = 0;
// server connection string
Cvar_Set( "cl_currentServerAddress", server );
}
#define MAX_RCON_MESSAGE 1024
/*
==================
CL_CompleteRcon
==================
*/
static void CL_CompleteRcon( char *args, int argNum )
{
if( argNum == 2 )
{
// Skip "rcon "
char *p = Com_SkipTokens( args, 1, " " );
if( p > args )
Field_CompleteCommand( p, qtrue, qtrue );
}
}
/*
=====================
CL_Rcon_f
Send the rest of the command line over as
an unconnected command.
=====================
*/
void CL_Rcon_f( void ) {
char message[MAX_RCON_MESSAGE];
netadr_t to;
if ( !rcon_client_password->string[0] ) {
Com_Printf( "You must set 'rconpassword' before\n"
"issuing an rcon command.\n" );
return;
}
message[0] = -1;
message[1] = -1;
message[2] = -1;
message[3] = -1;
message[4] = 0;
Q_strcat (message, MAX_RCON_MESSAGE, "rcon ");
Q_strcat (message, MAX_RCON_MESSAGE, rcon_client_password->string);
Q_strcat (message, MAX_RCON_MESSAGE, " ");
Q_strcat (message, MAX_RCON_MESSAGE, Cmd_Cmd()+5);
if ( clc.state >= CA_CONNECTED ) {
to = clc.netchan.remoteAddress;
} else {
if ( !strlen( rconAddress->string ) ) {
Com_Printf( "You must either be connected,\n"
"or set the 'rconAddress' cvar\n"
"to issue rcon commands\n" );
return;
}
NET_StringToAdr (rconAddress->string, &to, NA_UNSPEC);
if ( to.port == 0 ) {
to.port = BigShort( PORT_SERVER );
}
}
NET_SendPacket( NS_CLIENT, strlen( message ) + 1, message, to );
}
/*
=================
CL_SendPureChecksums
=================
*/
void CL_SendPureChecksums( void ) {
char cMsg[MAX_INFO_VALUE];
// if we are pure we need to send back a command with our referenced pk3 checksums
Com_sprintf(cMsg, sizeof(cMsg), "cp %d %s", cl.serverId, FS_ReferencedPakPureChecksums());
CL_AddReliableCommand(cMsg, qfalse);
}
/*
=================
CL_ResetPureClientAtServer
=================
*/
void CL_ResetPureClientAtServer( void ) {
CL_AddReliableCommand("vdr", qfalse);
}
/*
=================
CL_Vid_Restart_f
Restart the video subsystem
we also have to reload the UI and CGame because the renderer
doesn't know what graphics to reload
=================
*/
void CL_Vid_Restart_f( void ) {
vmCvar_t musicCvar;
// RF, don't show percent bar, since the memory usage will just sit at the same level anyway
Cvar_Set( "com_expectedhunkusage", "-1" );
// Settings may have changed so stop recording now
if( CL_VideoRecording( ) ) {
CL_CloseAVI( );
}
if(clc.demorecording)
CL_StopRecord_f();
// don't let them loop during the restart
S_StopAllSounds();
if(!FS_ConditionalRestart(clc.checksumFeed, qtrue))
{
// if not running a server clear the whole hunk
if(com_sv_running->integer)
{
// clear all the client data on the hunk
Hunk_ClearToMark();
}
else
{
// clear the whole hunk
Hunk_Clear();
}
// shutdown the UI
CL_ShutdownUI();
// shutdown the CGame
CL_ShutdownCGame();
// shutdown the renderer and clear the renderer interface
CL_ShutdownRef();
// client is no longer pure untill new checksums are sent
CL_ResetPureClientAtServer();
// clear pak references
FS_ClearPakReferences( FS_UI_REF | FS_CGAME_REF );
// reinitialize the filesystem if the game directory or checksum has changed
cls.rendererStarted = qfalse;
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.soundRegistered = qfalse;
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
// initialize the renderer interface
CL_InitRef();
// startup all the client stuff
CL_StartHunkUsers(qfalse);
// start the cgame if connected
if(clc.state > CA_CONNECTED && clc.state != CA_CINEMATIC)
{
cls.cgameStarted = qtrue;
CL_InitCGame();
// send pure checksums
CL_SendPureChecksums();
}
// start music if there was any
Cvar_Register( &musicCvar, "s_currentMusic", "", CVAR_ROM );
if ( strlen( musicCvar.string ) ) {
S_StartBackgroundTrack( musicCvar.string, musicCvar.string );
}
// fade up volume
// S_FadeAllSounds( 1, 0 );
}
}
/*
=================
CL_Snd_Shutdown
Shut down the sound subsystem
=================
*/
void CL_Snd_Shutdown(void)
{
S_Shutdown();
cls.soundStarted = qfalse;
}
/*
=================
CL_Snd_Restart_f
Restart the sound subsystem
The cgame and game must also be forced to restart because
handles will be invalid
=================
*/
void CL_Snd_Restart_f(void)
{
CL_Snd_Shutdown();
// sound will be reinitialized by vid_restart
CL_Vid_Restart_f();
}
/*
==================
CL_PK3List_f
==================
*/
void CL_OpenedPK3List_f( void ) {
Com_Printf( "Opened PK3 Names: %s\n", FS_LoadedPakNames() );
}
/*
==================
CL_PureList_f
==================
*/
void CL_ReferencedPK3List_f( void ) {
Com_Printf( "Referenced PK3 Names: %s\n", FS_ReferencedPakNames() );
}
/*
==================
CL_Configstrings_f
==================
*/
void CL_Configstrings_f( void ) {
int i;
int ofs;
if ( clc.state != CA_ACTIVE ) {
Com_Printf( "Not connected to a server.\n" );
return;
}
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
ofs = cl.gameState.stringOffsets[ i ];
if ( !ofs ) {
continue;
}
Com_Printf( "%4i: %s\n", i, cl.gameState.stringData + ofs );
}
}
/*
==============
CL_Clientinfo_f
==============
*/
void CL_Clientinfo_f( void ) {
Com_Printf( "--------- Client Information ---------\n" );
Com_Printf( "state: %i\n", clc.state );
Com_Printf( "Server: %s\n", clc.servername );
Com_Printf( "User info settings:\n" );
Info_Print( Cvar_InfoString( CVAR_USERINFO ) );
Com_Printf( "--------------------------------------\n" );
}
//====================================================================
/*
=================
CL_DownloadsComplete
Called when all downloading has been completed
=================
*/
void CL_DownloadsComplete( void ) {
#ifdef USE_CURL
// if we downloaded with cURL
if(clc.cURLUsed) {
clc.cURLUsed = qfalse;
CL_cURL_Shutdown();
if( clc.cURLDisconnected ) {
if(clc.downloadRestart) {
FS_Restart(clc.checksumFeed);
clc.downloadRestart = qfalse;
}
clc.cURLDisconnected = qfalse;
CL_Reconnect_f();
return;
}
}
#endif
// if we downloaded files we need to restart the file system
if ( clc.downloadRestart ) {
clc.downloadRestart = qfalse;
FS_Restart( clc.checksumFeed ); // We possibly downloaded a pak, restart the file system to load it
// inform the server so we get new gamestate info
CL_AddReliableCommand( "donedl", qfalse );
// by sending the donedl command we request a new gamestate
// so we don't want to load stuff yet
return;
}
// let the client game init and load data
clc.state = CA_LOADING;
Com_EventLoop();
// if the gamestate was changed by calling Com_EventLoop
// then we loaded everything already and we don't want to do it again.
if ( clc.state != CA_LOADING ) {
return;
}
// starting to load a map so we get out of full screen ui mode
Cvar_Set( "r_uiFullScreen", "0" );
// flush client memory and start loading stuff
// this will also (re)load the UI
// if this is a local client then only the client part of the hunk
// will be cleared, note that this is done after the hunk mark has been set
CL_FlushMemory();
// initialize the CGame
cls.cgameStarted = qtrue;
CL_InitCGame();
// set pure checksums
CL_SendPureChecksums();
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
/*
=================
CL_BeginDownload
Requests a file to download from the server. Stores it in the current
game directory.
=================
*/
void CL_BeginDownload( const char *localName, const char *remoteName ) {
Com_DPrintf( "***** CL_BeginDownload *****\n"
"Localname: %s\n"
"Remotename: %s\n"
"****************************\n", localName, remoteName );
Q_strncpyz( clc.downloadName, localName, sizeof( clc.downloadName ) );
Com_sprintf( clc.downloadTempName, sizeof( clc.downloadTempName ), "%s.tmp", localName );
// Set so UI gets access to it
Cvar_Set( "cl_downloadName", remoteName );
Cvar_Set( "cl_downloadSize", "0" );
Cvar_Set( "cl_downloadCount", "0" );
Cvar_SetValue( "cl_downloadTime", cls.realtime );
clc.downloadBlock = 0; // Starting new file
clc.downloadCount = 0;
CL_AddReliableCommand( va( "download %s", remoteName ), qfalse );
}
/*
=================
CL_NextDownload
A download completed or failed
=================
*/
void CL_NextDownload( void ) {
char *s;
char *remoteName, *localName;
qboolean useCURL = qfalse;
// A download has finished, check whether this matches a referenced checksum
if( *clc.downloadName ) {
char *zippath = FS_BuildOSPath(Cvar_VariableString("fs_homepath"), clc.downloadName, "");
zippath[strlen(zippath)-1] = '\0';
if(!FS_CompareZipChecksum(zippath))
Com_Error(ERR_DROP, "Incorrect checksum for file: %s", clc.downloadName);
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set("cl_downloadName", "");
// We are looking to start a download here
if ( *clc.downloadList ) {
s = clc.downloadList;
// format is:
// @remotename@localname@remotename@localname, etc.
if ( *s == '@' ) {
s++;
}
remoteName = s;
if ( ( s = strchr( s, '@' ) ) == NULL ) {
CL_DownloadsComplete();
return;
}
*s++ = 0;
localName = s;
if ( ( s = strchr( s, '@' ) ) != NULL ) {
*s++ = 0;
} else {
s = localName + strlen( localName ); // point at the nul byte
}
#ifdef USE_CURL
if(!(cl_allowDownload->integer & DLF_NO_REDIRECT)) {
if(clc.sv_allowDownload & DLF_NO_REDIRECT) {
Com_Printf("WARNING: server does not "
"allow download redirection "
"(sv_allowDownload is %d)\n",
clc.sv_allowDownload);
}
else if(!*clc.sv_dlURL) {
Com_Printf("WARNING: server allows "
"download redirection, but does not "
"have sv_dlURL set\n");
}
else if(!CL_cURL_Init()) {
Com_Printf("WARNING: could not load "
"cURL library\n");
}
else {
CL_cURL_BeginDownload(localName, va("%s/%s",
clc.sv_dlURL, remoteName));
useCURL = qtrue;
}
}
else if(!(clc.sv_allowDownload & DLF_NO_REDIRECT)) {
Com_Printf("WARNING: server allows download "
"redirection, but it disabled by client "
"configuration (cl_allowDownload is %d)\n",
cl_allowDownload->integer);
}
#endif /* USE_CURL */
if(!useCURL) {
if((cl_allowDownload->integer & DLF_NO_UDP)) {
Com_Error(ERR_DROP, "UDP Downloads are "
"disabled on your client. "
"(cl_allowDownload is %d)",
cl_allowDownload->integer);
return;
}
else {
CL_BeginDownload( localName, remoteName );
}
}
clc.downloadRestart = qtrue;
// move over the rest
memmove( clc.downloadList, s, strlen( s ) + 1 );
return;
}
CL_DownloadsComplete();
}
/*
=================
CL_InitDownloads
After receiving a valid game state, we valid the cgame and local zip files here
and determine if we need to download them
=================
*/
void CL_InitDownloads( void ) {
char missingfiles[1024];
if ( !(cl_allowDownload->integer & DLF_ENABLE) ) {
// autodownload is disabled on the client
// but it's possible that some referenced files on the server are missing
if (FS_ComparePaks( missingfiles, sizeof( missingfiles ), qfalse ) ) {
// NOTE TTimo I would rather have that printed as a modal message box
// but at this point while joining the game we don't know wether we will successfully join or not
Com_Printf( "\nWARNING: You are missing some files referenced by the server:\n%s"
"You might not be able to join the game\n"
"Go to the setting menu to turn on autodownload, or get the file elsewhere\n\n", missingfiles );
}
}
else if ( FS_ComparePaks( clc.downloadList, sizeof( clc.downloadList ) , qtrue ) ) {
Com_Printf("Need paks: %s\n", clc.downloadList );
if ( *clc.downloadList ) {
// if autodownloading is not enabled on the server
clc.state = CA_CONNECTED;
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
CL_NextDownload();
return;
}
}
CL_DownloadsComplete();
}
/*
=================
CL_CheckForResend
Resend a connect message if the last one has timed out
=================
*/
void CL_CheckForResend( void ) {
int port;
char info[MAX_INFO_STRING];
char data[MAX_INFO_STRING + 10];
// don't send anything if playing back a demo
if ( clc.demoplaying ) {
return;
}
// resend if we haven't gotten a reply yet
if ( clc.state != CA_CONNECTING && clc.state != CA_CHALLENGING ) {
return;
}
if ( cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT ) {
return;
}
clc.connectTime = cls.realtime; // for retransmit requests
clc.connectPacketCount++;
switch ( clc.state ) {
case CA_CONNECTING:
// requesting a challenge .. IPv6 users always get in as authorize server supports no ipv6.
#ifndef STANDALONE
#ifdef USE_AUTHORIZE_SERVER
if (!com_standalone->integer && clc.serverAddress.type == NA_IP && !Sys_IsLANAddress( clc.serverAddress ) )
CL_RequestAuthorization();
#endif
#endif
// The challenge request shall be followed by a client challenge so no malicious server can hijack this connection.
// Add the gamename so the server knows we're running the correct game or can reject the client
// with a meaningful message
Com_sprintf(data, sizeof(data), "getchallenge %d %s", clc.challenge, com_gamename->string);
NET_OutOfBandPrint(NS_CLIENT, clc.serverAddress, "%s", data);
break;
case CA_CHALLENGING:
// sending back the challenge
port = Cvar_VariableValue( "net_qport" );
Q_strncpyz( info, Cvar_InfoString( CVAR_USERINFO ), sizeof( info ) );
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer == com_protocol->integer)
clc.compat = qtrue;
if(clc.compat)
Info_SetValueForKey(info, "protocol", va("%i", com_legacyprotocol->integer));
else
#endif
Info_SetValueForKey( info, "protocol", va("%i", com_protocol->integer ) );
Info_SetValueForKey( info, "qport", va( "%i", port ) );
Info_SetValueForKey( info, "challenge", va( "%i", clc.challenge ) );
Com_sprintf( data, sizeof(data), "connect \"%s\"", info );
NET_OutOfBandData( NS_CLIENT, clc.serverAddress, (byte *) data, strlen ( data ) );
// the most current userinfo has been sent, so watch for any
// newer changes to userinfo variables
cvar_modifiedFlags &= ~CVAR_USERINFO;
break;
default:
Com_Error( ERR_FATAL, "CL_CheckForResend: bad clc.state" );
}
}
/*
===================
CL_MotdPacket
===================
*/
void CL_MotdPacket( netadr_t from ) {
#ifdef UPDATE_SERVER_NAME
char *challenge;
char *info;
// if not from our server, ignore it
if ( !NET_CompareAdr( from, cls.updateServer ) ) {
return;
}
info = Cmd_Argv( 1 );
// check challenge
challenge = Info_ValueForKey( info, "challenge" );
if ( strcmp( challenge, cls.updateChallenge ) ) {
return;
}
challenge = Info_ValueForKey( info, "motd" );
Q_strncpyz( cls.updateInfoString, info, sizeof( cls.updateInfoString ) );
Cvar_Set( "cl_motdString", challenge );
#endif
}
/*
===================
CL_InitServerInfo
===================
*/
void CL_InitServerInfo( serverInfo_t *server, netadr_t *address ) {
server->adr = *address;
server->clients = 0;
server->hostName[0] = '\0';
server->mapName[0] = '\0';
server->maxClients = 0;
server->maxPing = 0;
server->minPing = 0;
server->ping = -1;
server->game[0] = '\0';
server->gameType = 0;
server->netType = 0;
server->g_humanplayers = 0;
server->g_needpass = 0;
server->allowAnonymous = 0;
}
#define MAX_SERVERSPERPACKET 256
/*
===================
CL_ServersResponsePacket
===================
*/
void CL_ServersResponsePacket( const netadr_t* from, msg_t *msg, qboolean extended ) {
int i, j, count, total;
netadr_t addresses[MAX_SERVERSPERPACKET];
int numservers;
byte* buffptr;
byte* buffend;
Com_Printf( "CL_ServersResponsePacket\n" );
if ( cls.numglobalservers == -1 ) {
// state to detect lack of servers or lack of response
cls.numglobalservers = 0;
cls.numGlobalServerAddresses = 0;
}
// parse through server response string
numservers = 0;
buffptr = msg->data;
buffend = buffptr + msg->cursize;
// advance to initial token
do
{
if(*buffptr == '\\' || (extended && *buffptr == '/'))
break;
buffptr++;
} while (buffptr < buffend);
while (buffptr + 1 < buffend)
{
// IPv4 address
if (*buffptr == '\\')
{
buffptr++;
if (buffend - buffptr < sizeof(addresses[numservers].ip) + sizeof(addresses[numservers].port) + 1)
break;
for(i = 0; i < sizeof(addresses[numservers].ip); i++)
addresses[numservers].ip[i] = *buffptr++;
addresses[numservers].type = NA_IP;
}
// IPv6 address, if it's an extended response
else if (extended && *buffptr == '/')
{
buffptr++;
if (buffend - buffptr < sizeof(addresses[numservers].ip6) + sizeof(addresses[numservers].port) + 1)
break;
for(i = 0; i < sizeof(addresses[numservers].ip6); i++)
addresses[numservers].ip6[i] = *buffptr++;
addresses[numservers].type = NA_IP6;
addresses[numservers].scope_id = from->scope_id;
}
else
// syntax error!
break;
// parse out port
addresses[numservers].port = (*buffptr++) << 8;
addresses[numservers].port += *buffptr++;
addresses[numservers].port = BigShort( addresses[numservers].port );
// syntax check
if (*buffptr != '\\' && *buffptr != '/')
break;
numservers++;
if (numservers >= MAX_SERVERSPERPACKET)
break;
}
count = cls.numglobalservers;
for (i = 0; i < numservers && count < MAX_GLOBAL_SERVERS; i++) {
// build net address
serverInfo_t *server = &cls.globalServers[count];
// Tequila: It's possible to have sent many master server requests. Then
// we may receive many times the same addresses from the master server.
// We just avoid to add a server if it is still in the global servers list.
for (j = 0; j < count; j++)
{
if (NET_CompareAdr(cls.globalServers[j].adr, addresses[i]))
break;
}
if (j < count)
continue;
CL_InitServerInfo( server, &addresses[i] );
// advance to next slot
count++;
}
// if getting the global list
if ( count >= MAX_GLOBAL_SERVERS && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS )
{
// if we couldn't store the servers in the main list anymore
for (; i < numservers && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS; i++)
{
// just store the addresses in an additional list
cls.globalServerAddresses[cls.numGlobalServerAddresses++] = addresses[i];
}
}
cls.numglobalservers = count;
total = count + cls.numGlobalServerAddresses;
Com_Printf( "%d servers parsed (total %d)\n", numservers, total );
}
/*
=================
CL_ConnectionlessPacket
Responses to broadcasts, etc
=================
*/
void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) {
char *s;
char *c;
int challenge = 0;
MSG_BeginReadingOOB( msg );
MSG_ReadLong( msg ); // skip the -1
s = MSG_ReadStringLine( msg );
Cmd_TokenizeString( s );
c = Cmd_Argv( 0 );
Com_DPrintf ("CL packet %s: %s\n", NET_AdrToStringwPort(from), c);
// challenge from the server we are connecting to
if (!Q_stricmp(c, "challengeResponse"))
{
char *strver;
int ver;
if (clc.state != CA_CONNECTING)
{
Com_DPrintf("Unwanted challenge response received. Ignored.\n");
return;
}
c = Cmd_Argv( 2 );
if(*c)
challenge = atoi(c);
strver = Cmd_Argv( 3 );
if(*strver)
{
ver = atoi(strver);
if(ver != com_protocol->integer)
{
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer > 0)
{
// Server is ioq3 but has a different protocol than we do.
// Fall back to idq3 protocol.
clc.compat = qtrue;
Com_Printf(S_COLOR_YELLOW "Warning: Server reports protocol version %d, "
"we have %d. Trying legacy protocol %d.\n",
ver, com_protocol->integer, com_legacyprotocol->integer);
}
else
#endif
{
Com_Printf(S_COLOR_YELLOW "Warning: Server reports protocol version %d, we have %d. "
"Trying anyways.\n", ver, com_protocol->integer);
}
}
}
#ifdef LEGACY_PROTOCOL
else
clc.compat = qtrue;
if(clc.compat)
{
if(!NET_CompareAdr(from, clc.serverAddress))
{
// This challenge response is not coming from the expected address.
// Check whether we have a matching client challenge to prevent
// connection hi-jacking.
if(!*c || challenge != clc.challenge)
{
Com_DPrintf("Challenge response received from unexpected source. Ignored.\n");
return;
}
}
}
else
#endif
{
if(!*c || challenge != clc.challenge)
{
Com_Printf("Bad challenge for challengeResponse. Ignored.\n");
return;
}
}
// start sending challenge response instead of challenge request packets
clc.challenge = atoi(Cmd_Argv(1));
clc.state = CA_CHALLENGING;
clc.connectPacketCount = 0;
clc.connectTime = -99999;
// take this address as the new server address. This allows
// a server proxy to hand off connections to multiple servers
clc.serverAddress = from;
Com_DPrintf ("challengeResponse: %d\n", clc.challenge);
return;
}
// server connection
if ( !Q_stricmp( c, "connectResponse" ) ) {
if ( clc.state >= CA_CONNECTED ) {
Com_Printf( "Dup connect received. Ignored.\n" );
return;
}
if ( clc.state != CA_CHALLENGING ) {
Com_Printf( "connectResponse packet while not connecting. Ignored.\n" );
return;
}
if ( !NET_CompareAdr( from, clc.serverAddress ) ) {
Com_Printf( "connectResponse from wrong address. Ignored.\n" );
return;
}
#ifdef LEGACY_PROTOCOL
if(!clc.compat)
#endif
{
c = Cmd_Argv(1);
if(*c)
challenge = atoi(c);
else
{
Com_Printf("Bad connectResponse received. Ignored.\n");
return;
}
if(challenge != clc.challenge)
{
Com_Printf("ConnectResponse with bad challenge received. Ignored.\n");
return;
}
}
#ifdef LEGACY_PROTOCOL
Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableValue("net_qport"),
clc.challenge, clc.compat);
#else
Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableValue("net_qport"),
clc.challenge, qfalse);
#endif
clc.state = CA_CONNECTED;
clc.lastPacketSentTime = -9999; // send first packet immediately
return;
}
// server responding to an info broadcast
if ( !Q_stricmp( c, "infoResponse" ) ) {
CL_ServerInfoPacket( from, msg );
return;
}
// server responding to a get playerlist
if ( !Q_stricmp( c, "statusResponse" ) ) {
CL_ServerStatusResponse( from, msg );
return;
}
// echo request from server
if ( !Q_stricmp( c, "echo" ) ) {
NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv( 1 ) );
return;
}
// cd check
if ( !Q_stricmp( c, "keyAuthorize" ) ) {
// we don't use these now, so dump them on the floor
return;
}
// global MOTD from id
if ( !Q_stricmp( c, "motd" ) ) {
CL_MotdPacket( from );
return;
}
// echo request from server
if ( !Q_stricmp( c, "print" ) ) {
s = MSG_ReadString( msg );
Q_strncpyz( clc.serverMessage, s, sizeof( clc.serverMessage ) );
Com_Printf( "%s", s );
return;
}
// list of servers sent back by a master server (classic)
if ( !Q_strncmp( c, "getserversResponse", 18 ) ) {
CL_ServersResponsePacket( &from, msg, qfalse );
return;
}
// list of servers sent back by a master server (extended)
if ( !Q_strncmp(c, "getserversExtResponse", 21) ) {
CL_ServersResponsePacket( &from, msg, qtrue );
return;
}
Com_DPrintf( "Unknown connectionless packet command.\n" );
}
/*
=================
CL_PacketEvent
A packet has arrived from the main event loop
=================
*/
void CL_PacketEvent( netadr_t from, msg_t *msg ) {
int headerBytes;
clc.lastPacketTime = cls.realtime;
if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) {
CL_ConnectionlessPacket( from, msg );
return;
}
if ( clc.state < CA_CONNECTED ) {
return; // can't be a valid sequenced packet
}
if ( msg->cursize < 4 ) {
Com_Printf ("%s: Runt packet\n", NET_AdrToStringwPort( from ));
return;
}
//
// packet from server
//
if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
Com_DPrintf( "%s:sequenced packet without connection\n"
, NET_AdrToStringwPort( from ) );
// FIXME: send a client disconnect?
return;
}
if ( !CL_Netchan_Process( &clc.netchan, msg ) ) {
return; // out of order, duplicated, etc
}
// the header is different lengths for reliable and unreliable messages
headerBytes = msg->readcount;
// track the last message received so it can be returned in
// client messages, allowing the server to detect a dropped
// gamestate
clc.serverMessageSequence = LittleLong( *(int *)msg->data );
clc.lastPacketTime = cls.realtime;
CL_ParseServerMessage( msg );
//
// we don't know if it is ok to save a demo message until
// after we have parsed the frame
//
if ( clc.demorecording && !clc.demowaiting ) {
CL_WriteDemoMessage( msg, headerBytes );
}
}
/*
==================
CL_CheckTimeout
==================
*/
void CL_CheckTimeout( void ) {
//
// check timeout
//
if ( ( !CL_CheckPaused() || !sv_paused->integer )
&& clc.state >= CA_CONNECTED && clc.state != CA_CINEMATIC
&& cls.realtime - clc.lastPacketTime > cl_timeout->value * 1000 ) {
if ( ++cl.timeoutcount > 5 ) { // timeoutcount saves debugger
Com_Printf( "\nServer connection timed out.\n" );
CL_Disconnect( qtrue );
return;
}
} else {
cl.timeoutcount = 0;
}
}
/*
==================
CL_CheckPaused
Check whether client has been paused.
==================
*/
qboolean CL_CheckPaused(void)
{
// if cl_paused->modified is set, the cvar has only been changed in
// this frame. Keep paused in this frame to ensure the server doesn't
// lag behind.
if(cl_paused->integer || cl_paused->modified)
return qtrue;
return qfalse;
}
//============================================================================
/*
==================
CL_CheckUserinfo
==================
*/
void CL_CheckUserinfo( void ) {
// don't add reliable commands when not yet connected
if(clc.state < CA_CONNECTED)
return;
// don't overflow the reliable command buffer when paused
if(CL_CheckPaused())
return;
// send a reliable userinfo update if needed
if ( cvar_modifiedFlags & CVAR_USERINFO ) {
cvar_modifiedFlags &= ~CVAR_USERINFO;
CL_AddReliableCommand(va("userinfo \"%s\"", Cvar_InfoString( CVAR_USERINFO ) ), qfalse);
}
}
/*
==================
CL_Frame
==================
*/
void CL_Frame( int msec ) {
if ( !com_cl_running->integer ) {
return;
}
#ifdef USE_CURL
if(clc.downloadCURLM) {
CL_cURL_PerformDownload();
// we can't process frames normally when in disconnected
// download mode since the ui vm expects clc.state to be
// CA_CONNECTED
if(clc.cURLDisconnected) {
cls.realFrametime = msec;
cls.frametime = msec;
cls.realtime += cls.frametime;
SCR_UpdateScreen();
S_Update();
Con_RunConsole();
cls.framecount++;
return;
}
}
#endif
if ( cls.cddialog ) {
// bring up the cd error dialog if needed
cls.cddialog = qfalse;
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NEED_CD );
} else if ( cls.endgamemenu ) {
cls.endgamemenu = qfalse;
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_ENDGAME );
} else if ( clc.state == CA_DISCONNECTED && !( Key_GetCatcher( ) & KEYCATCH_UI )
&& !com_sv_running->integer && uivm ) {
// if disconnected, bring up the menu
S_StopAllSounds();
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_MAIN );
}
// if recording an avi, lock to a fixed fps
if ( ( CL_VideoRecording( ) && cl_aviFrameRate->integer && msec ) || ( cl_avidemo->integer && msec ) ) {
// save the current screen
if ( clc.state == CA_ACTIVE || cl_forceavidemo->integer ) {
if ( cl_avidemo->integer ) { // Legacy (screenshot) method
Cbuf_ExecuteText( EXEC_NOW, "screenshot silent\n" );
// fixed time for next frame
msec = ( 1000 / cl_avidemo->integer ) * com_timescale->value;
if ( msec == 0 ) {
msec = 1;
}
} else { // ioquake3 method
float fps = MIN(cl_aviFrameRate->value * com_timescale->value, 1000.0f);
float frameDuration = MAX(1000.0f / fps, 1.0f) + clc.aviVideoFrameRemainder;
CL_TakeVideoFrame( );
msec = (int)frameDuration;
clc.aviVideoFrameRemainder = frameDuration - msec;
}
}
}
if( cl_autoRecordDemo->integer ) {
if( clc.state == CA_ACTIVE && !clc.demorecording && !clc.demoplaying ) {
// If not recording a demo, and we should be, start one
qtime_t now;
char *nowString;
char *p;
char mapName[ MAX_QPATH ];
char serverName[ MAX_OSPATH ];
Com_RealTime( &now );
nowString = va( "%04d%02d%02d%02d%02d%02d",
1900 + now.tm_year,
1 + now.tm_mon,
now.tm_mday,
now.tm_hour,
now.tm_min,
now.tm_sec );
Q_strncpyz( serverName, clc.servername, MAX_OSPATH );
// Replace the ":" in the address as it is not a valid
// file name character
p = strstr( serverName, ":" );
if( p ) {
*p = '.';
}
Q_strncpyz( mapName, COM_SkipPath( cl.mapname ), sizeof( cl.mapname ) );
COM_StripExtension(mapName, mapName, sizeof(mapName));
Cbuf_ExecuteText( EXEC_NOW,
va( "record %s-%s-%s", nowString, serverName, mapName ) );
}
else if( clc.state != CA_ACTIVE && clc.demorecording ) {
// Recording, but not CA_ACTIVE, so stop recording
CL_StopRecord_f( );
}
}
// save the msec before checking pause
cls.realFrametime = msec;
// decide the simulation time
cls.frametime = msec;
cls.realtime += cls.frametime;
if ( cl_timegraph->integer ) {
SCR_DebugGraph ( cls.realFrametime * 0.25 );
}
// see if we need to update any userinfo
CL_CheckUserinfo();
// if we haven't gotten a packet in a long time,
// drop the connection
CL_CheckTimeout();
// send intentions now
CL_SendCmd();
// resend a connection request if necessary
CL_CheckForResend();
// decide on the serverTime to render
CL_SetCGameTime();
// update the screen
SCR_UpdateScreen();
// update audio
S_Update();
#ifdef USE_VOIP
CL_CaptureVoip();
#endif
#ifdef USE_MUMBLE
CL_UpdateMumble();
#endif
// advance local effects for next frame
SCR_RunCinematic();
Con_RunConsole();
cls.framecount++;
}
//============================================================================
// Ridah, startup-caching system
typedef struct {
char name[MAX_QPATH];
int hits;
int lastSetIndex;
} cacheItem_t;
typedef enum {
CACHE_SOUNDS,
CACHE_MODELS,
CACHE_IMAGES,
CACHE_NUMGROUPS
} cacheGroup_t;
static cacheItem_t cacheGroups[CACHE_NUMGROUPS] = {
{{'s','o','u','n','d',0}, CACHE_SOUNDS},
{{'m','o','d','e','l',0}, CACHE_MODELS},
{{'i','m','a','g','e',0}, CACHE_IMAGES},
};
#define MAX_CACHE_ITEMS 4096
#define CACHE_HIT_RATIO 0.75 // if hit on this percentage of maps, it'll get cached
static int cacheIndex;
static cacheItem_t cacheItems[CACHE_NUMGROUPS][MAX_CACHE_ITEMS];
static void CL_Cache_StartGather_f( void ) {
cacheIndex = 0;
memset( cacheItems, 0, sizeof( cacheItems ) );
Cvar_Set( "cl_cacheGathering", "1" );
}
static void CL_Cache_UsedFile_f( void ) {
char groupStr[MAX_QPATH];
char itemStr[MAX_QPATH];
int i,group;
cacheItem_t *item;
if ( Cmd_Argc() < 2 ) {
Com_Error( ERR_DROP, "usedfile without enough parameters\n" );
return;
}
strcpy( groupStr, Cmd_Argv( 1 ) );
strcpy( itemStr, Cmd_Argv( 2 ) );
for ( i = 3; i < Cmd_Argc(); i++ ) {
strcat( itemStr, " " );
strcat( itemStr, Cmd_Argv( i ) );
}
Q_strlwr( itemStr );
// find the cache group
for ( i = 0; i < CACHE_NUMGROUPS; i++ ) {
if ( !Q_strncmp( groupStr, cacheGroups[i].name, MAX_QPATH ) ) {
break;
}
}
if ( i == CACHE_NUMGROUPS ) {
Com_Error( ERR_DROP, "usedfile without a valid cache group\n" );
return;
}
// see if it's already there
group = i;
for ( i = 0, item = cacheItems[group]; i < MAX_CACHE_ITEMS; i++, item++ ) {
if ( !item->name[0] ) {
// didn't find it, so add it here
Q_strncpyz( item->name, itemStr, MAX_QPATH );
if ( cacheIndex > 9999 ) { // hack, but yeh
item->hits = cacheIndex;
} else {
item->hits++;
}
item->lastSetIndex = cacheIndex;
break;
}
if ( item->name[0] == itemStr[0] && !Q_strncmp( item->name, itemStr, MAX_QPATH ) ) {
if ( item->lastSetIndex != cacheIndex ) {
item->hits++;
item->lastSetIndex = cacheIndex;
}
break;
}
}
}
static void CL_Cache_SetIndex_f( void ) {
if ( Cmd_Argc() < 2 ) {
Com_Error( ERR_DROP, "setindex needs an index\n" );
return;
}
cacheIndex = atoi( Cmd_Argv( 1 ) );
}
static void CL_Cache_MapChange_f( void ) {
cacheIndex++;
}
static void CL_Cache_EndGather_f( void ) {
// save the frequently used files to the cache list file
int i, j, handle, cachePass;
char filename[MAX_QPATH];
cachePass = (int)floor( (float)cacheIndex * CACHE_HIT_RATIO );
for ( i = 0; i < CACHE_NUMGROUPS; i++ ) {
Q_strncpyz( filename, cacheGroups[i].name, MAX_QPATH );
Q_strcat( filename, MAX_QPATH, ".cache" );
handle = FS_FOpenFileWrite( filename );
for ( j = 0; j < MAX_CACHE_ITEMS; j++ ) {
// if it's a valid filename, and it's been hit enough times, cache it
if ( cacheItems[i][j].hits >= cachePass && strstr( cacheItems[i][j].name, "/" ) ) {
FS_Write( cacheItems[i][j].name, strlen( cacheItems[i][j].name ), handle );
FS_Write( "\n", 1, handle );
}
}
FS_FCloseFile( handle );
}
Cvar_Set( "cl_cacheGathering", "0" );
}
// done.
//============================================================================
/*
================
CL_MapRestart_f
================
*/
void CL_MapRestart_f( void ) {
if ( !com_cl_running ) {
return;
}
if ( !com_cl_running->integer ) {
return;
}
Com_Printf( "This command is no longer functional.\nUse \"loadgame current\" to load the current map." );
}
/*
================
CL_SetRecommended_f
================
*/
void CL_SetRecommended_f( void ) {
if ( Cmd_Argc() > 1 ) {
Com_SetRecommended( qtrue );
} else {
Com_SetRecommended( qfalse );
}
}
/*
================
CL_RefPrintf
DLL glue
================
*/
static __attribute__ ((format (printf, 2, 3))) void QDECL CL_RefPrintf( int print_level, const char *fmt, ...) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof ( msg ), fmt, argptr );
va_end( argptr );
if ( print_level == PRINT_ALL ) {
Com_Printf( "%s", msg );
} else if ( print_level == PRINT_WARNING ) {
Com_Printf( S_COLOR_YELLOW "%s", msg ); // yellow
} else if ( print_level == PRINT_DEVELOPER ) {
Com_DPrintf( S_COLOR_RED "%s", msg ); // red
}
}
/*
============
CL_ShutdownRef
============
*/
void CL_ShutdownRef( void ) {
if ( re.Shutdown ) {
re.Shutdown( qtrue );
}
memset( &re, 0, sizeof( re ) );
#ifdef USE_RENDERER_DLOPEN
if ( rendererLib ) {
Sys_UnloadLibrary( rendererLib );
rendererLib = NULL;
}
#endif
}
/*
============
CL_InitRenderer
============
*/
void CL_InitRenderer( void ) {
// this sets up the renderer and calls R_Init
re.BeginRegistration( &cls.glconfig );
// load character sets
cls.charSetShader = re.RegisterShader( "gfx/2d/bigchars" );
cls.whiteShader = re.RegisterShader( "white" );
cls.consoleShader = re.RegisterShader( "console" );
cls.consoleShader2 = re.RegisterShader( "console2" );
g_console_field_width = cls.glconfig.vidWidth / SMALLCHAR_WIDTH - 2;
g_consoleField.widthInChars = g_console_field_width;
}
/*
============================
CL_StartHunkUsers
After the server has cleared the hunk, these will need to be restarted
This is the only place that any of these functions are called from
============================
*/
void CL_StartHunkUsers( qboolean rendererOnly ) {
if ( !com_cl_running ) {
return;
}
if ( !com_cl_running->integer ) {
return;
}
if ( !cls.rendererStarted ) {
cls.rendererStarted = qtrue;
CL_InitRenderer();
}
if ( rendererOnly ) {
return;
}
if ( !cls.soundStarted ) {
cls.soundStarted = qtrue;
S_Init();
}
if ( !cls.soundRegistered ) {
cls.soundRegistered = qtrue;
S_BeginRegistration();
}
if( com_dedicated->integer ) {
return;
}
if ( !cls.uiStarted ) {
cls.uiStarted = qtrue;
CL_InitUI();
}
}
int CL_ScaledMilliseconds( void ) {
return Sys_Milliseconds() * com_timescale->value;
}
/*
============
CL_InitRef
============
*/
void CL_InitRef( void ) {
refimport_t ri;
refexport_t *ret;
#ifdef USE_RENDERER_DLOPEN
GetRefAPI_t GetRefAPI;
char dllName[MAX_OSPATH];
#endif
Com_Printf( "----- Initializing Renderer ----\n" );
#ifdef USE_RENDERER_DLOPEN
cl_renderer = Cvar_Get("cl_renderer", "opengl1", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED);
Com_sprintf(dllName, sizeof(dllName), "renderer_sp_%s_" ARCH_STRING DLL_EXT, cl_renderer->string);
if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString))
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Cvar_ForceReset("cl_renderer");
Com_sprintf(dllName, sizeof(dllName), "renderer_sp_opengl1_" ARCH_STRING DLL_EXT);
rendererLib = Sys_LoadDll(dllName, qfalse);
}
if(!rendererLib)
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Com_Error(ERR_FATAL, "Failed to load renderer");
}
GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI");
if(!GetRefAPI)
{
Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError());
}
#endif
ri.Cmd_AddCommand = Cmd_AddCommand;
ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
ri.Cmd_Argc = Cmd_Argc;
ri.Cmd_Argv = Cmd_Argv;
ri.Cmd_ExecuteText = Cbuf_ExecuteText;
ri.Printf = CL_RefPrintf;
ri.Error = Com_Error;
ri.Milliseconds = CL_ScaledMilliseconds;
ri.Z_Malloc = Z_Malloc;
ri.Free = Z_Free;
ri.Hunk_Clear = Hunk_ClearToMark;
#ifdef HUNK_DEBUG
ri.Hunk_AllocDebug = Hunk_AllocDebug;
#else
ri.Hunk_Alloc = Hunk_Alloc;
#endif
ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
ri.CM_ClusterPVS = CM_ClusterPVS;
ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
ri.FS_ReadFile = FS_ReadFile;
ri.FS_FreeFile = FS_FreeFile;
ri.FS_WriteFile = FS_WriteFile;
ri.FS_FreeFileList = FS_FreeFileList;
ri.FS_ListFiles = FS_ListFiles;
ri.FS_FileIsInPAK = FS_FileIsInPAK;
ri.FS_FileExists = FS_FileExists;
ri.Cvar_Get = Cvar_Get;
ri.Cvar_Set = Cvar_Set;
ri.Cvar_SetValue = Cvar_SetValue;
ri.Cvar_CheckRange = Cvar_CheckRange;
ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
// cinematic stuff
ri.CIN_UploadCinematic = CIN_UploadCinematic;
ri.CIN_PlayCinematic = CIN_PlayCinematic;
ri.CIN_RunCinematic = CIN_RunCinematic;
ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;
ri.IN_Init = IN_Init;
ri.IN_Shutdown = IN_Shutdown;
ri.IN_Restart = IN_Restart;
ri.ftol = Q_ftol;
ri.Sys_SetEnv = Sys_SetEnv;
ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit;
ri.Sys_GLimpInit = Sys_GLimpInit;
ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;
ret = GetRefAPI( REF_API_VERSION, &ri );
if ( !ret ) {
Com_Error( ERR_FATAL, "Couldn't initialize refresh" );
}
re = *ret;
Com_Printf( "---- Renderer Initialization Complete ----\n" );
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
}
// RF, trap manual client damage commands so users can't issue them manually
void CL_ClientDamageCommand( void ) {
// do nothing
}
#if defined (__i386__)
#define BIN_STRING "x86"
#endif
// NERVE - SMF
void CL_startMultiplayer_f( void ) {
char binName[MAX_OSPATH];
#if defined(_WIN64) || defined(__WIN64__)
Com_sprintf(binName, sizeof(binName), "ioWolfMP." ARCH_STRING ".exe");
Sys_StartProcess( binName, qtrue );
#elif defined(_WIN32) || defined(__WIN32__)
Com_sprintf(binName, sizeof(binName), "ioWolfMP." ARCH_STRING ".exe");
Sys_StartProcess( binName, qtrue );
#elif defined(__i386__) && (!defined(_WIN32) || !defined(__WIN32__))
Com_sprintf(binName, sizeof(binName), "./iowolfmp." BIN_STRING );
Sys_StartProcess( binName, qtrue );
#else
Com_sprintf(binName, sizeof(binName), "./iowolfmp." ARCH_STRING );
Sys_StartProcess( binName, qtrue );
#endif
}
// -NERVE - SMF
//----(SA) added
/*
==============
CL_ShellExecute_URL_f
Format:
shellExecute "open" <url> <doExit>
TTimo
show_bug.cgi?id=447
only supporting "open" syntax for URL openings, others are not portable or need to be added on a case-by-case basis
the shellExecute syntax as been kept to remain compatible with win32 SP demo pk3, but this thing only does open URL
==============
*/
void CL_ShellExecute_URL_f( void ) {
qboolean doexit;
Com_DPrintf( "CL_ShellExecute_URL_f\n" );
if ( Q_stricmp( Cmd_Argv( 1 ),"open" ) ) {
Com_DPrintf( "invalid CL_ShellExecute_URL_f syntax (shellExecute \"open\" <url> <doExit>)\n" );
return;
}
if ( Cmd_Argc() < 4 ) {
doexit = qtrue;
} else {
doexit = (qboolean)( atoi( Cmd_Argv( 3 ) ) );
}
Sys_OpenURL( Cmd_Argv( 2 ),doexit );
}
//----(SA) end
//===========================================================================================
/*
===============
CL_Video_f
video
video [filename]
===============
*/
void CL_Video_f( void )
{
char filename[ MAX_OSPATH ];
int i, last;
if( !clc.demoplaying )
{
Com_Printf( "The video command can only be used when playing back demos\n" );
return;
}
if( Cmd_Argc( ) == 2 )
{
// explicit filename
Com_sprintf( filename, MAX_OSPATH, "videos/%s.avi", Cmd_Argv( 1 ) );
}
else
{
// scan for a free filename
for( i = 0; i <= 9999; i++ )
{
int a, b, c, d;
last = i;
a = last / 1000;
last -= a * 1000;
b = last / 100;
last -= b * 100;
c = last / 10;
last -= c * 10;
d = last;
Com_sprintf( filename, MAX_OSPATH, "videos/video%d%d%d%d.avi", a, b, c, d );
if( !FS_FileExists( filename ) )
break; // file doesn't exist
}
if( i > 9999 )
{
Com_Printf( S_COLOR_RED "ERROR: no free file names to create video\n" );
return;
}
}
CL_OpenAVIForWriting( filename );
}
/*
===============
CL_StopVideo_f
===============
*/
void CL_StopVideo_f( void )
{
CL_CloseAVI( );
}
/*
===============
CL_GenerateQKey
test to see if a valid QKEY_FILE exists. If one does not, try to generate
it by filling it with 2048 bytes of random data.
===============
*/
static void CL_GenerateQKey(void)
{
int len = 0;
unsigned char buff[ QKEY_SIZE ];
fileHandle_t f;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
if( len == QKEY_SIZE ) {
Com_Printf( "RTCWKEY found.\n" );
return;
}
else {
if( len > 0 ) {
Com_Printf( "RTCWKEY file size != %d, regenerating\n",
QKEY_SIZE );
}
Com_Printf( "RTCWKEY building random string\n" );
Com_RandomBytes( buff, sizeof(buff) );
f = FS_SV_FOpenFileWrite( QKEY_FILE );
if( !f ) {
Com_Printf( "RTCWKEY could not open %s for write\n",
QKEY_FILE );
return;
}
FS_Write( buff, sizeof(buff), f );
FS_FCloseFile( f );
Com_Printf( "RTCWKEY generated\n" );
}
}
/*
====================
CL_Init
====================
*/
void CL_Init( void ) {
Com_Printf( "----- Client Initialization -----\n" );
Con_Init();
if(!com_fullyInitialized)
{
CL_ClearState();
clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
cl_oldGameSet = qfalse;
}
cls.realtime = 0;
CL_InitInput();
//
// register our variables
//
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
#ifdef UPDATE_SERVER_NAME
cl_motd = Cvar_Get( "cl_motd", "1", 0 );
#endif
cl_timeout = Cvar_Get( "cl_timeout", "200", 0 );
cl_timeNudge = Cvar_Get( "cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get( "cl_shownet", "0", CVAR_TEMP );
cl_showSend = Cvar_Get( "cl_showSend", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get( "cl_showTimeDelta", "0", CVAR_TEMP );
cl_freezeDemo = Cvar_Get( "cl_freezeDemo", "0", CVAR_TEMP );
rcon_client_password = Cvar_Get( "rconPassword", "", CVAR_TEMP );
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_timedemo = Cvar_Get( "timedemo", "0", 0 );
cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE);
cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE);
cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE);
cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE);
cl_avidemo = Cvar_Get( "cl_avidemo", "0", 0 );
cl_forceavidemo = Cvar_Get( "cl_forceavidemo", "0", 0 );
rconAddress = Cvar_Get( "rconAddress", "", 0 );
cl_yawspeed = Cvar_Get( "cl_yawspeed", "140", CVAR_ARCHIVE );
cl_pitchspeed = Cvar_Get( "cl_pitchspeed", "140", CVAR_ARCHIVE );
cl_anglespeedkey = Cvar_Get( "cl_anglespeedkey", "1.5", 0 );
cl_maxpackets = Cvar_Get( "cl_maxpackets", "38", CVAR_ARCHIVE );
cl_packetdup = Cvar_Get( "cl_packetdup", "1", CVAR_ARCHIVE );
cl_run = Cvar_Get( "cl_run", "1", CVAR_ARCHIVE );
cl_sensitivity = Cvar_Get( "sensitivity", "5", CVAR_ARCHIVE );
cl_mouseAccel = Cvar_Get( "cl_mouseAccel", "0", CVAR_ARCHIVE );
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE );
// 0: legacy mouse acceleration
// 1: new implementation
cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE );
// offset for the power function (for style 1, ignored otherwise)
// this should be set to the max rate value
cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE );
Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse);
cl_showMouseRate = Cvar_Get( "cl_showmouserate", "0", 0 );
cl_allowDownload = Cvar_Get( "cl_allowDownload", "0", CVAR_ARCHIVE );
#ifdef USE_CURL_DLOPEN
cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE | CVAR_PROTECTED);
#endif
// init autoswitch so the ui will have it correctly even
// if the cgame hasn't been started
Cvar_Get( "cg_autoswitch", "2", CVAR_ARCHIVE );
// Rafael - particle switch
Cvar_Get( "cg_wolfparticles", "1", CVAR_ARCHIVE );
// done
cl_conXOffset = Cvar_Get( "cl_conXOffset", "0", 0 );
cl_inGameVideo = Cvar_Get( "r_inGameVideo", "1", CVAR_ARCHIVE );
cl_serverStatusResendTime = Cvar_Get( "cl_serverStatusResendTime", "750", 0 );
// RF
cl_recoilPitch = Cvar_Get( "cg_recoilPitch", "0", CVAR_ROM );
m_pitch = Cvar_Get( "m_pitch", "0.022", CVAR_ARCHIVE );
m_yaw = Cvar_Get( "m_yaw", "0.022", CVAR_ARCHIVE );
m_forward = Cvar_Get( "m_forward", "0.25", CVAR_ARCHIVE );
m_side = Cvar_Get( "m_side", "0.25", CVAR_ARCHIVE );
m_filter = Cvar_Get( "m_filter", "0", CVAR_ARCHIVE );
j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE);
j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE);
j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE);
j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE);
j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE);
j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE);
j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE);
j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE);
j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE);
j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE);
Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM );
Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE );
cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE);
cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE);
// ~ and `, as keys and characters
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE);
// userinfo
Cvar_Get( "name", "WolfPlayer", CVAR_USERINFO | CVAR_ARCHIVE );
cl_rate = Cvar_Get( "rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE ); // NERVE - SMF - changed from 3000
Cvar_Get( "snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "model", "bj2", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "head", "default", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "color", "4", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "sex", "male", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "password", "", CVAR_USERINFO );
Cvar_Get( "cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE );
#ifdef USE_MUMBLE
cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH);
cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE);
#endif
#ifdef USE_VOIP
cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0);
cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0);
cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE);
cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE);
cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE);
cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE);
cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE);
cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE);
Cvar_CheckRange( cl_voip, 0, 1, qtrue );
cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM);
#endif
//----(SA) added
Cvar_Get( "cg_autoactivate", "1", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "cg_emptyswitch", "0", CVAR_USERINFO | CVAR_ARCHIVE );
//----(SA) end
// cgame might not be initialized before menu is used
Cvar_Get( "cg_viewsize", "100", CVAR_ARCHIVE );
// Make sure cg_stereoSeparation is zero as that variable is deprecated and should not be used anymore.
Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM);
cl_missionStats = Cvar_Get( "g_missionStats", "0", CVAR_ROM );
cl_waitForFire = Cvar_Get( "cl_waitForFire", "0", CVAR_ROM );
// NERVE - SMF - localization
cl_language = Cvar_Get( "cl_language", "0", CVAR_ARCHIVE );
cl_debugTranslation = Cvar_Get( "cl_debugTranslation", "0", 0 );
// -NERVE - SMF
//
// register our commands
//
Cmd_AddCommand( "cmd", CL_ForwardToServer_f );
Cmd_AddCommand( "configstrings", CL_Configstrings_f );
Cmd_AddCommand( "clientinfo", CL_Clientinfo_f );
Cmd_AddCommand( "snd_restart", CL_Snd_Restart_f );
Cmd_AddCommand( "vid_restart", CL_Vid_Restart_f );
Cmd_AddCommand( "disconnect", CL_Disconnect_f );
Cmd_AddCommand( "record", CL_Record_f );
Cmd_AddCommand( "demo", CL_PlayDemo_f );
Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName );
Cmd_AddCommand( "cinematic", CL_PlayCinematic_f );
Cmd_AddCommand( "stoprecord", CL_StopRecord_f );
Cmd_AddCommand( "connect", CL_Connect_f );
Cmd_AddCommand( "reconnect", CL_Reconnect_f );
Cmd_AddCommand( "localservers", CL_LocalServers_f );
Cmd_AddCommand( "globalservers", CL_GlobalServers_f );
Cmd_AddCommand( "rcon", CL_Rcon_f );
Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon );
Cmd_AddCommand( "ping", CL_Ping_f );
Cmd_AddCommand( "serverstatus", CL_ServerStatus_f );
Cmd_AddCommand( "showip", CL_ShowIP_f );
Cmd_AddCommand( "fs_openedList", CL_OpenedPK3List_f );
Cmd_AddCommand( "fs_referencedList", CL_ReferencedPK3List_f );
Cmd_AddCommand ("video", CL_Video_f );
Cmd_AddCommand ("stopvideo", CL_StopVideo_f );
// Ridah, startup-caching system
Cmd_AddCommand( "cache_startgather", CL_Cache_StartGather_f );
Cmd_AddCommand( "cache_usedfile", CL_Cache_UsedFile_f );
Cmd_AddCommand( "cache_setindex", CL_Cache_SetIndex_f );
Cmd_AddCommand( "cache_mapchange", CL_Cache_MapChange_f );
Cmd_AddCommand( "cache_endgather", CL_Cache_EndGather_f );
Cmd_AddCommand( "updatehunkusage", CL_UpdateLevelHunkUsage );
Cmd_AddCommand( "updatescreen", SCR_UpdateScreen );
// done.
// RF, add this command so clients can't bind a key to send client damage commands to the server
Cmd_AddCommand( "cld", CL_ClientDamageCommand );
Cmd_AddCommand( "startMultiplayer", CL_startMultiplayer_f ); // NERVE - SMF
Cmd_AddCommand( "shellExecute", CL_ShellExecute_URL_f );
// RF, prevent users from issuing a map_restart manually
Cmd_AddCommand( "map_restart", CL_MapRestart_f );
Cmd_AddCommand( "setRecommended", CL_SetRecommended_f );
CL_InitRef();
SCR_Init();
// Cbuf_Execute();
Cvar_Set( "cl_running", "1" );
CL_GenerateQKey();
Cvar_Get( "cl_guid", "", CVAR_USERINFO | CVAR_ROM );
CL_UpdateGUID( NULL, 0 );
Com_Printf( "----- Client Initialization Complete -----\n" );
}
/*
===============
CL_Shutdown
===============
*/
void CL_Shutdown( char *finalmsg, qboolean disconnect, qboolean quit ) {
static qboolean recursive = qfalse;
// check whether the client is running at all.
if(!(com_cl_running && com_cl_running->integer))
return;
Com_Printf( "----- Client Shutdown (%s) -----\n", finalmsg );
if ( recursive ) {
Com_Printf( "WARNING: Recursive shutdown\n" );
return;
}
recursive = qtrue;
noGameRestart = quit;
if(disconnect)
CL_Disconnect(qtrue);
CL_ClearMemory(qtrue);
CL_Snd_Shutdown();
Cmd_RemoveCommand( "cmd" );
Cmd_RemoveCommand( "configstrings" );
Cmd_RemoveCommand ("clientinfo");
Cmd_RemoveCommand( "snd_restart" );
Cmd_RemoveCommand( "vid_restart" );
Cmd_RemoveCommand( "disconnect" );
Cmd_RemoveCommand( "record" );
Cmd_RemoveCommand( "demo" );
Cmd_RemoveCommand( "cinematic" );
Cmd_RemoveCommand( "stoprecord" );
Cmd_RemoveCommand( "connect" );
Cmd_RemoveCommand ("reconnect");
Cmd_RemoveCommand( "localservers" );
Cmd_RemoveCommand( "globalservers" );
Cmd_RemoveCommand( "rcon" );
Cmd_RemoveCommand( "ping" );
Cmd_RemoveCommand( "serverstatus" );
Cmd_RemoveCommand( "showip" );
Cmd_RemoveCommand ("fs_openedList");
Cmd_RemoveCommand ("fs_referencedList");
Cmd_RemoveCommand( "model" );
Cmd_RemoveCommand ("video");
Cmd_RemoveCommand ("stopvideo");
// Ridah, startup-caching system
Cmd_RemoveCommand( "cache_startgather" );
Cmd_RemoveCommand( "cache_usedfile" );
Cmd_RemoveCommand( "cache_setindex" );
Cmd_RemoveCommand( "cache_mapchange" );
Cmd_RemoveCommand( "cache_endgather" );
Cmd_RemoveCommand( "updatehunkusage" );
// done.
CL_ShutdownInput();
Con_Shutdown();
Cvar_Set( "cl_running", "0" );
recursive = qfalse;
memset( &cls, 0, sizeof( cls ) );
Key_SetCatcher( 0 );
Com_Printf( "-----------------------\n" );
}
static void CL_SetServerInfo( serverInfo_t *server, const char *info, int ping ) {
if ( server ) {
if ( info ) {
server->clients = atoi( Info_ValueForKey( info, "clients" ) );
Q_strncpyz( server->hostName,Info_ValueForKey( info, "hostname" ), MAX_NAME_LENGTH );
Q_strncpyz( server->mapName, Info_ValueForKey( info, "mapname" ), MAX_NAME_LENGTH );
server->maxClients = atoi( Info_ValueForKey( info, "sv_maxclients" ) );
Q_strncpyz( server->game,Info_ValueForKey( info, "game" ), MAX_NAME_LENGTH );
server->gameType = atoi( Info_ValueForKey( info, "gametype" ) );
server->netType = atoi( Info_ValueForKey( info, "nettype" ) );
server->minPing = atoi( Info_ValueForKey( info, "minping" ) );
server->maxPing = atoi( Info_ValueForKey( info, "maxping" ) );
server->g_humanplayers = atoi( Info_ValueForKey( info, "g_humanplayers" ) );
server->g_needpass = atoi( Info_ValueForKey( info, "g_needpass" ) );
server->allowAnonymous = atoi( Info_ValueForKey( info, "sv_allowAnonymous" ) );
}
server->ping = ping;
}
}
static void CL_SetServerInfoByAddress( netadr_t from, const char *info, int ping ) {
int i;
for ( i = 0; i < MAX_OTHER_SERVERS; i++ ) {
if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) {
CL_SetServerInfo( &cls.localServers[i], info, ping );
}
}
for ( i = 0; i < MAX_GLOBAL_SERVERS; i++ ) {
if ( NET_CompareAdr( from, cls.globalServers[i].adr ) ) {
CL_SetServerInfo( &cls.globalServers[i], info, ping );
}
}
for ( i = 0; i < MAX_OTHER_SERVERS; i++ ) {
if ( NET_CompareAdr( from, cls.favoriteServers[i].adr ) ) {
CL_SetServerInfo( &cls.favoriteServers[i], info, ping );
}
}
}
/*
===================
CL_ServerInfoPacket
===================
*/
void CL_ServerInfoPacket( netadr_t from, msg_t *msg ) {
int i, type;
char info[MAX_INFO_STRING];
char *infoString;
int prot;
char *gamename;
qboolean gameMismatch;
infoString = MSG_ReadString( msg );
// if this isn't the correct gamename, ignore it
gamename = Info_ValueForKey( infoString, "gamename" );
#ifdef LEGACY_PROTOCOL
// gamename is optional for legacy protocol
if (com_legacyprotocol->integer && !*gamename)
gameMismatch = qfalse;
else
#endif
gameMismatch = !*gamename || strcmp(gamename, com_gamename->string) != 0;
if (gameMismatch)
{
Com_DPrintf( "Game mismatch in info packet: %s\n", infoString );
return;
}
// if this isn't the correct protocol version, ignore it
prot = atoi( Info_ValueForKey( infoString, "protocol" ) );
if(prot != com_protocol->integer
#ifdef LEGACY_PROTOCOL
&& prot != com_legacyprotocol->integer
#endif
)
{
Com_DPrintf( "Different protocol info packet: %s\n", infoString );
// return;
}
// iterate servers waiting for ping response
for ( i = 0; i < MAX_PINGREQUESTS; i++ )
{
if ( cl_pinglist[i].adr.port && !cl_pinglist[i].time && NET_CompareAdr( from, cl_pinglist[i].adr ) ) {
// calc ping time
cl_pinglist[i].time = Sys_Milliseconds() - cl_pinglist[i].start;
Com_DPrintf( "ping time %dms from %s\n", cl_pinglist[i].time, NET_AdrToString( from ) );
// save of info
Q_strncpyz( cl_pinglist[i].info, infoString, sizeof( cl_pinglist[i].info ) );
// tack on the net type
// NOTE: make sure these types are in sync with the netnames strings in the UI
switch ( from.type )
{
case NA_BROADCAST:
case NA_IP:
type = 1;
break;
case NA_IP6:
type = 2;
break;
default:
type = 0;
break;
}
Info_SetValueForKey( cl_pinglist[i].info, "nettype", va( "%d", type ) );
CL_SetServerInfoByAddress( from, infoString, cl_pinglist[i].time );
return;
}
}
// if not just sent a local broadcast or pinging local servers
if ( cls.pingUpdateSource != AS_LOCAL ) {
return;
}
for ( i = 0 ; i < MAX_OTHER_SERVERS ; i++ ) {
// empty slot
if ( cls.localServers[i].adr.port == 0 ) {
break;
}
// avoid duplicate
if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) {
return;
}
}
if ( i == MAX_OTHER_SERVERS ) {
Com_DPrintf( "MAX_OTHER_SERVERS hit, dropping infoResponse\n" );
return;
}
// add this to the list
cls.numlocalservers = i + 1;
CL_InitServerInfo( &cls.localServers[i], &from );
Q_strncpyz( info, MSG_ReadString( msg ), MAX_INFO_STRING );
if ( strlen( info ) ) {
if ( info[strlen( info ) - 1] != '\n' ) {
Q_strcat( info, sizeof(info), "\n" );
}
Com_Printf( "%s: %s", NET_AdrToStringwPort( from ), info );
}
}
/*
===================
CL_GetServerStatus
===================
*/
serverStatus_t *CL_GetServerStatus( netadr_t from ) {
int i, oldest, oldestTime;
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
return &cl_serverStatusList[i];
}
}
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( cl_serverStatusList[i].retrieved ) {
return &cl_serverStatusList[i];
}
}
oldest = -1;
oldestTime = 0;
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( oldest == -1 || cl_serverStatusList[i].startTime < oldestTime ) {
oldest = i;
oldestTime = cl_serverStatusList[i].startTime;
}
}
return &cl_serverStatusList[oldest];
}
/*
===================
CL_ServerStatus
===================
*/
int CL_ServerStatus( char *serverAddress, char *serverStatusString, int maxLen ) {
int i;
netadr_t to;
serverStatus_t *serverStatus;
// if no server address then reset all server status requests
if ( !serverAddress ) {
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
cl_serverStatusList[i].address.port = 0;
cl_serverStatusList[i].retrieved = qtrue;
}
return qfalse;
}
// get the address
if ( !NET_StringToAdr( serverAddress, &to, NA_UNSPEC) ) {
return qfalse;
}
serverStatus = CL_GetServerStatus( to );
// if no server status string then reset the server status request for this address
if ( !serverStatusString ) {
serverStatus->retrieved = qtrue;
return qfalse;
}
// if this server status request has the same address
if ( NET_CompareAdr( to, serverStatus->address ) ) {
// if we received a response for this server status request
if ( !serverStatus->pending ) {
Q_strncpyz( serverStatusString, serverStatus->string, maxLen );
serverStatus->retrieved = qtrue;
serverStatus->startTime = 0;
return qtrue;
}
// resend the request regularly
else if ( serverStatus->startTime < Com_Milliseconds() - cl_serverStatusResendTime->integer ) {
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->time = 0;
serverStatus->startTime = Com_Milliseconds();
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
}
// if retrieved
else if ( serverStatus->retrieved ) {
serverStatus->address = to;
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->startTime = Com_Milliseconds();
serverStatus->time = 0;
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
return qfalse;
}
/*
===================
CL_ServerStatusResponse
===================
*/
void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) {
char *s;
char info[MAX_INFO_STRING];
int i, l, score, ping;
int len;
serverStatus_t *serverStatus;
serverStatus = NULL;
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
serverStatus = &cl_serverStatusList[i];
break;
}
}
// if we didn't request this server status
if ( !serverStatus ) {
return;
}
s = MSG_ReadStringLine( msg );
len = 0;
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "%s", s );
if ( serverStatus->print ) {
Com_Printf( "Server settings:\n" );
// print cvars
while ( *s ) {
for ( i = 0; i < 2 && *s; i++ ) {
if ( *s == '\\' ) {
s++;
}
l = 0;
while ( *s ) {
info[l++] = *s;
if ( l >= MAX_INFO_STRING - 1 ) {
break;
}
s++;
if ( *s == '\\' ) {
break;
}
}
info[l] = '\0';
if ( i ) {
Com_Printf( "%s\n", info );
} else {
Com_Printf( "%-24s", info );
}
}
}
}
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\" );
if ( serverStatus->print ) {
Com_Printf( "\nPlayers:\n" );
Com_Printf( "num: score: ping: name:\n" );
}
for ( i = 0, s = MSG_ReadStringLine( msg ); *s; s = MSG_ReadStringLine( msg ), i++ ) {
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\%s", s );
if ( serverStatus->print ) {
score = ping = 0;
sscanf( s, "%d %d", &score, &ping );
s = strchr( s, ' ' );
if ( s ) {
s = strchr( s + 1, ' ' );
}
if ( s ) {
s++;
} else {
s = "unknown";
}
Com_Printf( "%-2d %-3d %-3d %s\n", i, score, ping, s );
}
}
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\" );
serverStatus->time = Com_Milliseconds();
serverStatus->address = from;
serverStatus->pending = qfalse;
if (serverStatus->print) {
serverStatus->retrieved = qtrue;
}
}
/*
==================
CL_LocalServers_f
==================
*/
void CL_LocalServers_f( void ) {
char *message;
int i, j;
netadr_t to;
Com_Printf( "Scanning for servers on the local network...\n" );
// reset the list, waiting for response
cls.numlocalservers = 0;
cls.pingUpdateSource = AS_LOCAL;
for ( i = 0; i < MAX_OTHER_SERVERS; i++ ) {
qboolean b = cls.localServers[i].visible;
Com_Memset( &cls.localServers[i], 0, sizeof( cls.localServers[i] ) );
cls.localServers[i].visible = b;
}
Com_Memset( &to, 0, sizeof( to ) );
// The 'xxx' in the message is a challenge that will be echoed back
// by the server. We don't care about that here, but master servers
// can use that to prevent spoofed server responses from invalid ip
message = "\377\377\377\377getinfo xxx";
// send each message twice in case one is dropped
for ( i = 0 ; i < 2 ; i++ ) {
// send a broadcast packet on each server port
// we support multiple server ports so a single machine
// can nicely run multiple servers
for ( j = 0 ; j < NUM_SERVER_PORTS ; j++ ) {
to.port = BigShort( (short)( PORT_SERVER + j ) );
to.type = NA_BROADCAST;
NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
to.type = NA_MULTICAST6;
NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
}
}
}
/*
==================
CL_GlobalServers_f
==================
*/
void CL_GlobalServers_f( void ) {
netadr_t to;
int count, i, masterNum;
char command[1024], *masteraddress;
if ((count = Cmd_Argc()) < 3 || (masterNum = atoi(Cmd_Argv(1))) < 0 || masterNum > MAX_MASTER_SERVERS - 1)
{
Com_Printf("usage: globalservers <master# 0-%d> <protocol> [keywords]\n", MAX_MASTER_SERVERS - 1);
return;
}
sprintf(command, "sv_master%d", masterNum + 1);
masteraddress = Cvar_VariableString(command);
if(!*masteraddress)
{
Com_Printf( "CL_GlobalServers_f: Error: No master server address given.\n");
return;
}
// reset the list, waiting for response
// -1 is used to distinguish a "no response"
i = NET_StringToAdr(masteraddress, &to, NA_UNSPEC);
if(!i)
{
Com_Printf( "CL_GlobalServers_f: Error: could not resolve address of master %s\n", masteraddress);
return;
}
else if(i == 2)
to.port = BigShort(PORT_MASTER);
Com_Printf("Requesting servers from master %s...\n", masteraddress);
cls.numglobalservers = -1;
cls.pingUpdateSource = AS_GLOBAL;
// Use the extended query for IPv6 masters
if (to.type == NA_IP6 || to.type == NA_MULTICAST6)
{
int v4enabled = Cvar_VariableIntegerValue("net_enabled") & NET_ENABLEV4;
if(v4enabled)
{
Com_sprintf(command, sizeof(command), "getserversExt %s %s",
com_gamename->string, Cmd_Argv(2));
}
else
{
Com_sprintf(command, sizeof(command), "getserversExt %s %s ipv6",
com_gamename->string, Cmd_Argv(2));
}
}
else if ( !Q_stricmp( com_gamename->string, LEGACY_MASTER_GAMENAME ) )
Com_sprintf(command, sizeof(command), "getservers %s",
Cmd_Argv(2));
else
Com_sprintf(command, sizeof(command), "getservers %s %s",
com_gamename->string, Cmd_Argv(2));
for (i=3; i < count; i++)
{
Q_strcat(command, sizeof(command), " ");
Q_strcat(command, sizeof(command), Cmd_Argv(i));
}
NET_OutOfBandPrint( NS_SERVER, to, "%s", command );
}
/*
==================
CL_GetPing
==================
*/
void CL_GetPing( int n, char *buf, int buflen, int *pingtime ) {
const char *str;
int time;
int maxPing;
if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port)
{
// empty or invalid slot
buf[0] = '\0';
*pingtime = 0;
return;
}
str = NET_AdrToStringwPort( cl_pinglist[n].adr );
Q_strncpyz( buf, str, buflen );
time = cl_pinglist[n].time;
if ( !time ) {
// check for timeout
time = Sys_Milliseconds() - cl_pinglist[n].start;
maxPing = Cvar_VariableIntegerValue( "cl_maxPing" );
if ( maxPing < 100 ) {
maxPing = 100;
}
if ( time < maxPing ) {
// not timed out yet
time = 0;
}
}
CL_SetServerInfoByAddress( cl_pinglist[n].adr, cl_pinglist[n].info, cl_pinglist[n].time );
*pingtime = time;
}
/*
==================
CL_GetPingInfo
==================
*/
void CL_GetPingInfo( int n, char *buf, int buflen ) {
if ( n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port ) {
// empty or invalid slot
if ( buflen ) {
buf[0] = '\0';
}
return;
}
Q_strncpyz( buf, cl_pinglist[n].info, buflen );
}
/*
==================
CL_ClearPing
==================
*/
void CL_ClearPing( int n ) {
if ( n < 0 || n >= MAX_PINGREQUESTS ) {
return;
}
cl_pinglist[n].adr.port = 0;
}
/*
==================
CL_GetPingQueueCount
==================
*/
int CL_GetPingQueueCount( void ) {
int i;
int count;
ping_t* pingptr;
count = 0;
pingptr = cl_pinglist;
for ( i = 0; i < MAX_PINGREQUESTS; i++, pingptr++ ) {
if ( pingptr->adr.port ) {
count++;
}
}
return ( count );
}
/*
==================
CL_GetFreePing
==================
*/
ping_t* CL_GetFreePing( void ) {
ping_t* pingptr;
ping_t* best;
int oldest;
int i;
int time;
pingptr = cl_pinglist;
for ( i = 0; i < MAX_PINGREQUESTS; i++, pingptr++ )
{
// find free ping slot
if ( pingptr->adr.port ) {
if ( !pingptr->time ) {
if (Sys_Milliseconds() - pingptr->start < 500)
{
// still waiting for response
continue;
}
} else if ( pingptr->time < 500 ) {
// results have not been queried
continue;
}
}
// clear it
pingptr->adr.port = 0;
return ( pingptr );
}
// use oldest entry
pingptr = cl_pinglist;
best = cl_pinglist;
oldest = INT_MIN;
for ( i = 0; i < MAX_PINGREQUESTS; i++, pingptr++ )
{
// scan for oldest
time = Sys_Milliseconds() - pingptr->start;
if ( time > oldest ) {
oldest = time;
best = pingptr;
}
}
return ( best );
}
/*
==================
CL_Ping_f
==================
*/
void CL_Ping_f( void ) {
netadr_t to;
ping_t* pingptr;
char* server;
int argc;
netadrtype_t family = NA_UNSPEC;
argc = Cmd_Argc();
if ( argc != 2 && argc != 3 ) {
Com_Printf( "usage: ping [-4|-6] server\n");
return;
}
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
Com_Memset( &to, 0, sizeof( netadr_t ) );
if ( !NET_StringToAdr( server, &to, family ) ) {
return;
}
pingptr = CL_GetFreePing();
memcpy( &pingptr->adr, &to, sizeof( netadr_t ) );
pingptr->start = Sys_Milliseconds();
pingptr->time = 0;
CL_SetServerInfoByAddress( pingptr->adr, NULL, 0 );
NET_OutOfBandPrint( NS_CLIENT, to, "getinfo xxx" );
}
/*
==================
CL_UpdateVisiblePings_f
==================
*/
qboolean CL_UpdateVisiblePings_f( int source ) {
int slots, i;
char buff[MAX_STRING_CHARS];
int pingTime;
int max;
qboolean status = qfalse;
if ( source < 0 || source > AS_FAVORITES ) {
return qfalse;
}
cls.pingUpdateSource = source;
slots = CL_GetPingQueueCount();
if ( slots < MAX_PINGREQUESTS ) {
serverInfo_t *server = NULL;
switch ( source ) {
case AS_LOCAL:
server = &cls.localServers[0];
max = cls.numlocalservers;
break;
case AS_GLOBAL:
server = &cls.globalServers[0];
max = cls.numglobalservers;
break;
case AS_FAVORITES:
server = &cls.favoriteServers[0];
max = cls.numfavoriteservers;
break;
default:
return qfalse;
}
for ( i = 0; i < max; i++ ) {
if ( server[i].visible ) {
if ( server[i].ping == -1 ) {
int j;
if ( slots >= MAX_PINGREQUESTS ) {
break;
}
for ( j = 0; j < MAX_PINGREQUESTS; j++ ) {
if ( !cl_pinglist[j].adr.port ) {
continue;
}
if ( NET_CompareAdr( cl_pinglist[j].adr, server[i].adr ) ) {
// already on the list
break;
}
}
if ( j >= MAX_PINGREQUESTS ) {
status = qtrue;
for ( j = 0; j < MAX_PINGREQUESTS; j++ ) {
if ( !cl_pinglist[j].adr.port ) {
break;
}
}
memcpy( &cl_pinglist[j].adr, &server[i].adr, sizeof( netadr_t ) );
cl_pinglist[j].start = Sys_Milliseconds();
cl_pinglist[j].time = 0;
NET_OutOfBandPrint( NS_CLIENT, cl_pinglist[j].adr, "getinfo xxx" );
slots++;
}
}
// if the server has a ping higher than cl_maxPing or
// the ping packet got lost
else if ( server[i].ping == 0 ) {
// if we are updating global servers
if ( source == AS_GLOBAL ) {
//
if ( cls.numGlobalServerAddresses > 0 ) {
// overwrite this server with one from the additional global servers
cls.numGlobalServerAddresses--;
CL_InitServerInfo( &server[i], &cls.globalServerAddresses[cls.numGlobalServerAddresses] );
// NOTE: the server[i].visible flag stays untouched
}
}
}
}
}
}
if ( slots ) {
status = qtrue;
}
for ( i = 0; i < MAX_PINGREQUESTS; i++ ) {
if ( !cl_pinglist[i].adr.port ) {
continue;
}
CL_GetPing( i, buff, MAX_STRING_CHARS, &pingTime );
if ( pingTime != 0 ) {
CL_ClearPing( i );
status = qtrue;
}
}
return status;
}
/*
==================
CL_ServerStatus_f
==================
*/
void CL_ServerStatus_f( void ) {
netadr_t to, *toptr = NULL;
char *server;
serverStatus_t *serverStatus;
int argc;
netadrtype_t family = NA_UNSPEC;
argc = Cmd_Argc();
if ( argc != 2 && argc != 3 )
{
if (clc.state != CA_ACTIVE || clc.demoplaying)
{
Com_Printf( "Not connected to a server.\n" );
Com_Printf( "usage: serverstatus [-4|-6] server\n");
return;
}
toptr = &clc.serverAddress;
}
if(!toptr)
{
Com_Memset( &to, 0, sizeof(netadr_t) );
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
toptr = &to;
if ( !NET_StringToAdr( server, toptr, family ) )
return;
}
NET_OutOfBandPrint( NS_CLIENT, *toptr, "getstatus" );
serverStatus = CL_GetServerStatus( *toptr );
serverStatus->address = *toptr;
serverStatus->print = qtrue;
serverStatus->pending = qtrue;
}
/*
==================
CL_ShowIP_f
==================
*/
void CL_ShowIP_f( void ) {
Sys_ShowIP();
}
/*
=================
CL_CDKeyValidate
=================
*/
qboolean CL_CDKeyValidate( const char *key, const char *checksum ) {
#ifdef STANDALONE
return qtrue;
#else
char ch;
byte sum;
char chs[3];
int i, len;
len = strlen( key );
if ( len != CDKEY_LEN ) {
return qfalse;
}
if ( checksum && strlen( checksum ) != CDCHKSUM_LEN ) {
return qfalse;
}
sum = 0;
// for loop gets rid of conditional assignment warning
for ( i = 0; i < len; i++ ) {
ch = *key++;
if ( ch >= 'a' && ch <= 'z' ) {
ch -= 32;
}
switch ( ch ) {
case '2':
case '3':
case '7':
case 'A':
case 'B':
case 'C':
case 'D':
case 'G':
case 'H':
case 'J':
case 'L':
case 'P':
case 'R':
case 'S':
case 'T':
case 'W':
sum += ch;
continue;
default:
return qfalse;
}
}
sprintf( chs, "%02x", sum );
if ( checksum && !Q_stricmp( chs, checksum ) ) {
return qtrue;
}
if ( !checksum ) {
return qtrue;
}
return qfalse;
#endif
}
// NERVE - SMF
/*
=======================
CL_AddToLimboChat
=======================
*/
void CL_AddToLimboChat( const char *str ) {
int len = 0;
char *p;
int i;
cl.limboChatPos = LIMBOCHAT_HEIGHT - 1;
// copy old strings
for ( i = cl.limboChatPos; i > 0; i-- ) {
strcpy( cl.limboChatMsgs[i], cl.limboChatMsgs[i - 1] );
}
// copy new string
p = cl.limboChatMsgs[0];
*p = 0;
while ( *str ) {
if ( len > LIMBOCHAT_WIDTH - 1 ) {
break;
}
if ( Q_IsColorString( str ) ) {
*p++ = *str++;
*p++ = *str++;
continue;
}
*p++ = *str++;
len++;
}
*p = 0;
}
/*
=======================
CL_GetLimboString
=======================
*/
qboolean CL_GetLimboString( int index, char *buf ) {
if ( index >= LIMBOCHAT_HEIGHT ) {
return qfalse;
}
strncpy( buf, cl.limboChatMsgs[index], 140 );
return qtrue;
}
// -NERVE - SMF
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3233_3 |
crossvul-cpp_data_bad_3233_1 | /*
===========================================================================
Return to Castle Wolfenstein multiplayer GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (RTCW MP Source Code).
RTCW MP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW MP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW MP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
/*****************************************************************************
* name: files.c
*
* desc: handle based filesystem for Quake III Arena
*
*
*****************************************************************************/
#include "q_shared.h"
#include "qcommon.h"
#include "../zlib-1.2.8/unzip.h"
/*
=============================================================================
QUAKE3 FILESYSTEM
All of Quake's data access is through a hierarchical file system, but the contents of
the file system can be transparently merged from several sources.
A "qpath" is a reference to game file data. MAX_ZPATH is 256 characters, which must include
a terminating zero. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any
references outside the quake directory system.
The "base path" is the path to the directory holding all the game directories and usually
the executable. It defaults to ".", but can be overridden with a "+set fs_basepath c:\quake3"
command line to allow code debugging in a different directory. Basepath cannot
be modified at all after startup. Any files that are created (demos, screenshots,
etc) will be created relative to the base path, so base path should usually be writable.
The "home path" is the path used for all write access. On win32 systems we have "base path"
== "home path", but on *nix systems the base installation is usually readonly, and
"home path" points to ~/.q3a or similar
The user can also install custom mods and content in "home path", so it should be searched
along with "home path" and "cd path" for game content.
The "base game" is the directory under the paths where data comes from by default, and
can be either "baseq3" or "demoq3".
The "current game" may be the same as the base game, or it may be the name of another
directory under the paths that should be searched for files before looking in the base game.
This is the basis for addons.
Clients automatically set the game directory after receiving a gamestate from a server,
so only servers need to worry about +set fs_game.
No other directories outside of the base game and current game will ever be referenced by
filesystem functions.
To save disk space and speed loading, directory trees can be collapsed into zip files.
The files use a ".pk3" extension to prevent users from unzipping them accidentally, but
otherwise the are simply normal uncompressed zip files. A game directory can have multiple
zip files of the form "pak0.pk3", "pak1.pk3", etc. Zip files are searched in decending order
from the highest number to the lowest, and will always take precedence over the filesystem.
This allows a pk3 distributed as a patch to override all existing data.
Because we will have updated executables freely available online, there is no point to
trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
should be exactly the same executables as release versions, but with different data that
automatically restricts where game media can come from to prevent add-ons from working.
File search order: when FS_FOpenFileRead gets called it will go through the fs_searchpaths
structure and stop on the first successful hit. fs_searchpaths is built with successive
calls to FS_AddGameDirectory
Additionaly, we search in several subdirectories:
current game is the current mode
base game is a variable to allow mods based on other mods
(such as baseq3 + missionpack content combination in a mod for instance)
BASEGAME is the hardcoded base game ("baseq3")
e.g. the qpath "sound/newstuff/test.wav" would be searched for in the following places:
home path + current game's zip files
home path + current game's directory
base path + current game's zip files
base path + current game's directory
cd path + current game's zip files
cd path + current game's directory
home path + base game's zip file
home path + base game's directory
base path + base game's zip file
base path + base game's directory
cd path + base game's zip file
cd path + base game's directory
home path + BASEGAME's zip file
home path + BASEGAME's directory
base path + BASEGAME's zip file
base path + BASEGAME's directory
cd path + BASEGAME's zip file
cd path + BASEGAME's directory
server download, to be written to home path + current game's directory
The filesystem can be safely shutdown and reinitialized with different
basedir / cddir / game combinations, but all other subsystems that rely on it
(sound, video) must also be forced to restart.
Because the same files are loaded by both the clip model (CM_) and renderer (TR_)
subsystems, a simple single-file caching scheme is used. The CM_ subsystems will
load the file with a request to cache. Only one file will be kept cached at a time,
so any models that are going to be referenced by both subsystems should alternate
between the CM_ load function and the ref load function.
TODO: A qpath that starts with a leading slash will always refer to the base game, even if another
game is currently active. This allows character models, skins, and sounds to be downloaded
to a common directory no matter which game is active.
How to prevent downloading zip files?
Pass pk3 file names in systeminfo, and download before FS_Restart()?
Aborting a download disconnects the client from the server.
How to mark files as downloadable? Commercial add-ons won't be downloadable.
Non-commercial downloads will want to download the entire zip file.
the game would have to be reset to actually read the zip in
Auto-update information
Path separators
Casing
separate server gamedir and client gamedir, so if the user starts
a local game after having connected to a network game, it won't stick
with the network game.
allow menu options for game selection?
Read / write config to floppy option.
Different version coexistance?
When building a pak file, make sure a wolfconfig.cfg isn't present in it,
or configs will never get loaded from disk!
todo:
downloading (outside fs?)
game directory passing and restarting
=============================================================================
*/
// TTimo: moved to qcommon.h
// NOTE: could really do with a cvar
//#define BASEGAME "main"
//#define DEMOGAME "demomain"
// every time a new demo pk3 file is built, this checksum must be updated.
// the easiest way to get it is to just run the game and see what it spits out
//DHM - Nerve :: Wolf Multiplayer demo checksum
// NOTE TTimo: always needs the 'u' for unsigned int (gcc)
#define DEMO_PAK0_CHECKSUM 2031778175u
static const unsigned int pak_checksums[] = {
1886207346u
};
static const unsigned int mppak_checksums[] = {
764840216u,
-1023558518u,
125907563u,
131270674u,
-137448799u,
2149774797u
};
#define MAX_ZPATH 256
#define MAX_SEARCH_PATHS 4096
#define MAX_FILEHASH_SIZE 1024
typedef struct fileInPack_s {
char *name; // name of the file
unsigned long pos; // file info position in zip
unsigned long len; // uncompress file size
struct fileInPack_s* next; // next file in the hash
} fileInPack_t;
typedef struct {
char pakPathname[MAX_OSPATH]; // c:\quake3\baseq3
char pakFilename[MAX_OSPATH]; // c:\quake3\baseq3\pak0.pk3
char pakBasename[MAX_OSPATH]; // pak0
char pakGamename[MAX_OSPATH]; // baseq3
unzFile handle; // handle to zip file
int checksum; // regular checksum
int pure_checksum; // checksum for pure
int numfiles; // number of files in pk3
int referenced; // referenced file flags
int hashSize; // hash table size (power of 2)
fileInPack_t* *hashTable; // hash table
fileInPack_t* buildBuffer; // buffer with the filenames etc.
} pack_t;
typedef struct {
char path[MAX_OSPATH]; // c:\quake3
char fullpath[MAX_OSPATH]; // c:\quake3\baseq3
char gamedir[MAX_OSPATH]; // baseq3
qboolean allowUnzippedDLLs; // whether to load unzipped dlls from directory
} directory_t;
typedef struct searchpath_s {
struct searchpath_s *next;
pack_t *pack; // only one of pack / dir will be non NULL
directory_t *dir;
} searchpath_t;
static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators
static cvar_t *fs_debug;
static cvar_t *fs_homepath;
#ifdef __APPLE__
// Also search the .app bundle for .pk3 files
static cvar_t *fs_apppath;
#endif
#ifndef STANDALONE
static cvar_t *fs_steampath;
#endif
static cvar_t *fs_basepath;
static cvar_t *fs_basegame;
static cvar_t *fs_gamedirvar;
static searchpath_t *fs_searchpaths;
static int fs_readCount; // total bytes read
static int fs_loadCount; // total files read
static int fs_loadStack; // total files in memory
static int fs_packFiles = 0; // total number of files in packs
static int fs_checksumFeed;
typedef union qfile_gus {
FILE* o;
unzFile z;
} qfile_gut;
typedef struct qfile_us {
qfile_gut file;
qboolean unique;
} qfile_ut;
typedef struct {
qfile_ut handleFiles;
qboolean handleSync;
int fileSize;
int zipFilePos;
int zipFileLen;
qboolean zipFile;
qboolean streamed;
char name[MAX_ZPATH];
} fileHandleData_t;
static fileHandleData_t fsh[MAX_FILE_HANDLES];
// TTimo - show_bug.cgi?id=540
// wether we did a reorder on the current search path when joining the server
static qboolean fs_reordered;
// never load anything from pk3 files that are not present at the server when pure
// ex: when fs_numServerPaks != 0, FS_FOpenFileRead won't load anything outside of pk3 except .cfg .menu .game .dat
static int fs_numServerPaks = 0;
static int fs_serverPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverPakNames[MAX_SEARCH_PATHS]; // pk3 names
// only used for autodownload, to make sure the client has at least
// all the pk3 files that are referenced at the server side
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS]; // pk3 names
// last valid game folder used
char lastValidBase[MAX_OSPATH];
char lastValidComBaseGame[MAX_OSPATH];
char lastValidFsBaseGame[MAX_OSPATH];
char lastValidGame[MAX_OSPATH];
#ifdef FS_MISSING
FILE* missingFiles = NULL;
#endif
/* C99 defines __func__ */
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2 || _MSC_VER >= 1300
# define __func__ __FUNCTION__
# else
# define __func__ "(unknown)"
# endif
#endif
/*
==============
FS_Initialized
==============
*/
qboolean FS_Initialized( void ) {
return ( fs_searchpaths != NULL );
}
/*
=================
FS_PakIsPure
=================
*/
qboolean FS_PakIsPure( pack_t *pack ) {
int i;
if ( fs_numServerPaks ) {
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
// FIXME: also use hashed file names
// NOTE TTimo: a pk3 with same checksum but different name would be validated too
// I don't see this as allowing for any exploit, it would only happen if the client does manips of its file names 'not a bug'
if ( pack->checksum == fs_serverPaks[i] ) {
return qtrue; // on the approved list
}
}
return qfalse; // not on the pure server pak list
}
return qtrue;
}
/*
=================
FS_LoadStack
return load stack
=================
*/
int FS_LoadStack( void ) {
return fs_loadStack;
}
/*
================
return a hash value for the filename
================
*/
static long FS_HashFileName( const char *fname, int hashSize ) {
int i;
long hash;
char letter;
hash = 0;
i = 0;
while ( fname[i] != '\0' ) {
letter = tolower( fname[i] );
if ( letter == '.' ) {
break; // don't include extension
}
if ( letter == '\\' ) {
letter = '/'; // damn path names
}
if ( letter == PATH_SEP ) {
letter = '/'; // damn path names
}
hash += (long)( letter ) * ( i + 119 );
i++;
}
hash = ( hash ^ ( hash >> 10 ) ^ ( hash >> 20 ) );
hash &= ( hashSize - 1 );
return hash;
}
static fileHandle_t FS_HandleForFile( void ) {
int i;
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o == NULL ) {
return i;
}
}
Com_Error( ERR_DROP, "FS_HandleForFile: none free" );
return 0;
}
static FILE *FS_FileForHandle( fileHandle_t f ) {
if ( f < 1 || f >= MAX_FILE_HANDLES ) {
Com_Error( ERR_DROP, "FS_FileForHandle: out of range" );
}
if ( fsh[f].zipFile == qtrue ) {
Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" );
}
if ( !fsh[f].handleFiles.file.o ) {
Com_Error( ERR_DROP, "FS_FileForHandle: NULL" );
}
return fsh[f].handleFiles.file.o;
}
void FS_ForceFlush( fileHandle_t f ) {
FILE *file;
file = FS_FileForHandle( f );
setvbuf( file, NULL, _IONBF, 0 );
}
/*
================
FS_fplength
================
*/
long FS_fplength(FILE *h)
{
long pos;
long end;
pos = ftell(h);
fseek(h, 0, SEEK_END);
end = ftell(h);
fseek(h, pos, SEEK_SET);
return end;
}
/*
================
FS_filelength
If this is called on a non-unique FILE (from a pak file),
it will return the size of the pak file, not the expected
size of the file.
================
*/
long FS_filelength(fileHandle_t f)
{
FILE *h;
h = FS_FileForHandle(f);
if(h == NULL)
return -1;
else
return FS_fplength(h);
}
/*
====================
FS_ReplaceSeparators
Fix things up differently for win/unix/mac
====================
*/
static void FS_ReplaceSeparators( char *path ) {
char *s;
qboolean lastCharWasSep = qfalse;
for ( s = path ; *s ; s++ ) {
if ( *s == '/' || *s == '\\' ) {
if ( !lastCharWasSep ) {
*s = PATH_SEP;
lastCharWasSep = qtrue;
} else {
memmove (s, s + 1, strlen (s));
}
} else {
lastCharWasSep = qfalse;
}
}
}
/*
===================
FS_BuildOSPath
Qpath may have either forward or backwards slashes
===================
*/
char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) {
char temp[MAX_OSPATH];
static char ospath[2][MAX_OSPATH];
static int toggle;
toggle ^= 1; // flip-flop to allow two returns without clash
if ( !game || !game[0] ) {
game = fs_gamedir;
}
Com_sprintf( temp, sizeof( temp ), "/%s/%s", game, qpath );
FS_ReplaceSeparators( temp );
Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp );
return ospath[toggle];
}
/*
============
FS_CreatePath
Creates any directories needed to store the given filename
============
*/
qboolean FS_CreatePath( char *OSPath ) {
char *ofs;
char path[MAX_OSPATH];
// make absolutely sure that it can't back up the path
// FIXME: is c: allowed???
if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) {
Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath );
return qtrue;
}
Q_strncpyz( path, OSPath, sizeof( path ) );
FS_ReplaceSeparators( path );
// Skip creation of the root directory as it will always be there
ofs = strchr( path, PATH_SEP );
if ( ofs != NULL ) {
ofs++;
}
for (; ofs != NULL && *ofs ; ofs++) {
if (*ofs == PATH_SEP) {
// create the directory
*ofs = 0;
if (!Sys_Mkdir (path)) {
Com_Error( ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"",
path );
}
*ofs = PATH_SEP;
}
}
return qfalse;
}
/*
=================
FS_CheckFilenameIsMutable
ERR_FATAL if trying to maniuplate a file with the platform library, QVM, or pk3 extension
=================
*/
static void FS_CheckFilenameIsMutable( const char *filename,
const char *function )
{
// Check if the filename ends with the library, QVM, or pk3 extension
if( COM_CompareExtension( filename, DLL_EXT )
|| COM_CompareExtension( filename, ".qvm" )
|| COM_CompareExtension( filename, ".pk3" ) )
{
Com_Error( ERR_FATAL, "%s: Not allowed to manipulate '%s' due "
"to %s extension", function, filename, COM_GetExtension( filename ) );
}
}
/*
===========
FS_Remove
===========
*/
void FS_Remove( const char *osPath ) {
FS_CheckFilenameIsMutable( osPath, __func__ );
remove( osPath );
}
/*
===========
FS_HomeRemove
===========
*/
void FS_HomeRemove( const char *homePath ) {
FS_CheckFilenameIsMutable( homePath, __func__ );
remove( FS_BuildOSPath( fs_homepath->string,
fs_gamedir, homePath ) );
}
/*
================
FS_FileInPathExists
Tests if path and file exists
================
*/
qboolean FS_FileInPathExists(const char *testpath)
{
FILE *filep;
filep = Sys_FOpen(testpath, "rb");
if(filep)
{
fclose(filep);
return qtrue;
}
return qfalse;
}
/*
================
FS_FileExists
Tests if the file exists in the current gamedir, this DOES NOT
search the paths. This is to determine if opening a file to write
(which always goes into the current gamedir) will cause any overwrites.
NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards
================
*/
qboolean FS_FileExists(const char *file)
{
return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file));
}
/*
================
FS_SV_FileExists
Tests if the file exists
================
*/
qboolean FS_SV_FileExists( const char *file )
{
char *testpath;
testpath = FS_BuildOSPath( fs_homepath->string, file, "");
testpath[strlen(testpath)-1] = '\0';
return FS_FileInPathExists(testpath);
}
/*
===========
FS_SV_FOpenFileWrite
===========
*/
fileHandle_t FS_SV_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileWrite: %s\n", ospath );
}
// FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_SV_FOpenFileRead
Search for a file somewhere below the home path then base path
in that order
===========
*/
long FS_SV_FOpenFileRead( const char *filename, fileHandle_t *fp ) {
char *ospath;
fileHandle_t f = 0;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
// S_ClearSoundBuffer();
// search homepath
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
// remove trailing slash
ospath[strlen( ospath ) - 1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o)
{
// If fs_homepath == fs_basepath, don't bother
if (Q_stricmp(fs_homepath->string,fs_basepath->string))
{
// search basepath
ospath = FS_BuildOSPath( fs_basepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
#ifndef STANDALONE
// Check fs_steampath too
if (!fsh[f].handleFiles.file.o && fs_steampath->string[0])
{
ospath = FS_BuildOSPath( fs_steampath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_steampath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
#endif
if ( !fsh[f].handleFiles.file.o )
{
f = 0;
}
}
*fp = f;
if ( f ) {
return FS_filelength( f );
}
return -1;
}
/*
===========
FS_SV_Rename
===========
*/
void FS_SV_Rename( const char *from, const char *to, qboolean safe ) {
char *from_ospath, *to_ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
// don't let sound stutter
// S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, from, "" );
to_ospath = FS_BuildOSPath( fs_homepath->string, to, "" );
from_ospath[strlen( from_ospath ) - 1] = '\0';
to_ospath[strlen( to_ospath ) - 1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath );
}
if ( safe ) {
FS_CheckFilenameIsMutable( to_ospath, __func__ );
}
rename(from_ospath, to_ospath);
}
/*
===========
FS_Rename
===========
*/
void FS_Rename( const char *from, const char *to ) {
char *from_ospath, *to_ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
// don't let sound stutter
// S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from );
to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to );
if ( fs_debug->integer ) {
Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath );
}
FS_CheckFilenameIsMutable( to_ospath, __func__ );
rename(from_ospath, to_ospath);
}
/*
==============
FS_FCloseFile
If the FILE pointer is an open pak file, leave it open.
For some reason, other dll's can't just cal fclose()
on files returned by FS_FOpenFile...
==============
*/
void FS_FCloseFile( fileHandle_t f ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( fsh[f].zipFile == qtrue ) {
unzCloseCurrentFile( fsh[f].handleFiles.file.z );
if ( fsh[f].handleFiles.unique ) {
unzClose( fsh[f].handleFiles.file.z );
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
return;
}
// we didn't find it as a pak, so close it as a unique file
if ( fsh[f].handleFiles.file.o ) {
fclose( fsh[f].handleFiles.file.o );
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
}
/*
===========
FS_FOpenFileWrite
===========
*/
fileHandle_t FS_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileWrite: %s\n", ospath );
}
// FS_CheckFilenameIsMutable( ospath, __func__ );
if ( FS_CreatePath( ospath ) ) {
return 0;
}
// enabling the following line causes a recursive function call loop
// when running with +set logfile 1 +set developer 1
//Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if ( !fsh[f].handleFiles.file.o ) {
f = 0;
}
return f;
}
/*
===========
FS_FOpenFileAppend
===========
*/
fileHandle_t FS_FOpenFileAppend( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
// S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileAppend: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if ( FS_CreatePath( ospath ) ) {
return 0;
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "ab" );
fsh[f].handleSync = qfalse;
if ( !fsh[f].handleFiles.file.o ) {
f = 0;
}
return f;
}
/*
===========
FS_FCreateOpenPipeFile
===========
*/
fileHandle_t FS_FCreateOpenPipeFile( const char *filename ) {
char *ospath;
FILE *fifo;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
// S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FCreateOpenPipeFile: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
fifo = Sys_Mkfifo( ospath );
if( fifo ) {
fsh[f].handleFiles.file.o = fifo;
fsh[f].handleSync = qfalse;
}
else
{
Com_Printf( S_COLOR_YELLOW "WARNING: Could not create new com_pipefile at %s. "
"com_pipefile will not be used.\n", ospath );
f = 0;
}
return f;
}
/*
===========
FS_FilenameCompare
Ignore case and seprator char distinctions
===========
*/
qboolean FS_FilenameCompare( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if ( c1 >= 'a' && c1 <= 'z' ) {
c1 -= ( 'a' - 'A' );
}
if ( c2 >= 'a' && c2 <= 'z' ) {
c2 -= ( 'a' - 'A' );
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if ( c1 != c2 ) {
return qtrue; // strings not equal
}
} while ( c1 );
return qfalse; // strings are equal
}
/*
===========
FS_IsExt
Return qtrue if ext matches file extension filename
===========
*/
qboolean FS_IsExt(const char *filename, const char *ext, int namelen)
{
int extlen;
extlen = strlen(ext);
if(extlen > namelen)
return qfalse;
filename += namelen - extlen;
return !Q_stricmp(filename, ext);
}
/*
===========
FS_IsDemoExt
Return qtrue if filename has a demo extension
===========
*/
qboolean FS_IsDemoExt(const char *filename, int namelen)
{
char *ext_test;
int index, protocol;
ext_test = strrchr(filename, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMOEXT, ARRAY_LEN(DEMOEXT) - 1))
{
protocol = atoi(ext_test + ARRAY_LEN(DEMOEXT));
if(protocol == com_protocol->integer)
return qtrue;
#ifdef LEGACY_PROTOCOL
if(protocol == com_legacyprotocol->integer)
return qtrue;
#endif
for(index = 0; demo_protocols[index]; index++)
{
if(demo_protocols[index] == protocol)
return qtrue;
}
}
return qfalse;
}
/*
===========
FS_ShiftedStrStr
===========
*/
char *FS_ShiftedStrStr( const char *string, const char *substring, int shift ) {
char buf[MAX_STRING_TOKENS];
int i;
for ( i = 0; substring[i]; i++ ) {
buf[i] = substring[i] + shift;
}
buf[i] = '\0';
return strstr( string, buf );
}
/*
==========
FS_ShiftStr
perform simple string shifting to avoid scanning from the exe
==========
*/
char *FS_ShiftStr( const char *string, int shift ) {
static char buf[MAX_STRING_CHARS];
int i,l;
l = strlen( string );
for ( i = 0; i < l; i++ ) {
buf[i] = string[i] + shift;
}
buf[i] = '\0';
return buf;
}
/*
===========
FS_FOpenFileReadDir
Tries opening file "filename" in searchpath "search"
Returns filesize and an open FILE pointer.
===========
*/
extern qboolean com_fullyInitialized;
// see FS_FOpenFileRead_Filtered
static int fs_filter_flag = 0;
long FS_FOpenFileReadDir(const char *filename, searchpath_t *search, fileHandle_t *file, qboolean uniqueFILE, qboolean unpure)
{
long hash;
pack_t *pak;
fileInPack_t *pakFile;
directory_t *dir;
char *netpath;
FILE *filep;
int len;
if(filename == NULL)
Com_Error(ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed");
// qpaths are not supposed to have a leading slash
if(filename[0] == '/' || filename[0] == '\\')
filename++;
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if(strstr(filename, ".." ) || strstr(filename, "::"))
{
if(file == NULL)
return qfalse;
*file = 0;
return -1;
}
// make sure the rtcwkey file is only readable by the WolfMP.exe at initialization
// any other time the key should only be accessed in memory using the provided functions
if(com_fullyInitialized && strstr(filename, "rtcwkey"))
{
if(file == NULL)
return qfalse;
*file = 0;
return -1;
}
if(file == NULL)
{
// just wants to see if file is there
// is the element a pak file?
if(search->pack)
{
hash = FS_HashFileName(filename, search->pack->hashSize);
if(search->pack->hashTable[hash] && !(fs_filter_flag & FS_EXCLUDE_PK3))
{
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do
{
// case and separator insensitive comparisons
if(!FS_FilenameCompare(pakFile->name, filename))
{
// found it!
if(pakFile->len)
return pakFile->len;
else
{
// It's not nice, but legacy code depends
// on positive value if file exists no matter
// what size
return 1;
}
}
pakFile = pakFile->next;
} while(pakFile != NULL);
}
}
else if(search->dir && !(fs_filter_flag & FS_EXCLUDE_DIR))
{
dir = search->dir;
netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
filep = Sys_FOpen(netpath, "rb");
if(filep)
{
len = FS_fplength(filep);
fclose(filep);
if(len)
return len;
else
return 1;
}
}
return 0;
}
*file = FS_HandleForFile();
fsh[*file].handleFiles.unique = uniqueFILE;
// is the element a pak file?
if(search->pack)
{
hash = FS_HashFileName(filename, search->pack->hashSize);
if(search->pack->hashTable[hash] && !(fs_filter_flag & FS_EXCLUDE_PK3))
{
// disregard if it doesn't match one of the allowed pure pak files
if(!unpure && !FS_PakIsPure(search->pack))
{
*file = 0;
return -1;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do
{
// case and separator insensitive comparisons
if(!FS_FilenameCompare(pakFile->name, filename))
{
// found it!
// Mark the pak as having been referenced and mark specifics on cgame and ui.
// Shaders, txt, and arena files by themselves do not count as a reference as
// these are loaded from all pk3s
len = strlen(filename);
if (!(pak->referenced & FS_GENERAL_REF))
{
if(!FS_IsExt(filename, ".shader", len) &&
!FS_IsExt(filename, ".txt", len) &&
!FS_IsExt(filename, ".cfg", len) &&
!FS_IsExt(filename, ".config", len) &&
!FS_IsExt(filename, ".bot", len) &&
!FS_IsExt(filename, ".arena", len) &&
!FS_IsExt(filename, ".menu", len) &&
// Q_stricmp(filename, "vm/qagame.qvm") != 0 && // Commented out for now
!strstr(filename, "levelshots"))
{
pak->referenced |= FS_GENERAL_REF;
}
}
if(strstr(filename, Sys_GetDLLName( "cgame" )))
pak->referenced |= FS_CGAME_REF;
if(strstr(filename, Sys_GetDLLName( "ui" )))
pak->referenced |= FS_UI_REF;
if(strstr(filename, "cgame.mp.qvm"))
pak->referenced |= FS_CGAME_REF;
if(strstr(filename, "ui.mp.qvm"))
pak->referenced |= FS_UI_REF;
// DHM -- Nerve :: Don't allow singleplayer maps to be loaded from pak0
if ( Q_stricmp( filename + len - 4, ".bsp" ) == 0 &&
Q_stricmp( pak->pakBasename, "pak0" ) == 0 ) {
*file = 0;
return -1;
}
if(uniqueFILE)
{
// open a new file on the pakfile
fsh[*file].handleFiles.file.z = unzOpen(pak->pakFilename);
if(fsh[*file].handleFiles.file.z == NULL)
Com_Error(ERR_FATAL, "Couldn't open %s", pak->pakFilename);
}
else
fsh[*file].handleFiles.file.z = pak->handle;
Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
fsh[*file].zipFile = qtrue;
// set the file position in the zip file (also sets the current file info)
unzSetOffset(fsh[*file].handleFiles.file.z, pakFile->pos);
// open the file in the zip
unzOpenCurrentFile(fsh[*file].handleFiles.file.z);
fsh[*file].zipFilePos = pakFile->pos;
fsh[*file].zipFileLen = pakFile->len;
if(fs_debug->integer)
{
Com_Printf("FS_FOpenFileRead: %s (found in '%s')\n",
filename, pak->pakFilename);
}
return pakFile->len;
}
pakFile = pakFile->next;
} while(pakFile != NULL);
}
}
else if(search->dir && !(fs_filter_flag & FS_EXCLUDE_DIR))
{
// check a file in the directory tree
// if we are running restricted, the only files we
// will allow to come from the directory are .cfg files
len = strlen(filename);
// FIXME TTimo I'm not sure about the fs_numServerPaks test
// if you are using FS_ReadFile to find out if a file exists,
// this test can make the search fail although the file is in the directory
// I had the problem on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8
// turned out I used FS_FileExists instead
if(!unpure && fs_numServerPaks)
{
if(!FS_IsExt(filename, ".cfg", len) && // for config files
!FS_IsExt(filename, ".menu", len) && // menu files
!FS_IsExt(filename, ".game", len) && // menu files
!FS_IsExt(filename, ".dat", len) && // for journal files
!FS_IsDemoExt(filename, len)) // demos
{
*file = 0;
return -1;
}
}
dir = search->dir;
netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
filep = Sys_FOpen(netpath, "rb");
if (filep == NULL)
{
*file = 0;
return -1;
}
Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
fsh[*file].zipFile = qfalse;
if(fs_debug->integer)
{
Com_Printf("FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename,
dir->path, PATH_SEP, dir->gamedir);
}
fsh[*file].handleFiles.file.o = filep;
return FS_fplength(filep);
}
*file = 0;
return -1;
}
/*
===========
FS_FOpenFileRead
Finds the file in the search path.
Returns filesize and an open FILE pointer.
Used for streaming data out of either a
separate file or a ZIP file.
===========
*/
long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE)
{
searchpath_t *search;
long len;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
for(search = fs_searchpaths; search; search = search->next)
{
len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse);
if(file == NULL)
{
if(len > 0)
return len;
}
else
{
if(len >= 0 && *file)
return len;
}
}
#ifdef FS_MISSING
if(missingFiles)
fprintf(missingFiles, "%s\n", filename);
#endif
if(file)
{
*file = 0;
return -1;
}
else
{
// When file is NULL, we're querying the existance of the file
// If we've got here, it doesn't exist
return 0;
}
}
int FS_FOpenFileRead_Filtered( const char *qpath, fileHandle_t *file, qboolean uniqueFILE, int filter_flag ) {
int ret;
fs_filter_flag = filter_flag;
ret = FS_FOpenFileRead( qpath, file, uniqueFILE );
fs_filter_flag = 0;
return ret;
}
/*
=================
FS_FindVM
Find a suitable VM file in search path order.
In each searchpath try:
- open DLL file
- open QVM file if QVM loading enabled
write found DLL or QVM to "found" and return VMI_NATIVE if DLL, VMI_COMPILED if QVM
Return the searchpath in "startSearch".
=================
*/
int FS_FindVM(void **startSearch, char *found, int foundlen, const char *name, qboolean unpure, int enableQvm)
{
searchpath_t *search, *lastSearch;
directory_t *dir;
pack_t *pack;
char dllName[MAX_OSPATH], qvmName[MAX_OSPATH];
char *netpath;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
if(enableQvm)
Com_sprintf(qvmName, sizeof(qvmName), "vm/%s.mp.qvm", name);
Q_strncpyz(dllName, Sys_GetDLLName(name), sizeof(dllName));
lastSearch = *startSearch;
if(*startSearch == NULL)
search = fs_searchpaths;
else
search = lastSearch->next;
while(search)
{
if(search->dir && (unpure || !Q_stricmp(name, "qagame")))
{
dir = search->dir;
netpath = FS_BuildOSPath(dir->path, dir->gamedir, dllName);
if(enableQvm && FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, unpure) > 0)
{
*startSearch = search;
return VMI_COMPILED;
}
if(dir->allowUnzippedDLLs && FS_FileInPathExists(netpath))
{
Q_strncpyz(found, netpath, foundlen);
*startSearch = search;
return VMI_NATIVE;
}
}
else if(search->pack)
{
pack = search->pack;
if(lastSearch && lastSearch->pack)
{
// make sure we only try loading one VM file per game dir
// i.e. if VM from pak7.pk3 fails we won't try one from pak6.pk3
if(!FS_FilenameCompare(lastSearch->pack->pakPathname, pack->pakPathname))
{
search = search->next;
continue;
}
}
if(enableQvm && FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, unpure) > 0)
{
*startSearch = search;
return VMI_COMPILED;
}
#ifndef DEDICATED
// extract the dlls from the mp_bin.pk3 so
// that they can be referenced
if (Q_stricmp(name, "qagame"))
{
netpath = FS_BuildOSPath(fs_homepath->string, pack->pakGamename, dllName);
if (FS_FOpenFileReadDir(dllName, search, NULL, qfalse, unpure) > 0
&& FS_CL_ExtractFromPakFile(search, netpath, dllName, NULL))
{
Com_Printf( "Loading %s dll from %s\n", name, pack->pakFilename );
Q_strncpyz(found, netpath, foundlen);
*startSearch = search;
return VMI_NATIVE;
}
}
#endif
}
search = search->next;
}
return -1;
}
// TTimo
// relevant to client only
#if !defined( DEDICATED )
/*
==================
FS_CL_ExtractFromPakFile
NERVE - SMF - Extracts the latest file from a pak file.
Compares packed file against extracted file. If no differences, does not copy.
This is necessary for exe/dlls which may or may not be locked.
NOTE TTimo:
fullpath gives the full OS path to the dll that will potentially be loaded
on win32 it's always in fs_basepath/<fs_game>/
on linux it can be in fs_homepath/<fs_game>/ or fs_basepath/<fs_game>/
the dll is extracted to fs_homepath (== fs_basepath on win32) if needed
the return value doesn't tell wether file was extracted or not, it just says wether it's ok to continue
(i.e. either the right file was extracted successfully, or it was already present)
cvar_lastVersion is the optional name of a CVAR_ARCHIVE used to store the wolf version for the last extracted .so
show_bug.cgi?id=463
==================
*/
qboolean FS_CL_ExtractFromPakFile( void *searchpath, const char *fullpath, const char *filename, const char *cvar_lastVersion ) {
int srcLength;
int destLength;
unsigned char *srcData;
unsigned char *destData;
qboolean needToCopy;
FILE *destHandle;
int read;
needToCopy = qtrue;
// read in compressed file
srcLength = FS_ReadFileDir(filename, searchpath, qfalse, (void **)&srcData);
// if its not in the pak, we bail
if ( srcLength == -1 ) {
return qfalse;
}
// read in local file
destHandle = Sys_FOpen( fullpath, "rb" );
// if we have a local file, we need to compare the two
if ( destHandle ) {
fseek( destHandle, 0, SEEK_END );
destLength = ftell( destHandle );
fseek( destHandle, 0, SEEK_SET );
if ( destLength > 0 ) {
destData = (unsigned char*)Z_Malloc( destLength );
read = fread( destData, 1, destLength, destHandle );
if (read == 0) {
Com_Error (ERR_FATAL, "FS_CL_ExtractFromPakFile: 0 bytes read");
}
// compare files
if ( destLength == srcLength ) {
int i;
for ( i = 0; i < destLength; i++ ) {
if ( destData[i] != srcData[i] ) {
break;
}
}
if ( i == destLength ) {
needToCopy = qfalse;
}
}
Z_Free( destData ); // TTimo
}
fclose( destHandle );
}
// write file
if ( needToCopy ) {
fileHandle_t f;
Com_DPrintf("FS_ExtractFromPakFile: FS_FOpenFileWrite '%s'\n", filename);
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf( "Failed to open %s\n", filename );
return qfalse;
}
FS_Write( srcData, srcLength, f );
FS_FCloseFile( f );
#ifdef __linux__
// show_bug.cgi?id=463
// need to keep track of what versions we extract
if ( cvar_lastVersion ) {
Cvar_Set( cvar_lastVersion, Cvar_VariableString( "version" ) );
}
#endif
}
FS_FreeFile( srcData );
return qtrue;
}
#endif
/*
==============
FS_Delete
TTimo - this was not in the 1.30 filesystem code
using fs_homepath for the file to remove
==============
*/
int FS_Delete( char *filename ) {
#if 0 // Stub...not used in MP
char *ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
}
if ( !filename || filename[0] == 0 ) {
return 0;
}
// for safety, only allow deletion from the save directory
if ( Q_strncmp( filename, "save/", 5 ) != 0 ) {
return 0;
}
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( remove( ospath ) != -1 ) { // success
return 1;
}
#endif
return 0;
}
/*
=================
FS_Read
Properly handles partial reads
=================
*/
int FS_Read2( void *buffer, int len, fileHandle_t f ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !f ) {
return 0;
}
if ( fsh[f].streamed ) {
int r;
fsh[f].streamed = qfalse;
r = FS_Read( buffer, len, f );
fsh[f].streamed = qtrue;
return r;
} else {
return FS_Read( buffer, len, f );
}
}
int FS_Read( void *buffer, int len, fileHandle_t f ) {
int block, remaining;
int read;
byte *buf;
int tries;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !f ) {
return 0;
}
buf = (byte *)buffer;
fs_readCount += len;
if ( fsh[f].zipFile == qfalse ) {
remaining = len;
tries = 0;
while ( remaining ) {
block = remaining;
read = fread( buf, 1, block, fsh[f].handleFiles.file.o );
if ( read == 0 ) {
// we might have been trying to read from a CD, which
// sometimes returns a 0 read on windows
if ( !tries ) {
tries = 1;
} else {
return len - remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read");
}
}
if ( read == -1 ) {
Com_Error( ERR_FATAL, "FS_Read: -1 bytes read" );
}
remaining -= read;
buf += read;
}
return len;
} else {
return unzReadCurrentFile( fsh[f].handleFiles.file.z, buffer, len );
}
}
/*
=================
FS_Write
Properly handles partial writes
=================
*/
int FS_Write( const void *buffer, int len, fileHandle_t h ) {
int block, remaining;
int written;
byte *buf;
int tries;
FILE *f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !h ) {
return 0;
}
f = FS_FileForHandle( h );
buf = (byte *)buffer;
remaining = len;
tries = 0;
while ( remaining ) {
block = remaining;
written = fwrite( buf, 1, block, f );
if ( written == 0 ) {
if ( !tries ) {
tries = 1;
} else {
Com_Printf( "FS_Write: 0 bytes written\n" );
return 0;
}
}
if ( written == -1 ) {
Com_Printf( "FS_Write: -1 bytes written\n" );
return 0;
}
remaining -= written;
buf += written;
}
if ( fsh[h].handleSync ) {
fflush( f );
}
return len;
}
void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof( msg ), fmt, argptr );
va_end( argptr );
FS_Write( msg, strlen( msg ), h );
}
#define PK3_SEEK_BUFFER_SIZE 65536
/*
=================
FS_Seek
=================
*/
int FS_Seek( fileHandle_t f, long offset, int origin ) {
int _origin;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
return -1;
}
if (fsh[f].streamed) {
int r;
fsh[f].streamed = qfalse;
r = FS_Seek( f, offset, origin );
fsh[f].streamed = qtrue;
return r;
}
if (fsh[f].zipFile == qtrue) {
//FIXME: this is really, really crappy
//(but better than what was here before)
byte buffer[PK3_SEEK_BUFFER_SIZE];
int remainder;
int currentPosition = FS_FTell( f );
// change negative offsets into FS_SEEK_SET
if ( offset < 0 ) {
switch( origin ) {
case FS_SEEK_END:
remainder = fsh[f].zipFileLen + offset;
break;
case FS_SEEK_CUR:
remainder = currentPosition + offset;
break;
case FS_SEEK_SET:
default:
remainder = 0;
break;
}
if ( remainder < 0 ) {
remainder = 0;
}
origin = FS_SEEK_SET;
} else {
if ( origin == FS_SEEK_END ) {
remainder = fsh[f].zipFileLen - currentPosition + offset;
} else {
remainder = offset;
}
}
switch( origin ) {
case FS_SEEK_SET:
if ( remainder == currentPosition ) {
return offset;
}
unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
unzOpenCurrentFile(fsh[f].handleFiles.file.z);
//fallthrough
case FS_SEEK_END:
case FS_SEEK_CUR:
while( remainder > PK3_SEEK_BUFFER_SIZE ) {
FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f );
remainder -= PK3_SEEK_BUFFER_SIZE;
}
FS_Read( buffer, remainder, f );
return offset;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
return -1;
}
} else {
FILE *file;
file = FS_FileForHandle(f);
switch( origin ) {
case FS_SEEK_CUR:
_origin = SEEK_CUR;
break;
case FS_SEEK_END:
_origin = SEEK_END;
break;
case FS_SEEK_SET:
_origin = SEEK_SET;
break;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
break;
}
return fseek( file, offset, _origin );
}
}
/*
======================================================================================
CONVENIENCE FUNCTIONS FOR ENTIRE FILES
======================================================================================
*/
int FS_FileIsInPAK( const char *filename, int *pChecksum ) {
searchpath_t *search;
pack_t *pak;
fileInPack_t *pakFile;
long hash = 0;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !filename ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed" );
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
return -1;
}
//
// search through the path, one element at a time
//
for ( search = fs_searchpaths ; search ; search = search->next ) {
//
if ( search->pack ) {
hash = FS_HashFileName( filename, search->pack->hashSize );
}
// is the element a pak file?
if ( search->pack && search->pack->hashTable[hash] ) {
// disregard if it doesn't match one of the allowed pure pak files
if ( !FS_PakIsPure( search->pack ) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
if ( pChecksum ) {
*pChecksum = pak->pure_checksum;
}
return 1;
}
pakFile = pakFile->next;
} while ( pakFile != NULL );
}
}
return -1;
}
/*
============
FS_ReadFileDir
Filename are relative to the quake search path
a null buffer will just return the file length without loading
If searchPath is non-NULL search only in that specific search path
============
*/
long FS_ReadFileDir(const char *qpath, void *searchPath, qboolean unpure, void **buffer)
{
fileHandle_t h;
searchpath_t *search;
byte* buf;
qboolean isConfig;
long len;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !qpath || !qpath[0] ) {
Com_Error( ERR_FATAL, "FS_ReadFile with empty name" );
}
buf = NULL; // quiet compiler warning
// if this is a .cfg file and we are playing back a journal, read
// it from the journal file
if ( strstr( qpath, ".cfg" ) ) {
isConfig = qtrue;
if ( com_journal && com_journal->integer == 2 ) {
int r;
Com_DPrintf( "Loading %s from journal file.\n", qpath );
r = FS_Read( &len, sizeof( len ), com_journalDataFile );
if ( r != sizeof( len ) ) {
if (buffer != NULL) *buffer = NULL;
return -1;
}
// if the file didn't exist when the journal was created
if (!len) {
if (buffer == NULL) {
return 1; // hack for old journal files
}
*buffer = NULL;
return -1;
}
if (buffer == NULL) {
return len;
}
buf = Hunk_AllocateTempMemory(len+1);
*buffer = buf;
r = FS_Read( buf, len, com_journalDataFile );
if ( r != len ) {
Com_Error( ERR_FATAL, "Read from journalDataFile failed" );
}
fs_loadCount++;
fs_loadStack++;
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
return len;
}
} else {
isConfig = qfalse;
}
search = searchPath;
if(search == NULL)
{
// look for it in the filesystem or pack files
len = FS_FOpenFileRead(qpath, &h, qfalse);
}
else
{
// look for it in a specific search path only
len = FS_FOpenFileReadDir(qpath, search, &h, qfalse, unpure);
}
if ( h == 0 ) {
if ( buffer ) {
*buffer = NULL;
}
// if we are journalling and it is a config file, write a zero to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing zero for %s to journal file.\n", qpath );
len = 0;
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return -1;
}
if ( !buffer ) {
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing len for %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
FS_FCloseFile( h);
return len;
}
fs_loadCount++;
fs_loadStack++;
buf = Hunk_AllocateTempMemory(len+1);
*buffer = buf;
FS_Read (buf, len, h);
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
FS_FCloseFile( h );
// if we are journalling and it is a config file, write it to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Write( buf, len, com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return len;
}
/*
============
FS_ReadFile
Filename are relative to the quake search path
a null buffer will just return the file length without loading
============
*/
long FS_ReadFile(const char *qpath, void **buffer)
{
return FS_ReadFileDir(qpath, NULL, qfalse, buffer);
}
/*
=============
FS_FreeFile
=============
*/
void FS_FreeFile( void *buffer ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !buffer ) {
Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" );
}
fs_loadStack--;
Hunk_FreeTempMemory( buffer );
// if all of our temp files are free, clear all of our space
if ( fs_loadStack == 0 ) {
Hunk_ClearTempMemory();
}
}
/*
============
FS_WriteFile
Filenames are relative to the quake search path
============
*/
void FS_WriteFile( const char *qpath, const void *buffer, int size ) {
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !qpath || !buffer ) {
Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" );
}
f = FS_FOpenFileWrite( qpath );
if ( !f ) {
Com_Printf( "Failed to open %s\n", qpath );
return;
}
FS_Write( buffer, size, f );
FS_FCloseFile( f );
}
/*
==========================================================================
ZIP FILE LOADING
==========================================================================
*/
/*
=================
FS_LoadZipFile
Creates a new pak_t in the search chain for the contents
of a zip file.
=================
*/
static pack_t *FS_LoadZipFile(const char *zipfile, const char *basename ) {
fileInPack_t *buildBuffer;
pack_t *pack;
unzFile uf;
int err;
unz_global_info gi;
char filename_inzip[MAX_ZPATH];
unz_file_info file_info;
int i, len;
long hash;
int fs_numHeaderLongs;
int *fs_headerLongs;
char *namePtr;
fs_numHeaderLongs = 0;
uf = unzOpen( zipfile );
err = unzGetGlobalInfo( uf,&gi );
if ( err != UNZ_OK ) {
return NULL;
}
fs_packFiles += gi.number_entry;
len = 0;
unzGoToFirstFile( uf );
for ( i = 0; i < gi.number_entry; i++ )
{
err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 );
if ( err != UNZ_OK ) {
break;
}
len += strlen( filename_inzip ) + 1;
unzGoToNextFile( uf );
}
buildBuffer = Z_Malloc( ( gi.number_entry * sizeof( fileInPack_t ) ) + len );
namePtr = ( (char *) buildBuffer ) + gi.number_entry * sizeof( fileInPack_t );
fs_headerLongs = Z_Malloc( ( gi.number_entry + 1 ) * sizeof(int) );
fs_headerLongs[ fs_numHeaderLongs++ ] = LittleLong( fs_checksumFeed );
// get the hash table size from the number of files in the zip
// because lots of custom pk3 files have less than 32 or 64 files
for ( i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1 ) {
if ( i > gi.number_entry ) {
break;
}
}
pack = Z_Malloc( sizeof( pack_t ) + i * sizeof( fileInPack_t * ) );
pack->hashSize = i;
pack->hashTable = ( fileInPack_t ** )( ( (char *) pack ) + sizeof( pack_t ) );
for ( i = 0; i < pack->hashSize; i++ ) {
pack->hashTable[i] = NULL;
}
Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) );
Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) );
// strip .pk3 if needed
if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) {
pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0;
}
pack->handle = uf;
pack->numfiles = gi.number_entry;
unzGoToFirstFile( uf );
for ( i = 0; i < gi.number_entry; i++ )
{
err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 );
if ( err != UNZ_OK ) {
break;
}
if ( file_info.uncompressed_size > 0 ) {
fs_headerLongs[fs_numHeaderLongs++] = LittleLong( file_info.crc );
}
Q_strlwr( filename_inzip );
hash = FS_HashFileName( filename_inzip, pack->hashSize );
buildBuffer[i].name = namePtr;
strcpy( buildBuffer[i].name, filename_inzip );
namePtr += strlen( filename_inzip ) + 1;
// store the file position in the zip
buildBuffer[i].pos = unzGetOffset(uf);
buildBuffer[i].len = file_info.uncompressed_size;
buildBuffer[i].next = pack->hashTable[hash];
pack->hashTable[hash] = &buildBuffer[i];
unzGoToNextFile( uf );
}
pack->checksum = Com_BlockChecksum( &fs_headerLongs[ 1 ], sizeof(*fs_headerLongs) * ( fs_numHeaderLongs - 1 ) );
pack->pure_checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs );
pack->checksum = LittleLong( pack->checksum );
pack->pure_checksum = LittleLong( pack->pure_checksum );
Z_Free( fs_headerLongs );
pack->buildBuffer = buildBuffer;
return pack;
}
/*
=================
FS_FreePak
Frees a pak structure and releases all associated resources
=================
*/
static void FS_FreePak(pack_t *thepak)
{
unzClose(thepak->handle);
Z_Free(thepak->buildBuffer);
Z_Free(thepak);
}
/*
=================
FS_GetZipChecksum
Compares whether the given pak file matches a referenced checksum
=================
*/
qboolean FS_CompareZipChecksum(const char *zipfile)
{
pack_t *thepak;
int index, checksum;
thepak = FS_LoadZipFile(zipfile, "");
if(!thepak)
return qfalse;
checksum = thepak->checksum;
FS_FreePak(thepak);
for(index = 0; index < fs_numServerReferencedPaks; index++)
{
if(checksum == fs_serverReferencedPaks[index])
return qtrue;
}
return qfalse;
}
/*
=================================================================================
DIRECTORY SCANNING FUNCTIONS
=================================================================================
*/
#define MAX_FOUND_FILES 0x1000
static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) {
int len, at, newdep;
newdep = 0;
zpath[0] = 0;
len = 0;
at = 0;
while ( zname[at] != 0 )
{
if ( zname[at] == '/' || zname[at] == '\\' ) {
len = at;
newdep++;
}
at++;
}
strcpy( zpath, zname );
zpath[len] = 0;
*depth = newdep;
return len;
}
/*
==================
FS_AddFileToList
==================
*/
static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) {
int i;
if ( nfiles == MAX_FOUND_FILES - 1 ) {
return nfiles;
}
for ( i = 0 ; i < nfiles ; i++ ) {
if ( !Q_stricmp( name, list[i] ) ) {
return nfiles; // allready in list
}
}
list[nfiles] = CopyString( name );
nfiles++;
return nfiles;
}
/*
===============
FS_ListFilteredFiles
Returns a uniqued list of files that match the given criteria
from all search paths
===============
*/
char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles, qboolean allowNonPureFilesOnDisk ) {
int nfiles;
char **listCopy;
char *list[MAX_FOUND_FILES];
searchpath_t *search;
int i;
int pathLength;
int extensionLength;
int length, pathDepth, temp;
pack_t *pak;
fileInPack_t *buildBuffer;
char zpath[MAX_ZPATH];
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !path ) {
*numfiles = 0;
return NULL;
}
if ( !extension ) {
extension = "";
}
pathLength = strlen( path );
if ( path[pathLength - 1] == '\\' || path[pathLength - 1] == '/' ) {
pathLength--;
}
extensionLength = strlen( extension );
nfiles = 0;
FS_ReturnPath( path, zpath, &pathDepth );
//
// search through the path, one element at a time, adding to list
//
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
//ZOID: If we are pure, don't search for files on paks that
// aren't on the pure list
if ( !FS_PakIsPure( search->pack ) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
buildBuffer = pak->buildBuffer;
for ( i = 0; i < pak->numfiles; i++ ) {
char *name;
int zpathLen, depth;
// check for directory match
name = buildBuffer[i].name;
//
if ( filter ) {
// case insensitive
if ( !Com_FilterPath( filter, name, qfalse ) ) {
continue;
}
// unique the match
nfiles = FS_AddFileToList( name, list, nfiles );
} else {
zpathLen = FS_ReturnPath( name, zpath, &depth );
if ( ( depth - pathDepth ) > 2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) {
continue;
}
// check for extension match
length = strlen( name );
if ( length < extensionLength ) {
continue;
}
if ( Q_stricmp( name + length - extensionLength, extension ) ) {
continue;
}
// unique the match
temp = pathLength;
if ( pathLength ) {
temp++; // include the '/'
}
nfiles = FS_AddFileToList( name + temp, list, nfiles );
}
}
} else if ( search->dir ) { // scan for files in the filesystem
char *netpath;
int numSysFiles;
char **sysFiles;
char *name;
// don't scan directories for files if we are pure or restricted
if ( fs_numServerPaks && !allowNonPureFilesOnDisk ) {
continue;
} else {
netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path );
sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse );
for ( i = 0 ; i < numSysFiles ; i++ ) {
// unique the match
name = sysFiles[i];
nfiles = FS_AddFileToList( name, list, nfiles );
}
Sys_FreeFileList( sysFiles );
}
}
}
// return a copy of the list
*numfiles = nfiles;
if ( !nfiles ) {
return NULL;
}
listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
for ( i = 0 ; i < nfiles ; i++ ) {
listCopy[i] = list[i];
}
listCopy[i] = NULL;
return listCopy;
}
/*
=================
FS_ListFiles
=================
*/
char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) {
return FS_ListFilteredFiles( path, extension, NULL, numfiles, qfalse );
}
/*
=================
FS_FreeFileList
=================
*/
void FS_FreeFileList( char **list ) {
int i;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !list ) {
return;
}
for ( i = 0 ; list[i] ; i++ ) {
Z_Free( list[i] );
}
Z_Free( list );
}
/*
================
FS_GetFileList
================
*/
int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
int nFiles, i, nTotal, nLen;
char **pFiles = NULL;
*listbuf = 0;
nFiles = 0;
nTotal = 0;
if ( Q_stricmp( path, "$modlist" ) == 0 ) {
return FS_GetModList( listbuf, bufsize );
}
pFiles = FS_ListFiles( path, extension, &nFiles );
for ( i = 0; i < nFiles; i++ ) {
nLen = strlen( pFiles[i] ) + 1;
if ( nTotal + nLen + 1 < bufsize ) {
strcpy( listbuf, pFiles[i] );
listbuf += nLen;
nTotal += nLen;
} else {
nFiles = i;
break;
}
}
FS_FreeFileList( pFiles );
return nFiles;
}
/*
=======================
Sys_ConcatenateFileLists
mkv: Naive implementation. Concatenates three lists into a
new list, and frees the old lists from the heap.
FIXME TTimo those two should move to common.c next to Sys_ListFiles
=======================
*/
static unsigned int Sys_CountFileList(char **list)
{
int i = 0;
if (list)
{
while (*list)
{
list++;
i++;
}
}
return i;
}
static char** Sys_ConcatenateFileLists( char **list0, char **list1 )
{
int totalLength = 0;
char** cat = NULL, **dst, **src;
totalLength += Sys_CountFileList(list0);
totalLength += Sys_CountFileList(list1);
/* Create new list. */
dst = cat = Z_Malloc( ( totalLength + 1 ) * sizeof( char* ) );
/* Copy over lists. */
if (list0)
{
for (src = list0; *src; src++, dst++)
*dst = *src;
}
if (list1)
{
for (src = list1; *src; src++, dst++)
*dst = *src;
}
// Terminate the list
*dst = NULL;
// Free our old lists.
// NOTE: not freeing their content, it's been merged in dst and still being used
if (list0) Z_Free( list0 );
if (list1) Z_Free( list1 );
return cat;
}
/*
================
FS_GetModDescription
================
*/
void FS_GetModDescription( const char *modDir, char *description, int descriptionLen ) {
fileHandle_t descHandle;
char descPath[MAX_QPATH];
int nDescLen;
FILE *file;
Com_sprintf( descPath, sizeof ( descPath ), "%s/description.txt", modDir );
nDescLen = FS_SV_FOpenFileRead( descPath, &descHandle );
if ( nDescLen > 0 && descHandle ) {
file = FS_FileForHandle(descHandle);
Com_Memset( description, 0, descriptionLen );
nDescLen = fread(description, 1, descriptionLen, file);
if (nDescLen >= 0) {
description[nDescLen] = '\0';
}
FS_FCloseFile(descHandle);
} else {
Q_strncpyz( description, modDir, descriptionLen );
}
}
/*
================
FS_GetModList
Returns a list of mod directory names
A mod directory is a peer to baseq3 with a pk3 in it
The directories are searched in base path, cd path and home path
================
*/
int FS_GetModList( char *listbuf, int bufsize ) {
int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen;
char **pFiles = NULL;
char **pPaks = NULL;
char *name, *path;
char description[MAX_OSPATH];
int dummy;
char **pFiles0 = NULL;
char **pFiles1 = NULL;
#ifndef STANDALONE
char **pFiles2 = NULL;
char **pFiles3 = NULL;
#endif
qboolean bDrop = qfalse;
*listbuf = 0;
nMods = nTotal = 0;
pFiles0 = Sys_ListFiles( fs_homepath->string, NULL, NULL, &dummy, qtrue );
pFiles1 = Sys_ListFiles( fs_basepath->string, NULL, NULL, &dummy, qtrue );
#ifndef STANDALONE
pFiles2 = Sys_ListFiles( fs_steampath->string, NULL, NULL, &dummy, qtrue );
#endif
// we searched for mods in the three paths
// it is likely that we have duplicate names now, which we will cleanup below
#ifndef STANDALONE
pFiles3 = Sys_ConcatenateFileLists( pFiles0, pFiles1 );
pFiles = Sys_ConcatenateFileLists( pFiles2, pFiles3 );
#else
pFiles = Sys_ConcatenateFileLists( pFiles0, pFiles1 );
#endif
nPotential = Sys_CountFileList(pFiles);
for ( i = 0 ; i < nPotential ; i++ ) {
name = pFiles[i];
// NOTE: cleaner would involve more changes
// ignore duplicate mod directories
if (i!=0) {
bDrop = qfalse;
for(j=0; j<i; j++)
{
if (Q_stricmp(pFiles[j],name)==0) {
// this one can be dropped
bDrop = qtrue;
break;
}
}
}
if (bDrop) {
continue;
}
// we drop "baseq3" "." and ".."
if (Q_stricmp(name, com_basegame->string) && Q_stricmpn(name, ".", 1)) {
// now we need to find some .pk3 files to validate the mod
// NOTE TTimo: (actually I'm not sure why .. what if it's a mod under developement with no .pk3?)
// we didn't keep the information when we merged the directory names, as to what OS Path it was found under
// so it could be in base path, cd path or home path
// we will try each three of them here (yes, it's a bit messy)
path = FS_BuildOSPath( fs_basepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse);
Sys_FreeFileList( pPaks ); // we only use Sys_ListFiles to check wether .pk3 files are present
/* try on home path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_homepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
#ifndef STANDALONE
/* try on steam path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_steampath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
#endif
if (nPaks > 0) {
nLen = strlen(name) + 1;
// nLen is the length of the mod path
// we need to see if there is a description available
FS_GetModDescription( name, description, sizeof( description ) );
nDescLen = strlen(description) + 1;
if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) {
strcpy(listbuf, name);
listbuf += nLen;
strcpy(listbuf, description);
listbuf += nDescLen;
nTotal += nLen + nDescLen;
nMods++;
}
else {
break;
}
}
}
}
Sys_FreeFileList( pFiles );
return nMods;
}
//============================================================================
/*
================
FS_Dir_f
================
*/
void FS_Dir_f( void ) {
char *path;
char *extension;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) {
Com_Printf( "usage: dir <directory> [extension]\n" );
return;
}
if ( Cmd_Argc() == 2 ) {
path = Cmd_Argv( 1 );
extension = "";
} else {
path = Cmd_Argv( 1 );
extension = Cmd_Argv( 2 );
}
Com_Printf( "Directory of %s %s\n", path, extension );
Com_Printf( "---------------\n" );
dirnames = FS_ListFiles( path, extension, &ndirs );
for ( i = 0; i < ndirs; i++ ) {
Com_Printf( "%s\n", dirnames[i] );
}
FS_FreeFileList( dirnames );
}
/*
===========
FS_ConvertPath
===========
*/
void FS_ConvertPath( char *s ) {
while ( *s ) {
if ( *s == '\\' || *s == ':' ) {
*s = '/';
}
s++;
}
}
/*
===========
FS_PathCmp
Ignore case and seprator char distinctions
===========
*/
int FS_PathCmp( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if ( c1 >= 'a' && c1 <= 'z' ) {
c1 -= ( 'a' - 'A' );
}
if ( c2 >= 'a' && c2 <= 'z' ) {
c2 -= ( 'a' - 'A' );
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if ( c1 < c2 ) {
return -1; // strings not equal
}
if ( c1 > c2 ) {
return 1;
}
} while ( c1 );
return 0; // strings are equal
}
/*
================
FS_SortFileList
================
*/
void FS_SortFileList( char **filelist, int numfiles ) {
int i, j, k, numsortedfiles;
char **sortedlist;
sortedlist = Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ) );
sortedlist[0] = NULL;
numsortedfiles = 0;
for ( i = 0; i < numfiles; i++ ) {
for ( j = 0; j < numsortedfiles; j++ ) {
if ( FS_PathCmp( filelist[i], sortedlist[j] ) < 0 ) {
break;
}
}
for ( k = numsortedfiles; k > j; k-- ) {
sortedlist[k] = sortedlist[k - 1];
}
sortedlist[j] = filelist[i];
numsortedfiles++;
}
Com_Memcpy( filelist, sortedlist, numfiles * sizeof( *filelist ) );
Z_Free( sortedlist );
}
/*
================
FS_NewDir_f
================
*/
void FS_NewDir_f( void ) {
char *filter;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 ) {
Com_Printf( "usage: fdir <filter>\n" );
Com_Printf( "example: fdir *q3dm*.bsp\n" );
return;
}
filter = Cmd_Argv( 1 );
Com_Printf( "---------------\n" );
dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs, qfalse );
FS_SortFileList( dirnames, ndirs );
for ( i = 0; i < ndirs; i++ ) {
FS_ConvertPath( dirnames[i] );
Com_Printf( "%s\n", dirnames[i] );
}
Com_Printf( "%d files listed\n", ndirs );
FS_FreeFileList( dirnames );
}
/*
============
FS_Path_f
============
*/
void FS_Path_f( void ) {
searchpath_t *s;
int i;
Com_Printf( "Current search path:\n" );
for ( s = fs_searchpaths; s; s = s->next ) {
if ( s->pack ) {
Com_Printf( "%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles );
if ( fs_numServerPaks ) {
if ( !FS_PakIsPure( s->pack ) ) {
Com_Printf( " not on the pure list\n" );
} else {
Com_Printf( " on the pure list\n" );
}
}
} else {
Com_Printf ("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir );
}
}
Com_Printf( "\n" );
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o ) {
Com_Printf( "handle %i: %s\n", i, fsh[i].name );
}
}
}
/*
============
FS_TouchFile_f
============
*/
void FS_TouchFile_f( void ) {
fileHandle_t f;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: touchFile <file>\n" );
return;
}
FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse );
if ( f ) {
FS_FCloseFile( f );
}
}
/*
============
FS_Which
============
*/
qboolean FS_Which(const char *filename, void *searchPath)
{
searchpath_t *search = searchPath;
if(FS_FOpenFileReadDir(filename, search, NULL, qfalse, qfalse) > 0)
{
if(search->pack)
{
Com_Printf("File \"%s\" found in \"%s\"\n", filename, search->pack->pakFilename);
return qtrue;
}
else if(search->dir)
{
Com_Printf( "File \"%s\" found at \"%s\"\n", filename, search->dir->fullpath);
return qtrue;
}
}
return qfalse;
}
/*
============
FS_Which_f
============
*/
void FS_Which_f( void ) {
searchpath_t *search;
char *filename;
filename = Cmd_Argv(1);
if ( !filename[0] ) {
Com_Printf( "Usage: which <file>\n" );
return;
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// just wants to see if file is there
for(search = fs_searchpaths; search; search = search->next)
{
if(FS_Which(filename, search))
return;
}
Com_Printf("File not found: \"%s\"\n", filename);
}
//===========================================================================
static int QDECL paksort( const void *a, const void *b ) {
char *aa, *bb;
aa = *(char **)a;
bb = *(char **)b;
return FS_PathCmp( aa, bb );
}
/*
================
FS_AddGameDirectory
Sets fs_gamedir, adds the directory to the head of the path,
then loads the zip headers
================
*/
#define MAX_PAKFILES 1024
void FS_AddGameDirectory( const char *path, const char *dir, qboolean allowUnzippedDLLs ) {
searchpath_t *sp;
int i;
searchpath_t *search;
pack_t *pak;
char curpath[MAX_OSPATH + 1], *pakfile;
int numfiles;
char **pakfiles;
char *sorted[MAX_PAKFILES];
// find all pak files in this directory
Q_strncpyz(curpath, FS_BuildOSPath(path, dir, ""), sizeof(curpath));
curpath[strlen(curpath) - 1] = '\0'; // strip the trailing slash
// this fixes the case where fs_basepath is the same as fs_cdpath
// which happens on full installs
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->dir && !Q_stricmp( sp->dir->path, path ) && !Q_stricmp( sp->dir->gamedir, dir ) ) {
return; // we've already got this one
}
}
Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) );
// find all pak files in this directory
pakfile = FS_BuildOSPath( path, dir, "" );
pakfile[ strlen( pakfile ) - 1 ] = 0; // strip the trailing slash
pakfiles = Sys_ListFiles( pakfile, ".pk3", NULL, &numfiles, qfalse );
// sort them so that later alphabetic matches override
// earlier ones. This makes pak1.pk3 override pak0.pk3
if ( numfiles > MAX_PAKFILES ) {
numfiles = MAX_PAKFILES;
}
for ( i = 0 ; i < numfiles ; i++ ) {
sorted[i] = pakfiles[i];
// JPW NERVE KLUDGE: sorry, temp mod mp_* to _p_* so "mp_pak*" gets alphabetically sorted before "pak*"
if ( !Q_strncmp( sorted[i],"mp_",3 ) ) {
memcpy( sorted[i],"zz",2 );
}
// jpw
}
qsort( sorted, numfiles, sizeof(char*), paksort );
for ( i = 0 ; i < numfiles ; i++ ) {
if ( Q_strncmp( sorted[i],"sp_",3 ) ) { // JPW NERVE -- exclude sp_*
// JPW NERVE KLUDGE: fix filenames broken in mp/sp/pak sort above
if ( !Q_strncmp( sorted[i],"zz_",3 ) ) {
memcpy( sorted[i],"mp",2 );
}
// jpw
pakfile = FS_BuildOSPath( path, dir, sorted[i] );
if ( ( pak = FS_LoadZipFile( pakfile, sorted[i] ) ) == 0 ) {
continue;
}
Q_strncpyz(pak->pakPathname, curpath, sizeof(pak->pakPathname));
// store the game name for downloading
strcpy( pak->pakGamename, dir );
search = Z_Malloc( sizeof( searchpath_t ) );
search->pack = pak;
search->next = fs_searchpaths;
fs_searchpaths = search;
}
}
// done
Sys_FreeFileList( pakfiles );
//
// add the directory to the search path
//
search = Z_Malloc (sizeof(searchpath_t));
search->dir = Z_Malloc( sizeof( *search->dir ) );
Q_strncpyz(search->dir->path, path, sizeof(search->dir->path));
Q_strncpyz(search->dir->fullpath, curpath, sizeof(search->dir->fullpath));
Q_strncpyz(search->dir->gamedir, dir, sizeof(search->dir->gamedir));
search->dir->allowUnzippedDLLs = allowUnzippedDLLs;
search->next = fs_searchpaths;
fs_searchpaths = search;
}
/*
================
FS_idPak
================
*/
qboolean FS_idPak(char *pak, char *base, int numPaks) {
int i;
if ( !FS_FilenameCompare( pak, va( "%s/mp_bin", base ) ) ) {
return qtrue;
}
for ( i = 0; i < NUM_ID_PAKS; i++ ) {
if ( !FS_FilenameCompare( pak, va( "%s/mp_bin%d", base, i ) ) ) {
break;
}
if ( !FS_FilenameCompare( pak, va( "%s/pak%d", base, i ) ) ) {
break;
}
// JPW NERVE -- this fn prevents external sources from downloading/overwriting official files, so exclude both SP and MP files from this list as well
if ( !FS_FilenameCompare( pak, va( "%s/mp_pak%d",base,i ) ) ) {
break;
}
if ( !FS_FilenameCompare( pak, va( "%s/sp_pak%d",base,i + 1) ) ) {
break;
}
// jpw
}
if ( i < numPaks ) {
return qtrue;
}
return qfalse;
}
/*
================
FS_CheckDirTraversal
Check whether the string contains stuff like "../" to prevent directory traversal bugs
and return qtrue if it does.
================
*/
qboolean FS_CheckDirTraversal(const char *checkdir)
{
if(strstr(checkdir, "../") || strstr(checkdir, "..\\"))
return qtrue;
return qfalse;
}
/*
================
FS_ComparePaks
----------------
dlstring == qtrue
Returns a list of pak files that we should download from the server. They all get stored
in the current gamedir and an FS_Restart will be fired up after we download them all.
The string is the format:
@remotename@localname [repeat]
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS];
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS];
----------------
dlstring == qfalse
we are not interested in a download string format, we want something human-readable
(this is used for diagnostics while connecting to a pure server)
================
*/
qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring ) {
searchpath_t *sp;
qboolean havepak;
char *origpos = neededpaks;
int i;
if ( !fs_numServerReferencedPaks )
return qfalse; // Server didn't send any pack information along
*neededpaks = 0;
for ( i = 0 ; i < fs_numServerReferencedPaks ; i++ )
{
// Ok, see if we have this pak file
havepak = qfalse;
// never autodownload any of the id paks
if(FS_idPak(fs_serverReferencedPakNames[i], BASEGAME, NUM_ID_PAKS))
{
continue;
}
// Make sure the server cannot make us write to non-quake3 directories.
if(FS_CheckDirTraversal(fs_serverReferencedPakNames[i]))
{
Com_Printf("WARNING: Invalid download name %s\n", fs_serverReferencedPakNames[i]);
continue;
}
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i] ) {
havepak = qtrue; // This is it!
break;
}
}
if ( !havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i] ) {
// Don't got it
if ( dlstring ) {
// We need this to make sure we won't hit the end of the buffer or the server could
// overwrite non-pk3 files on clients by writing so much crap into neededpaks that
// Q_strcat cuts off the .pk3 extension.
origpos += strlen(origpos);
// Remote name
Q_strcat( neededpaks, len, "@" );
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Local name
Q_strcat( neededpaks, len, "@" );
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) ) {
char st[MAX_ZPATH];
// We already have one called this, we need to download it to another name
// Make something up with the checksum in it
Com_sprintf( st, sizeof( st ), "%s.%08x.pk3", fs_serverReferencedPakNames[i], fs_serverReferencedPaks[i] );
Q_strcat( neededpaks, len, st );
} else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
}
// Find out whether it might have overflowed the buffer and don't add this file to the
// list if that is the case.
if(strlen(origpos) + (origpos - neededpaks) >= len - 1)
{
*origpos = '\0';
break;
}
} else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) ) {
Q_strcat( neededpaks, len, " (local file exists with wrong checksum)" );
}
Q_strcat( neededpaks, len, "\n" );
}
}
}
if ( *neededpaks ) {
Com_Printf( "Need paks: %s\n", neededpaks );
return qtrue;
}
return qfalse; // We have them all
}
/*
================
FS_Shutdown
Frees all resources.
================
*/
void FS_Shutdown( qboolean closemfp ) {
searchpath_t *p, *next;
int i;
for ( i = 0; i < MAX_FILE_HANDLES; i++ ) {
if ( fsh[i].fileSize ) {
FS_FCloseFile( i );
}
}
// free everything
for ( p = fs_searchpaths ; p ; p = next ) {
next = p->next;
if(p->pack)
FS_FreePak(p->pack);
if (p->dir)
Z_Free(p->dir);
Z_Free(p);
}
// any FS_ calls will now be an error until reinitialized
fs_searchpaths = NULL;
Cmd_RemoveCommand( "path" );
Cmd_RemoveCommand( "dir" );
Cmd_RemoveCommand( "fdir" );
Cmd_RemoveCommand( "touchFile" );
Cmd_RemoveCommand( "which" );
#ifdef FS_MISSING
if ( closemfp ) {
fclose( missingFiles );
}
#endif
}
/*
================
FS_ReorderPurePaks
NOTE TTimo: the reordering that happens here is not reflected in the cvars (\cvarlist *pak*)
this can lead to misleading situations, see show_bug.cgi?id=540
================
*/
static void FS_ReorderPurePaks( void ) {
searchpath_t *s;
int i;
searchpath_t **p_insert_index, // for linked list reordering
**p_previous; // when doing the scan
fs_reordered = qfalse;
// only relevant when connected to pure server
if ( !fs_numServerPaks ) {
return;
}
p_insert_index = &fs_searchpaths; // we insert in order at the beginning of the list
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
p_previous = p_insert_index; // track the pointer-to-current-item
for ( s = *p_insert_index; s; s = s->next ) { // the part of the list before p_insert_index has been sorted already
if ( s->pack && fs_serverPaks[i] == s->pack->checksum ) {
fs_reordered = qtrue;
// move this element to the insert list
*p_previous = s->next;
s->next = *p_insert_index;
*p_insert_index = s;
// increment insert list
p_insert_index = &s->next;
break; // iterate to next server pack
}
p_previous = &s->next;
}
}
}
/*
================
FS_Startup
================
*/
static void FS_Startup( const char *gameName ) {
const char *homePath;
Com_Printf( "----- FS_Startup -----\n" );
fs_packFiles = 0;
fs_debug = Cvar_Get( "fs_debug", "0", 0 );
fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT|CVAR_PROTECTED );
fs_basegame = Cvar_Get( "fs_basegame", "", CVAR_INIT );
homePath = Sys_DefaultHomePath();
if (!homePath || !homePath[0]) {
homePath = fs_basepath->string;
}
fs_homepath = Cvar_Get ("fs_homepath", homePath, CVAR_INIT|CVAR_PROTECTED );
fs_gamedirvar = Cvar_Get( "fs_game", "", CVAR_INIT | CVAR_SYSTEMINFO );
// add search path elements in reverse priority order
#ifndef STANDALONE
fs_steampath = Cvar_Get ("fs_steampath", Sys_SteamPath(), CVAR_INIT|CVAR_PROTECTED );
if (fs_steampath->string[0]) {
FS_AddGameDirectory( fs_steampath->string, gameName, qtrue );
}
#endif
if ( fs_basepath->string[0] ) {
FS_AddGameDirectory( fs_basepath->string, gameName, qtrue );
}
#ifdef __APPLE__
fs_apppath = Cvar_Get ("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT|CVAR_PROTECTED );
// Make MacOSX also include the base path included with the .app bundle
if (fs_apppath->string[0])
FS_AddGameDirectory(fs_apppath->string, gameName, qtrue);
#endif
// NOTE: same filtering below for mods and basegame
if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string)) {
FS_CreatePath ( fs_homepath->string );
FS_AddGameDirectory( fs_homepath->string, gameName, qtrue );
}
// check for additional base game so mods can be based upon other mods
if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) ) {
#ifndef STANDALONE
if ( fs_steampath->string[0] ) {
FS_AddGameDirectory( fs_steampath->string, fs_basegame->string, qtrue );
}
#endif
if ( fs_basepath->string[0] ) {
FS_AddGameDirectory( fs_basepath->string, fs_basegame->string, qtrue );
}
if ( fs_homepath->string[0] && Q_stricmp( fs_homepath->string,fs_basepath->string ) ) {
FS_AddGameDirectory( fs_homepath->string, fs_basegame->string, qtrue );
}
}
// check for additional game folder for mods
if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) ) {
#ifndef STANDALONE
if ( fs_steampath->string[0] ) {
FS_AddGameDirectory( fs_steampath->string, fs_gamedirvar->string, qtrue );
}
#endif
if ( fs_basepath->string[0] ) {
FS_AddGameDirectory( fs_basepath->string, fs_gamedirvar->string, qtrue );
}
if ( fs_homepath->string[0] && Q_stricmp( fs_homepath->string,fs_basepath->string ) ) {
FS_AddGameDirectory( fs_homepath->string, fs_gamedirvar->string, qtrue );
}
}
#ifndef STANDALONE
if(!com_standalone->integer)
{
cvar_t *fs;
Com_ReadCDKey(BASEGAME);
fs = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
if (fs && fs->string[0] != 0) {
Com_AppendCDKey( fs->string );
}
}
#endif
// add our commands
Cmd_AddCommand( "path", FS_Path_f );
Cmd_AddCommand( "dir", FS_Dir_f );
Cmd_AddCommand( "fdir", FS_NewDir_f );
Cmd_AddCommand( "touchFile", FS_TouchFile_f );
Cmd_AddCommand ("which", FS_Which_f );
// show_bug.cgi?id=506
// reorder the pure pk3 files according to server order
FS_ReorderPurePaks();
// print the current search paths
FS_Path_f();
fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified
Com_Printf( "----------------------\n" );
#ifdef FS_MISSING
if ( missingFiles == NULL ) {
missingFiles = Sys_FOpen( "\\missing.txt", "ab" );
}
#endif
Com_Printf( "%d files in pk3 files\n", fs_packFiles );
}
#ifndef STANDALONE
/*
===================
FS_CheckMPPaks
Check whether any of the original id pak files is present,
and start up in standalone mode, if there are none and a
different com_basegame was set.
Note: If you're building a game that doesn't depend on the
RTCW media mp_pak0.pk3, you'll want to remove this by defining
STANDALONE in q_shared.h
===================
*/
static void FS_CheckMPPaks( void )
{
searchpath_t *path;
pack_t *curpack;
unsigned int foundPak = 0;
for( path = fs_searchpaths; path; path = path->next )
{
const char* pakBasename = path->pack->pakBasename;
if(!path->pack)
continue;
curpack = path->pack;
if(!Q_stricmpn( curpack->pakGamename, BASEGAME, MAX_OSPATH )
&& strlen(pakBasename) == 7 && !Q_stricmpn( pakBasename, "mp_pak", 6 )
&& pakBasename[6] >= '0' && pakBasename[6] <= '0' + NUM_MP_PAKS - 1)
{
if( curpack->checksum != mppak_checksums[pakBasename[6]-'0'] )
{
if(pakBasename[6] == '0')
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/mp_pak0.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-copy mp_pak0.pk3 from your\n"
"legitimate RTCW CDROM.\n"
"**************************************************\n\n\n",
curpack->checksum );
}
else
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/mp_pak%d.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-install the point release\n"
"**************************************************\n\n\n",
pakBasename[6]-'0', curpack->checksum );
}
}
foundPak |= 1<<(pakBasename[6]-'0');
}
else
{
int index;
// Finally check whether this pak's checksum is listed because the user tried
// to trick us by renaming the file, and set foundPak's highest bit to indicate this case.
for(index = 0; index < ARRAY_LEN(mppak_checksums); index++)
{
if(curpack->checksum == mppak_checksums[index])
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: %s is renamed pak file %s%cmp_pak%d.pk3\n"
"Running in standalone mode won't work\n"
"Please rename, or remove this file\n"
"**************************************************\n\n\n",
curpack->pakFilename, BASEGAME, PATH_SEP, index);
foundPak |= 0x80000000;
}
}
}
}
if(!foundPak && Q_stricmp(com_basegame->string, BASEGAME))
{
Cvar_Set("com_standalone", "1");
}
else
Cvar_Set("com_standalone", "0");
if(!com_standalone->integer && (foundPak & 0x3f) != 0x3f)
{
char errorText[MAX_STRING_CHARS] = "";
char missingPaks[MAX_STRING_CHARS] = "";
int i = 0;
if((foundPak & 0x3f) != 0x3f)
{
for( i = 0; i < NUM_MP_PAKS; i++ ) {
if ( !( foundPak & ( 1 << i ) ) ) {
Q_strcat( missingPaks, sizeof( missingPaks ), va( "mp_pak%d.pk3 ", i ) );
}
}
Q_strcat( errorText, sizeof( errorText ),
va( "\n\nPoint Release files are missing: %s \n"
"Please re-install the 1.41 point release.\n\n", missingPaks ) );
}
Com_Error(ERR_FATAL, "%s", errorText);
}
}
/*
===================
FS_CheckPak0
Check whether any of the original id pak files is present,
and start up in standalone mode, if there are none and a
different com_basegame was set.
Note: If you're building a game that doesn't depend on the
RTCW media pak0.pk3, you'll want to remove this by defining
STANDALONE in q_shared.h
===================
*/
static void FS_CheckPak0( void )
{
searchpath_t *path;
pack_t *curpack;
qboolean founddemo = qfalse;
unsigned int foundPak = 0;
for( path = fs_searchpaths; path; path = path->next )
{
const char* pakBasename = path->pack->pakBasename;
if(!path->pack)
continue;
curpack = path->pack;
if(!Q_stricmpn( curpack->pakGamename, "demomain", MAX_OSPATH )
&& !Q_stricmpn( pakBasename, "pak0", MAX_OSPATH ))
{
if(curpack->checksum == DEMO_PAK0_CHECKSUM)
founddemo = qtrue;
}
else if(!Q_stricmpn( curpack->pakGamename, BASEGAME, MAX_OSPATH )
&& strlen(pakBasename) == 4 && !Q_stricmpn( pakBasename, "pak", 3 )
&& pakBasename[3] >= '0' && pakBasename[3] <= '0' + NUM_ID_PAKS - 1)
{
if( curpack->checksum != pak_checksums[pakBasename[3]-'0'] )
{
if(pakBasename[3] == '0')
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/pak0.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-copy pak0.pk3 from your\n"
"legitimate RTCW CDROM.\n"
"**************************************************\n\n\n",
curpack->checksum );
Com_Error(ERR_FATAL, NULL);
}
/*
else
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/pak%d.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-install the point release\n"
"**************************************************\n\n\n",
pakBasename[3]-'0', curpack->checksum );
}
*/
}
foundPak |= 1<<(pakBasename[3]-'0');
}
else
{
int index;
// Finally check whether this pak's checksum is listed because the user tried
// to trick us by renaming the file, and set foundPak's highest bit to indicate this case.
for(index = 0; index < ARRAY_LEN(pak_checksums); index++)
{
if(curpack->checksum == pak_checksums[index])
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: %s is renamed pak file %s%cpak%d.pk3\n"
"Running in standalone mode won't work\n"
"Please rename, or remove this file\n"
"**************************************************\n\n\n",
curpack->pakFilename, BASEGAME, PATH_SEP, index);
foundPak |= 0x80000000;
}
}
}
}
if(!foundPak && Q_stricmp(com_basegame->string, BASEGAME))
{
Cvar_Set("com_standalone", "1");
}
else
Cvar_Set("com_standalone", "0");
if(!com_standalone->integer)
{
if(!(foundPak & 0x01))
{
if(founddemo)
{
Com_Printf( "\n\n"
"**************************************************\n"
"WARNING: It looks like you're using pak0.pk3\n"
"from the demo. This may work fine, but it is not\n"
"guaranteed or supported.\n"
"**************************************************\n\n\n" );
foundPak |= 0x01;
}
}
}
if(!com_standalone->integer && (foundPak & 0x01) != 0x01)
{
char errorText[MAX_STRING_CHARS] = "";
if((foundPak & 0x01) != 0x01)
{
Q_strcat(errorText, sizeof(errorText),
"\n\n\"pak0.pk3\" is missing. Please copy it\n"
"from your legitimate RTCW CDROM.\n\n");
}
Q_strcat(errorText, sizeof(errorText),
va("Also check that your iortcw executable is in\n"
"the correct place and that every file\n"
"in the \"%s\" directory is present and readable.\n\n", BASEGAME));
Com_Error(ERR_FATAL, "%s", errorText);
}
if(!founddemo)
FS_CheckMPPaks();
}
#endif
/*
=====================
FS_LoadedPakChecksums
Returns a space separated string containing the checksums of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->checksum ) );
}
return info;
}
/*
=====================
FS_LoadedPakNames
Returns a space separated string containing the names of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
if ( *info ) {
Q_strcat( info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
return info;
}
/*
=====================
FS_LoadedPakPureChecksums
Returns a space separated string containing the pure checksums of all loaded pk3 files.
Servers with sv_pure use these checksums to compare with the checksums the clients send
back to the server.
=====================
*/
const char *FS_LoadedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->pure_checksum ) );
}
return info;
}
/*
=====================
FS_ReferencedPakChecksums
Returns a space separated string containing the checksums of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) {
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->checksum ) );
}
}
}
return info;
}
/*
=====================
FS_ReferencedPakNames
Returns a space separated string containing the names of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
// we want to return ALL pk3's from the fs_game path
// and referenced one's from baseq3
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) {
if (*info) {
Q_strcat(info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakGamename );
Q_strcat( info, sizeof( info ), "/" );
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
}
}
return info;
}
/*
=====================
FS_ReferencedPakPureChecksums
Returns a space separated string containing the pure checksums of all referenced pk3 files.
Servers with sv_pure set will get this string back from clients for pure validation
The string has a specific order, "cgame ui @ ref1 ref2 ref3 ..."
=====================
*/
const char *FS_ReferencedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
int nFlags, numPaks, checksum;
info[0] = 0;
checksum = fs_checksumFeed;
numPaks = 0;
for ( nFlags = FS_CGAME_REF; nFlags; nFlags = nFlags >> 1 ) {
if ( nFlags & FS_GENERAL_REF ) {
// add a delimter between must haves and general refs
//Q_strcat(info, sizeof(info), "@ ");
info[strlen( info ) + 1] = '\0';
info[strlen( info ) + 2] = '\0';
info[strlen( info )] = '@';
info[strlen( info )] = ' ';
}
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file and has it been referenced based on flag?
if ( search->pack && ( search->pack->referenced & nFlags ) ) {
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->pure_checksum ) );
if ( nFlags & ( FS_CGAME_REF | FS_UI_REF ) ) {
break;
}
checksum ^= search->pack->pure_checksum;
numPaks++;
}
}
}
// last checksum is the encoded number of referenced pk3s
checksum ^= numPaks;
Q_strcat( info, sizeof( info ), va( "%i ", checksum ) );
return info;
}
/*
=====================
FS_ClearPakReferences
=====================
*/
void FS_ClearPakReferences( int flags ) {
searchpath_t *search;
if ( !flags ) {
flags = -1;
}
for ( search = fs_searchpaths; search; search = search->next ) {
// is the element a pak file and has it been referenced?
if ( search->pack ) {
search->pack->referenced &= ~flags;
}
}
}
/*
=====================
FS_PureServerSetLoadedPaks
If the string is empty, all data sources will be allowed.
If not empty, only pk3 files that match one of the space
separated checksums will be checked for files, with the
exception of .cfg and .dat files.
=====================
*/
void FS_PureServerSetLoadedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
fs_numServerPaks = c;
for ( i = 0 ; i < c ; i++ ) {
fs_serverPaks[i] = atoi( Cmd_Argv( i ) );
}
if ( fs_numServerPaks ) {
Com_DPrintf( "Connected to a pure server.\n" );
} else
{
if ( fs_reordered ) {
// show_bug.cgi?id=540
// force a restart to make sure the search order will be correct
Com_DPrintf( "FS search reorder is required\n" );
FS_Restart( fs_checksumFeed );
return;
}
}
for ( i = 0 ; i < c ; i++ ) {
if ( fs_serverPakNames[i] ) {
Z_Free( fs_serverPakNames[i] );
}
fs_serverPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if ( d > MAX_SEARCH_PATHS ) {
d = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < d ; i++ ) {
fs_serverPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
}
/*
=====================
FS_PureServerSetReferencedPaks
The checksums and names of the pk3 files referenced at the server
are sent to the client and stored here. The client will use these
checksums to see if any pk3 files need to be auto-downloaded.
=====================
*/
void FS_PureServerSetReferencedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d = 0;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < c ; i++ ) {
fs_serverReferencedPaks[i] = atoi( Cmd_Argv( i ) );
}
for (i = 0 ; i < ARRAY_LEN(fs_serverReferencedPakNames); i++)
{
if(fs_serverReferencedPakNames[i])
Z_Free( fs_serverReferencedPakNames[i] );
fs_serverReferencedPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if(d > c)
d = c;
for ( i = 0 ; i < d ; i++ ) {
fs_serverReferencedPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
// ensure that there are as many checksums as there are pak names.
if(d < c)
c = d;
fs_numServerReferencedPaks = c;
}
/*
================
FS_InitFilesystem
Called only at inital startup, not when the filesystem
is resetting due to a game change
================
*/
void FS_InitFilesystem( void ) {
// allow command line parms to override our defaults
// we have to specially handle this, because normal command
// line variable sets don't happen until after the filesystem
// has already been initialized
Com_StartupVariable("fs_basepath");
Com_StartupVariable("fs_homepath");
Com_StartupVariable("fs_game");
if(!FS_FilenameCompare(Cvar_VariableString("fs_game"), com_basegame->string))
Cvar_Set("fs_game", "");
// try to start up normally
FS_Startup(com_basegame->string);
#ifndef STANDALONE
#ifndef UPDATE_SERVER
FS_CheckPak0( );
#endif
#endif
#ifndef UPDATE_SERVER
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
// TTimo - added some verbosity, 'couldn't load default.cfg' confuses the hell out of users
Com_Error( ERR_FATAL, "Couldn't load default.cfg - I am missing essential files - verify your installation?" );
}
#endif
Q_strncpyz( lastValidBase, fs_basepath->string, sizeof( lastValidBase ) );
Q_strncpyz( lastValidComBaseGame, com_basegame->string, sizeof( lastValidComBaseGame ) );
Q_strncpyz( lastValidFsBaseGame, fs_basegame->string, sizeof( lastValidFsBaseGame ) );
Q_strncpyz( lastValidGame, fs_gamedirvar->string, sizeof( lastValidGame ) );
}
/*
================
FS_Restart
================
*/
void FS_Restart( int checksumFeed ) {
const char *lastGameDir;
// free anything we currently have loaded
FS_Shutdown( qfalse );
// set the checksum feed
fs_checksumFeed = checksumFeed;
// clear pak references
FS_ClearPakReferences( 0 );
// try to start up normally
FS_Startup(com_basegame->string);
#ifndef STANDALONE
FS_CheckPak0( );
#endif
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
// this might happen when connecting to a pure server not using BASEGAME/pak0.pk3
// (for instance a TA demo server)
if ( lastValidBase[0] ) {
FS_PureServerSetLoadedPaks( "", "" );
Cvar_Set( "fs_basepath", lastValidBase );
Cvar_Set( "com_basegame", lastValidComBaseGame );
Cvar_Set( "fs_basegame", lastValidFsBaseGame );
Cvar_Set( "fs_game", lastValidGame );
lastValidBase[0] = '\0';
lastValidComBaseGame[0] = '\0';
lastValidFsBaseGame[0] = '\0';
lastValidGame[0] = '\0';
FS_Restart( checksumFeed );
Com_Error( ERR_DROP, "Invalid game folder" );
return;
}
Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
}
lastGameDir = ( lastValidGame[0] ) ? lastValidGame : lastValidComBaseGame;
if ( Q_stricmp( FS_GetCurrentGameDir(), lastGameDir ) ) {
Sys_RemovePIDFile( lastGameDir );
Sys_InitPIDFile( FS_GetCurrentGameDir() );
// skip the wolfconfig.cfg if "safe" is on the command line
if ( !Com_SafeMode() ) {
Cbuf_AddText("exec " Q3CONFIG_CFG "\n");
}
}
Q_strncpyz( lastValidBase, fs_basepath->string, sizeof( lastValidBase ) );
Q_strncpyz( lastValidComBaseGame, com_basegame->string, sizeof( lastValidComBaseGame ) );
Q_strncpyz( lastValidFsBaseGame, fs_basegame->string, sizeof( lastValidFsBaseGame ) );
Q_strncpyz( lastValidGame, fs_gamedirvar->string, sizeof( lastValidGame ) );
}
/*
=================
FS_ConditionalRestart
Restart if necessary
Return qtrue if restarting due to game directory changed, qfalse otherwise
=================
*/
qboolean FS_ConditionalRestart(int checksumFeed, qboolean disconnect)
{
if(fs_gamedirvar->modified)
{
if(FS_FilenameCompare(lastValidGame, fs_gamedirvar->string) &&
(*lastValidGame || FS_FilenameCompare(fs_gamedirvar->string, com_basegame->string)) &&
(*fs_gamedirvar->string || FS_FilenameCompare(lastValidGame, com_basegame->string)))
{
Com_GameRestart(checksumFeed, disconnect);
return qtrue;
}
else
fs_gamedirvar->modified = qfalse;
}
if(checksumFeed != fs_checksumFeed)
FS_Restart(checksumFeed);
else if(fs_numServerPaks && !fs_reordered)
FS_ReorderPurePaks();
return qfalse;
}
/*
========================================================================================
Handle based file calls for virtual machines
========================================================================================
*/
int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
int r;
qboolean sync;
sync = qfalse;
switch( mode ) {
case FS_READ:
r = FS_FOpenFileRead( qpath, f, qtrue );
break;
case FS_WRITE:
*f = FS_FOpenFileWrite( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
case FS_APPEND_SYNC:
sync = qtrue;
case FS_APPEND:
*f = FS_FOpenFileAppend( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
default:
Com_Error( ERR_FATAL, "FS_FOpenFileByMode: bad mode" );
return -1;
}
if (!f) {
return r;
}
if ( *f ) {
fsh[*f].fileSize = r;
fsh[*f].streamed = qfalse;
if (mode == FS_READ) {
fsh[*f].streamed = qtrue;
}
}
fsh[*f].handleSync = sync;
return r;
}
int FS_FTell( fileHandle_t f ) {
int pos;
if ( fsh[f].zipFile == qtrue ) {
pos = unztell( fsh[f].handleFiles.file.z );
} else {
pos = ftell( fsh[f].handleFiles.file.o );
}
return pos;
}
void FS_Flush( fileHandle_t f ) {
fflush( fsh[f].handleFiles.file.o );
}
void FS_FilenameCompletion( const char *dir, const char *ext,
qboolean stripExt, void(*callback)(const char *s), qboolean allowNonPureFilesOnDisk ) {
char **filenames;
int nfiles;
int i;
char filename[ MAX_STRING_CHARS ];
filenames = FS_ListFilteredFiles( dir, ext, NULL, &nfiles, allowNonPureFilesOnDisk );
FS_SortFileList( filenames, nfiles );
for( i = 0; i < nfiles; i++ ) {
FS_ConvertPath( filenames[ i ] );
Q_strncpyz( filename, filenames[ i ], MAX_STRING_CHARS );
if( stripExt ) {
COM_StripExtension(filename, filename, sizeof(filename));
}
callback( filename );
}
FS_FreeFileList( filenames );
}
const char *FS_GetCurrentGameDir(void)
{
if(fs_gamedirvar->string[0])
return fs_gamedirvar->string;
return com_basegame->string;
}
// CVE-2006-2082
// compared requested pak against the names as we built them in FS_ReferencedPakNames
qboolean FS_VerifyPak( const char *pak ) {
char teststring[ BIG_INFO_STRING ];
searchpath_t *search;
for ( search = fs_searchpaths ; search ; search = search->next ) {
if ( search->pack ) {
Q_strncpyz( teststring, search->pack->pakGamename, sizeof( teststring ) );
Q_strcat( teststring, sizeof( teststring ), "/" );
Q_strcat( teststring, sizeof( teststring ), search->pack->pakBasename );
Q_strcat( teststring, sizeof( teststring ), ".pk3" );
if ( !Q_stricmp( teststring, pak ) ) {
return qtrue;
}
}
}
return qfalse;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3233_1 |
crossvul-cpp_data_good_3232_1 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
Copyright (C) 2005 Stuart Dalton (badcdev@gmail.com)
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "snd_local.h"
#include "snd_codec.h"
#include "client.h"
#ifdef USE_OPENAL
#include "qal.h"
// Console variables specific to OpenAL
cvar_t *s_alPrecache;
cvar_t *s_alGain;
cvar_t *s_alSources;
cvar_t *s_alDopplerFactor;
cvar_t *s_alDopplerSpeed;
cvar_t *s_alMinDistance;
cvar_t *s_alMaxDistance;
cvar_t *s_alRolloff;
cvar_t *s_alGraceDistance;
cvar_t *s_alDriver;
cvar_t *s_alDevice;
cvar_t *s_alInputDevice;
cvar_t *s_alAvailableDevices;
cvar_t *s_alAvailableInputDevices;
cvar_t *s_alTalkAnims;
static qboolean enumeration_ext = qfalse;
static qboolean enumeration_all_ext = qfalse;
#ifdef USE_VOIP
static qboolean capture_ext = qfalse;
#endif
/*
=================
S_AL_Format
=================
*/
static
ALuint S_AL_Format(int width, int channels)
{
ALuint format = AL_FORMAT_MONO16;
// Work out format
if(width == 1)
{
if(channels == 1)
format = AL_FORMAT_MONO8;
else if(channels == 2)
format = AL_FORMAT_STEREO8;
}
else if(width == 2)
{
if(channels == 1)
format = AL_FORMAT_MONO16;
else if(channels == 2)
format = AL_FORMAT_STEREO16;
}
return format;
}
/*
=================
S_AL_ErrorMsg
=================
*/
static const char *S_AL_ErrorMsg(ALenum error)
{
switch(error)
{
case AL_NO_ERROR:
return "No error";
case AL_INVALID_NAME:
return "Invalid name";
case AL_INVALID_ENUM:
return "Invalid enumerator";
case AL_INVALID_VALUE:
return "Invalid value";
case AL_INVALID_OPERATION:
return "Invalid operation";
case AL_OUT_OF_MEMORY:
return "Out of memory";
default:
return "Unknown error";
}
}
/*
=================
S_AL_ClearError
=================
*/
static void S_AL_ClearError( qboolean quiet )
{
int error = qalGetError();
if( quiet )
return;
if(error != AL_NO_ERROR)
{
Com_DPrintf(S_COLOR_YELLOW "WARNING: unhandled AL error: %s\n",
S_AL_ErrorMsg(error));
}
}
//===========================================================================
typedef struct alSfx_s
{
char filename[MAX_QPATH];
ALuint buffer; // OpenAL buffer
snd_info_t info; // information for this sound like rate, sample count..
qboolean isDefault; // Couldn't be loaded - use default FX
qboolean isDefaultChecked; // Sound has been check if it isDefault
qboolean inMemory; // Sound is stored in memory
qboolean isLocked; // Sound is locked (can not be unloaded)
int lastUsedTime; // Time last used
int loopCnt; // number of loops using this sfx
int loopActiveCnt; // number of playing loops using this sfx
int masterLoopSrc; // All other sources looping this buffer are synced to this master src
} alSfx_t;
static qboolean alBuffersInitialised = qfalse;
// Sound effect storage, data structures
#define MAX_SFX 4096
static alSfx_t knownSfx[MAX_SFX];
static sfxHandle_t numSfx = 0;
static sfxHandle_t default_sfx;
/*
=================
S_AL_BufferFindFree
Find a free handle
=================
*/
static sfxHandle_t S_AL_BufferFindFree( void )
{
int i;
for(i = 0; i < MAX_SFX; i++)
{
// Got one
if(knownSfx[i].filename[0] == '\0')
{
if(i >= numSfx)
numSfx = i + 1;
return i;
}
}
// Shit...
Com_Error(ERR_FATAL, "S_AL_BufferFindFree: No free sound handles");
return -1;
}
/*
=================
S_AL_BufferFind
Find a sound effect if loaded, set up a handle otherwise
=================
*/
static sfxHandle_t S_AL_BufferFind(const char *filename)
{
// Look it up in the table
sfxHandle_t sfx = -1;
int i;
if ( !filename ) {
//Com_Error( ERR_FATAL, "Sound name is NULL" );
filename = "*default*";
}
if ( !filename[0] ) {
//Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is empty\n" );
filename = "*default*";
}
if ( strlen( filename ) >= MAX_QPATH ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is too long: %s\n", filename );
return 0;
}
for(i = 0; i < numSfx; i++)
{
if(!Q_stricmp(knownSfx[i].filename, filename))
{
sfx = i;
break;
}
}
// Not found in table?
if(sfx == -1)
{
alSfx_t *ptr;
sfx = S_AL_BufferFindFree();
// Clear and copy the filename over
ptr = &knownSfx[sfx];
memset(ptr, 0, sizeof(*ptr));
ptr->masterLoopSrc = -1;
strcpy(ptr->filename, filename);
}
// Return the handle
return sfx;
}
/*
=================
S_AL_BufferUseDefault
=================
*/
static void S_AL_BufferUseDefault(sfxHandle_t sfx)
{
if(sfx == default_sfx)
Com_Error(ERR_FATAL, "Can't load default sound effect %s", knownSfx[sfx].filename);
// Com_Printf( S_COLOR_YELLOW "WARNING: Using default sound for %s\n", knownSfx[sfx].filename);
knownSfx[sfx].isDefault = qtrue;
knownSfx[sfx].buffer = knownSfx[default_sfx].buffer;
}
/*
=================
S_AL_BufferUnload
=================
*/
static void S_AL_BufferUnload(sfxHandle_t sfx)
{
if(knownSfx[sfx].filename[0] == '\0')
return;
if(!knownSfx[sfx].inMemory)
return;
// Delete it
S_AL_ClearError( qfalse );
qalDeleteBuffers(1, &knownSfx[sfx].buffer);
if(qalGetError() != AL_NO_ERROR)
Com_Printf( S_COLOR_RED "ERROR: Can't delete sound buffer for %s\n",
knownSfx[sfx].filename);
knownSfx[sfx].inMemory = qfalse;
}
/*
=================
S_AL_BufferEvict
=================
*/
static qboolean S_AL_BufferEvict( void )
{
int i, oldestBuffer = -1;
int oldestTime = Sys_Milliseconds( );
for( i = 0; i < numSfx; i++ )
{
if( !knownSfx[ i ].filename[ 0 ] )
continue;
if( !knownSfx[ i ].inMemory )
continue;
if( knownSfx[ i ].lastUsedTime < oldestTime )
{
oldestTime = knownSfx[ i ].lastUsedTime;
oldestBuffer = i;
}
}
if( oldestBuffer >= 0 )
{
S_AL_BufferUnload( oldestBuffer );
return qtrue;
}
else
return qfalse;
}
/*
=================
S_AL_GenBuffers
=================
*/
static qboolean S_AL_GenBuffers(ALsizei numBuffers, ALuint *buffers, const char *name)
{
ALenum error;
S_AL_ClearError( qfalse );
qalGenBuffers( numBuffers, buffers );
error = qalGetError();
// If we ran out of buffers, start evicting the least recently used sounds
while( error == AL_INVALID_VALUE )
{
if( !S_AL_BufferEvict( ) )
{
Com_Printf( S_COLOR_RED "ERROR: Out of audio buffers\n");
return qfalse;
}
// Try again
S_AL_ClearError( qfalse );
qalGenBuffers( numBuffers, buffers );
error = qalGetError();
}
if( error != AL_NO_ERROR )
{
Com_Printf( S_COLOR_RED "ERROR: Can't create a sound buffer for %s - %s\n",
name, S_AL_ErrorMsg(error));
return qfalse;
}
return qtrue;
}
/*
=================
S_AL_BufferLoad
=================
*/
static void S_AL_BufferLoad(sfxHandle_t sfx, qboolean cache)
{
ALenum error;
ALuint format;
void *data;
snd_info_t info;
alSfx_t *curSfx = &knownSfx[sfx];
// Nothing?
if(curSfx->filename[0] == '\0')
return;
// Player SFX
if(curSfx->filename[0] == '*')
return;
// Already done?
if((curSfx->inMemory) || (curSfx->isDefault) || (!cache && curSfx->isDefaultChecked))
return;
// Try to load
data = S_CodecLoad(curSfx->filename, &info);
if(!data)
{
S_AL_BufferUseDefault(sfx);
return;
}
curSfx->isDefaultChecked = qtrue;
if (!cache)
{
// Don't create AL cache
Hunk_FreeTempMemory(data);
return;
}
format = S_AL_Format(info.width, info.channels);
// Create a buffer
if (!S_AL_GenBuffers(1, &curSfx->buffer, curSfx->filename))
{
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
return;
}
// Fill the buffer
if( info.size == 0 )
{
// We have no data to buffer, so buffer silence
byte dummyData[ 2 ] = { 0 };
qalBufferData(curSfx->buffer, AL_FORMAT_MONO16, (void *)dummyData, 2, 22050);
}
else
qalBufferData(curSfx->buffer, format, data, info.size, info.rate);
error = qalGetError();
// If we ran out of memory, start evicting the least recently used sounds
while(error == AL_OUT_OF_MEMORY)
{
if( !S_AL_BufferEvict( ) )
{
qalDeleteBuffers(1, &curSfx->buffer);
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
Com_Printf( S_COLOR_RED "ERROR: Out of memory loading %s\n", curSfx->filename);
return;
}
// Try load it again
qalBufferData(curSfx->buffer, format, data, info.size, info.rate);
error = qalGetError();
}
// Some other error condition
if(error != AL_NO_ERROR)
{
qalDeleteBuffers(1, &curSfx->buffer);
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
Com_Printf( S_COLOR_RED "ERROR: Can't fill sound buffer for %s - %s\n",
curSfx->filename, S_AL_ErrorMsg(error));
return;
}
curSfx->info = info;
// Free the memory
Hunk_FreeTempMemory(data);
// Woo!
curSfx->inMemory = qtrue;
}
/*
=================
S_AL_BufferUse
=================
*/
static
void S_AL_BufferUse(sfxHandle_t sfx)
{
if(knownSfx[sfx].filename[0] == '\0')
return;
if((!knownSfx[sfx].inMemory) && (!knownSfx[sfx].isDefault))
S_AL_BufferLoad(sfx, qtrue);
knownSfx[sfx].lastUsedTime = Sys_Milliseconds();
}
/*
=================
S_AL_BufferInit
=================
*/
static
qboolean S_AL_BufferInit( void )
{
if(alBuffersInitialised)
return qtrue;
// Clear the hash table, and SFX table
memset(knownSfx, 0, sizeof(knownSfx));
numSfx = 0;
// Load the default sound, and lock it
default_sfx = S_AL_BufferFind( "***DEFAULT***" );
S_AL_BufferUse(default_sfx);
knownSfx[default_sfx].isLocked = qtrue;
// All done
alBuffersInitialised = qtrue;
return qtrue;
}
/*
=================
S_AL_BufferShutdown
=================
*/
static
void S_AL_BufferShutdown( void )
{
int i;
if(!alBuffersInitialised)
return;
// Unlock the default sound effect
knownSfx[default_sfx].isLocked = qfalse;
// Free all used effects
for(i = 0; i < numSfx; i++)
S_AL_BufferUnload(i);
// Clear the tables
numSfx = 0;
// All undone
alBuffersInitialised = qfalse;
}
/*
=================
S_AL_RegisterSound
=================
*/
static
sfxHandle_t S_AL_RegisterSound( const char *sample, qboolean compressed )
{
sfxHandle_t sfx = S_AL_BufferFind(sample);
if((!knownSfx[sfx].inMemory) && (!knownSfx[sfx].isDefault))
S_AL_BufferLoad(sfx, s_alPrecache->integer);
knownSfx[sfx].lastUsedTime = Com_Milliseconds();
if (knownSfx[sfx].isDefault) {
return 0;
}
return sfx;
}
/*
=================
S_AL_BufferGet
Return's a sfx's buffer
=================
*/
static
ALuint S_AL_BufferGet(sfxHandle_t sfx)
{
return knownSfx[sfx].buffer;
}
//===========================================================================
typedef struct src_s
{
ALuint alSource; // OpenAL source object
sfxHandle_t sfx; // Sound effect in use
int lastUsedTime; // Last time used
alSrcPriority_t priority; // Priority
int entity; // Owning entity (-1 if none)
int channel; // Associated channel (-1 if none)
qboolean isActive; // Is this source currently in use?
qboolean isPlaying; // Is this source currently playing, or stopped?
qboolean isLocked; // This is locked (un-allocatable)
qboolean isLooping; // Is this a looping effect (attached to an entity)
qboolean isTracking; // Is this object tracking its owner
qboolean isStream; // Is this source a stream
float curGain; // gain employed if source is within maxdistance.
float scaleGain; // Last gain value for this source. 0 if muted.
float lastTimePos; // On stopped loops, the last position in the buffer
int lastSampleTime; // Time when this was stopped
vec3_t loopSpeakerPos; // Origin of the loop speaker
qboolean local; // Is this local (relative to the cam)
int flags; // flags from StartSoundEx
} src_t;
#ifdef __APPLE__
#define MAX_SRC 128
#else
#define MAX_SRC 256
#endif
static src_t srcList[MAX_SRC];
static int srcCount = 0;
static int srcActiveCnt = 0;
static qboolean alSourcesInitialised = qfalse;
static int lastListenerNumber = -1;
static vec3_t lastListenerOrigin = { 0.0f, 0.0f, 0.0f };
typedef struct sentity_s
{
vec3_t origin;
qboolean srcAllocated; // If a src_t has been allocated to this entity
int srcIndex;
qboolean loopAddedThisFrame;
alSrcPriority_t loopPriority;
sfxHandle_t loopSfx;
qboolean startLoopingSound;
} sentity_t;
static sentity_t entityList[MAX_GENTITIES];
/*
=================
S_AL_SanitiseVector
=================
*/
#define S_AL_SanitiseVector(v) _S_AL_SanitiseVector(v,__LINE__)
static void _S_AL_SanitiseVector( vec3_t v, int line )
{
if( Q_isnan( v[ 0 ] ) || Q_isnan( v[ 1 ] ) || Q_isnan( v[ 2 ] ) )
{
Com_DPrintf( S_COLOR_YELLOW "WARNING: vector with one or more NaN components "
"being passed to OpenAL at %s:%d -- zeroing\n", __FILE__, line );
VectorClear( v );
}
}
/*
=================
S_AL_Gain
Set gain to 0 if muted, otherwise set it to given value.
=================
*/
static void S_AL_Gain(ALuint source, float gainval)
{
if(s_muted->integer)
qalSourcef(source, AL_GAIN, 0.0f);
else
qalSourcef(source, AL_GAIN, gainval);
}
/*
=================
S_AL_ScaleGain
Adapt the gain if necessary to get a quicker fadeout when the source is too far away.
=================
*/
static void S_AL_ScaleGain(src_t *chksrc, vec3_t origin)
{
float distance;
if(!chksrc->local)
distance = Distance(origin, lastListenerOrigin);
// If we exceed a certain distance, scale the gain linearly until the sound
// vanishes into nothingness.
if(!chksrc->local && (distance -= s_alMaxDistance->value) > 0)
{
float scaleFactor;
if(distance >= s_alGraceDistance->value)
scaleFactor = 0.0f;
else
scaleFactor = 1.0f - distance / s_alGraceDistance->value;
scaleFactor *= chksrc->curGain;
if(chksrc->scaleGain != scaleFactor)
{
chksrc->scaleGain = scaleFactor;
S_AL_Gain(chksrc->alSource, chksrc->scaleGain);
}
}
else if(chksrc->scaleGain != chksrc->curGain)
{
chksrc->scaleGain = chksrc->curGain;
S_AL_Gain(chksrc->alSource, chksrc->scaleGain);
}
}
/*
=================
S_AL_HearingThroughEntity
Also see S_Base_HearingThroughEntity
=================
*/
static qboolean S_AL_HearingThroughEntity( int entityNum )
{
float distanceSq;
if( lastListenerNumber == entityNum )
{
// This is an outrageous hack to detect
// whether or not the player is rendering in third person or not. We can't
// ask the renderer because the renderer has no notion of entities and we
// can't ask cgame since that would involve changing the API and hence mod
// compatibility. I don't think there is any way around this, but I'll leave
// the FIXME just in case anyone has a bright idea.
distanceSq = DistanceSquared(
entityList[ entityNum ].origin,
lastListenerOrigin );
if( distanceSq > THIRD_PERSON_THRESHOLD_SQ )
return qfalse; //we're the player, but third person
else
return qtrue; //we're the player
}
else
return qfalse; //not the player
}
/*
=================
S_AL_SrcInit
=================
*/
static
qboolean S_AL_SrcInit( void )
{
int i;
int limit;
// Clear the sources data structure
memset(srcList, 0, sizeof(srcList));
srcCount = 0;
srcActiveCnt = 0;
// Cap s_alSources to MAX_SRC
limit = s_alSources->integer;
if(limit > MAX_SRC)
limit = MAX_SRC;
else if(limit < 16)
limit = 16;
S_AL_ClearError( qfalse );
// Allocate as many sources as possible
for(i = 0; i < limit; i++)
{
qalGenSources(1, &srcList[i].alSource);
if(qalGetError() != AL_NO_ERROR)
break;
srcCount++;
}
alSourcesInitialised = qtrue;
return qtrue;
}
/*
=================
S_AL_SrcShutdown
=================
*/
static
void S_AL_SrcShutdown( void )
{
int i;
src_t *curSource;
if(!alSourcesInitialised)
return;
// Destroy all the sources
for(i = 0; i < srcCount; i++)
{
curSource = &srcList[i];
if(curSource->isLocked)
{
srcList[i].isLocked = qfalse;
Com_DPrintf( S_COLOR_YELLOW "WARNING: Source %d was locked\n", i);
}
if(curSource->entity > 0)
entityList[curSource->entity].srcAllocated = qfalse;
qalSourceStop(srcList[i].alSource);
qalDeleteSources(1, &srcList[i].alSource);
}
memset(srcList, 0, sizeof(srcList));
memset( s_entityTalkAmplitude, 0, sizeof( s_entityTalkAmplitude ) );
alSourcesInitialised = qfalse;
}
/*
=================
S_AL_SrcSetup
=================
*/
static void S_AL_SrcSetup(srcHandle_t src, sfxHandle_t sfx, alSrcPriority_t priority,
int entity, int channel, int flags, qboolean local)
{
src_t *curSource;
// Set up src struct
curSource = &srcList[src];
curSource->lastUsedTime = Sys_Milliseconds();
curSource->sfx = sfx;
curSource->priority = priority;
curSource->entity = entity;
curSource->channel = channel;
curSource->isPlaying = qfalse;
curSource->isLocked = qfalse;
curSource->isLooping = qfalse;
curSource->isTracking = qfalse;
curSource->isStream = qfalse;
curSource->curGain = s_alGain->value * s_volume->value;
curSource->scaleGain = curSource->curGain;
curSource->local = local;
curSource->flags = flags;
// Set up OpenAL source
if(sfx >= 0)
{
// Mark the SFX as used, and grab the raw AL buffer
S_AL_BufferUse(sfx);
qalSourcei(curSource->alSource, AL_BUFFER, S_AL_BufferGet(sfx));
}
qalSourcef(curSource->alSource, AL_PITCH, 1.0f);
S_AL_Gain(curSource->alSource, curSource->curGain);
qalSourcefv(curSource->alSource, AL_POSITION, vec3_origin);
qalSourcefv(curSource->alSource, AL_VELOCITY, vec3_origin);
qalSourcei(curSource->alSource, AL_LOOPING, AL_FALSE);
qalSourcef(curSource->alSource, AL_REFERENCE_DISTANCE, s_alMinDistance->value);
if(local)
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_TRUE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, 0.0f);
}
else
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_FALSE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
}
}
/*
=================
S_AL_SaveLoopPos
Remove given source as loop master if it is the master and hand off master status to another source in this case.
=================
*/
static void S_AL_SaveLoopPos(src_t *dest, ALuint alSource)
{
int error;
S_AL_ClearError( qfalse );
qalGetSourcef(alSource, AL_SEC_OFFSET, &dest->lastTimePos);
if((error = qalGetError()) != AL_NO_ERROR)
{
// Old OpenAL implementations don't support AL_SEC_OFFSET
if(error != AL_INVALID_ENUM)
{
Com_Printf(S_COLOR_YELLOW "WARNING: Could not get time offset for alSource %d: %s\n",
alSource, S_AL_ErrorMsg(error));
}
dest->lastTimePos = -1;
}
else
dest->lastSampleTime = Sys_Milliseconds();
}
/*
=================
S_AL_NewLoopMaster
Remove given source as loop master if it is the master and hand off master status to another source in this case.
=================
*/
static void S_AL_NewLoopMaster(src_t *rmSource, qboolean iskilled)
{
int index;
src_t *curSource = NULL;
alSfx_t *curSfx;
curSfx = &knownSfx[rmSource->sfx];
if(rmSource->isPlaying)
curSfx->loopActiveCnt--;
if(iskilled)
curSfx->loopCnt--;
if(curSfx->loopCnt)
{
if(rmSource->priority == SRCPRI_ENTITY)
{
if(!iskilled && rmSource->isPlaying)
{
// only sync ambient loops...
// It makes more sense to have sounds for weapons/projectiles unsynced
S_AL_SaveLoopPos(rmSource, rmSource->alSource);
}
}
else if(rmSource == &srcList[curSfx->masterLoopSrc])
{
int firstInactive = -1;
// Only if rmSource was the master and if there are still playing loops for
// this sound will we need to find a new master.
if(iskilled || curSfx->loopActiveCnt)
{
for(index = 0; index < srcCount; index++)
{
curSource = &srcList[index];
if(curSource->sfx == rmSource->sfx && curSource != rmSource &&
curSource->isActive && curSource->isLooping && curSource->priority == SRCPRI_AMBIENT)
{
if(curSource->isPlaying)
{
curSfx->masterLoopSrc = index;
break;
}
else if(firstInactive < 0)
firstInactive = index;
}
}
}
if(!curSfx->loopActiveCnt)
{
if(firstInactive < 0)
{
if(iskilled)
{
curSfx->masterLoopSrc = -1;
return;
}
else
curSource = rmSource;
}
else
curSource = &srcList[firstInactive];
if(rmSource->isPlaying)
{
// this was the last not stopped source, save last sample position + time
S_AL_SaveLoopPos(curSource, rmSource->alSource);
}
else
{
// second case: all loops using this sound have stopped due to listener being of of range,
// and now the inactive master gets deleted. Just move over the soundpos settings to the
// new master.
curSource->lastTimePos = rmSource->lastTimePos;
curSource->lastSampleTime = rmSource->lastSampleTime;
}
}
}
}
else
curSfx->masterLoopSrc = -1;
}
/*
=================
S_AL_SrcKill
=================
*/
static void S_AL_SrcKill(srcHandle_t src)
{
src_t *curSource = &srcList[src];
// I'm not touching it. Unlock it first.
if(curSource->isLocked)
return;
// Remove the entity association and loop master status
if(curSource->isLooping)
{
curSource->isLooping = qfalse;
if(curSource->entity != -1)
{
sentity_t *curEnt = &entityList[curSource->entity];
curEnt->srcAllocated = qfalse;
curEnt->srcIndex = -1;
curEnt->loopAddedThisFrame = qfalse;
curEnt->startLoopingSound = qfalse;
}
S_AL_NewLoopMaster(curSource, qtrue);
}
// Stop it if it's playing
if(curSource->isPlaying)
{
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
// Detach any buffers
qalSourcei(curSource->alSource, AL_BUFFER, 0);
curSource->sfx = 0;
curSource->lastUsedTime = 0;
curSource->priority = 0;
curSource->entity = -1;
curSource->channel = -1;
if(curSource->isActive)
{
curSource->isActive = qfalse;
srcActiveCnt--;
}
curSource->isLocked = qfalse;
curSource->isTracking = qfalse;
curSource->local = qfalse;
}
/*
=================
S_AL_SrcAlloc
=================
*/
static
srcHandle_t S_AL_SrcAlloc( sfxHandle_t sfx, alSrcPriority_t priority, int entnum, int channel, int flags )
{
int i;
int empty = -1;
int weakest = -1;
int weakest_time = Sys_Milliseconds();
int weakest_pri = 999;
float weakest_gain = 1000.0;
qboolean weakest_isplaying = qtrue;
int weakest_numloops = 0;
src_t *curSource;
qboolean cutDuplicateSound = qfalse;
for(i = 0; i < srcCount; i++)
{
curSource = &srcList[i];
// If it's locked, we aren't even going to look at it
if(curSource->isLocked)
continue;
// Is it empty or not?
if(!curSource->isActive)
{
if (empty == -1)
empty = i;
break;
}
if(curSource->isPlaying)
{
if(weakest_isplaying && curSource->priority < priority &&
(curSource->priority < weakest_pri ||
(!curSource->isLooping && (curSource->scaleGain < weakest_gain || curSource->lastUsedTime < weakest_time))))
{
// If it has lower priority, is fainter or older, flag it as weak
// the last two values are only compared if it's not a looping sound, because we want to prevent two
// loops (loops are added EVERY frame) fighting for a slot
weakest_pri = curSource->priority;
weakest_time = curSource->lastUsedTime;
weakest_gain = curSource->scaleGain;
weakest = i;
}
}
else
{
weakest_isplaying = qfalse;
if(weakest < 0 ||
knownSfx[curSource->sfx].loopCnt > weakest_numloops ||
curSource->priority < weakest_pri ||
curSource->lastUsedTime < weakest_time)
{
// Sources currently not playing of course have lowest priority
// also try to always keep at least one loop master for every loop sound
weakest_pri = curSource->priority;
weakest_time = curSource->lastUsedTime;
weakest_numloops = knownSfx[curSource->sfx].loopCnt;
weakest = i;
}
}
// shut off other sounds on this channel if necessary
if((curSource->entity == entnum) && curSource->sfx > 0 && (curSource->channel == channel))
{
// currently apply only to non-looping sounds
if ( curSource->isLooping ) {
continue;
}
// cutoff all on channel
if ( flags & SND_CUTOFF_ALL ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
if ( curSource->flags & SND_NOCUT ) {
continue;
}
// RF, let client voice sounds be overwritten
if ( entnum < MAX_CLIENTS && curSource->channel != -1 && curSource->channel != CHAN_AUTO && curSource->channel != CHAN_WEAPON ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
// cutoff sounds that expect to be overwritten
if ( curSource->flags & SND_OKTOCUT ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
// cutoff 'weak' sounds on channel
if ( flags & SND_CUTOFF ) {
if ( curSource->flags & SND_REQUESTCUT ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
}
// re-use channel if applicable
if ( curSource->channel != -1 && curSource->channel != CHAN_AUTO && curSource->sfx == sfx && !cutDuplicateSound ) {
cutDuplicateSound = qtrue;
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
}
}
if(empty == -1)
empty = weakest;
if(empty >= 0)
{
S_AL_SrcKill(empty);
srcList[empty].isActive = qtrue;
srcActiveCnt++;
}
return empty;
}
/*
=================
S_AL_SrcFind
Finds an active source with matching entity and channel numbers
Returns -1 if there isn't one
=================
*/
#if 0
static
srcHandle_t S_AL_SrcFind(int entnum, int channel)
{
int i;
for(i = 0; i < srcCount; i++)
{
if(!srcList[i].isActive)
continue;
if((srcList[i].entity == entnum) && (srcList[i].channel == channel))
return i;
}
return -1;
}
#endif
/*
=================
S_AL_SrcLock
Locked sources will not be automatically reallocated or managed
=================
*/
static
void S_AL_SrcLock(srcHandle_t src)
{
srcList[src].isLocked = qtrue;
}
/*
=================
S_AL_SrcUnlock
Once unlocked, the source may be reallocated again
=================
*/
static
void S_AL_SrcUnlock(srcHandle_t src)
{
srcList[src].isLocked = qfalse;
}
/*
=================
S_AL_UpdateEntityPosition
=================
*/
static
void S_AL_UpdateEntityPosition( int entityNum, const vec3_t origin )
{
vec3_t sanOrigin;
VectorCopy( origin, sanOrigin );
S_AL_SanitiseVector( sanOrigin );
if ( entityNum < 0 || entityNum >= MAX_GENTITIES )
Com_Error( ERR_DROP, "S_UpdateEntityPosition: bad entitynum %i", entityNum );
VectorCopy( sanOrigin, entityList[entityNum].origin );
}
/*
=================
S_AL_CheckInput
Check whether input values from mods are out of range.
Necessary for i.g. Western Quake3 mod which is buggy.
=================
*/
static qboolean S_AL_CheckInput(int entityNum, sfxHandle_t sfx)
{
if (entityNum < 0 || entityNum >= MAX_GENTITIES)
Com_Error(ERR_DROP, "ERROR: S_AL_CheckInput: bad entitynum %i", entityNum);
if (sfx < 0 || sfx >= numSfx)
{
Com_Printf(S_COLOR_RED "ERROR: S_AL_CheckInput: handle %i out of range\n", sfx);
return qtrue;
}
return qfalse;
}
/*
=================
S_AL_StartLocalSound
Play a local (non-spatialized) sound effect
=================
*/
static
void S_AL_StartLocalSound(sfxHandle_t sfx, int channel)
{
srcHandle_t src;
if(S_AL_CheckInput(0, sfx))
return;
// Try to grab a source
src = S_AL_SrcAlloc(sfx, SRCPRI_LOCAL, -1, channel, 0);
if(src == -1)
return;
// Set up the effect
S_AL_SrcSetup(src, sfx, SRCPRI_LOCAL, -1, channel, 0, qtrue);
// Start it playing
srcList[src].isPlaying = qtrue;
qalSourcePlay(srcList[src].alSource);
}
/*
=================
S_AL_MainStartSound
Play a one-shot sound effect
=================
*/
static void S_AL_MainStartSound( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx, int flags )
{
vec3_t sorigin;
srcHandle_t src;
src_t *curSource;
if(origin)
{
if(S_AL_CheckInput(0, sfx))
return;
VectorCopy(origin, sorigin);
}
else
{
if(S_AL_CheckInput(entnum, sfx))
return;
if(S_AL_HearingThroughEntity(entnum))
{
S_AL_StartLocalSound(sfx, entchannel);
return;
}
VectorCopy(entityList[entnum].origin, sorigin);
}
S_AL_SanitiseVector(sorigin);
if((srcActiveCnt > 5 * srcCount / 3) &&
(DistanceSquared(sorigin, lastListenerOrigin) >=
(s_alMaxDistance->value + s_alGraceDistance->value) * (s_alMaxDistance->value + s_alGraceDistance->value)))
{
// We're getting tight on sources and source is not within hearing distance so don't add it
return;
}
// Talk anims default to ZERO amplitude
if ( entchannel == CHAN_VOICE )
memset( s_entityTalkAmplitude, 0, sizeof( s_entityTalkAmplitude ) );
if ( entnum < MAX_CLIENTS && entchannel == CHAN_VOICE )
{
s_entityTalkAmplitude[entnum] = (unsigned char)(s_alTalkAnims->integer);
}
// Try to grab a source
src = S_AL_SrcAlloc(sfx, SRCPRI_ONESHOT, entnum, entchannel, flags);
if(src == -1)
return;
S_AL_SrcSetup(src, sfx, SRCPRI_ONESHOT, entnum, entchannel, flags, qfalse);
curSource = &srcList[src];
if(!origin)
curSource->isTracking = qtrue;
qalSourcefv(curSource->alSource, AL_POSITION, sorigin );
S_AL_ScaleGain(curSource, sorigin);
// Start it playing
curSource->isPlaying = qtrue;
qalSourcePlay(curSource->alSource);
}
/*
=================
S_AL_StartSound
=================
*/
static void S_AL_StartSound( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx )
{
S_AL_MainStartSound( origin, entnum, entchannel, sfx, 0 );
}
/*
=================
S_AL_StartSoundEx
=================
*/
static void S_AL_StartSoundEx( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx, int flags )
{
// RF, we have lots of NULL sounds using up valuable channels, so just ignore them
if ( !sfx && entchannel != CHAN_WEAPON ) { // let null weapon sounds try to play. they kill any weapon sounds playing when a guy dies
return;
}
// RF, make the call now, or else we could override following streaming sounds in the same frame, due to the delay
S_AL_MainStartSound( origin, entnum, entchannel, sfx, flags );
}
/*
=================
S_AL_ClearLoopingSounds
=================
*/
static
void S_AL_ClearLoopingSounds( qboolean killall )
{
int i;
for(i = 0; i < srcCount; i++)
{
if((srcList[i].isLooping) && (srcList[i].entity != -1))
entityList[srcList[i].entity].loopAddedThisFrame = qfalse;
}
}
/*
=================
S_AL_SrcLoop
=================
*/
static void S_AL_SrcLoop( alSrcPriority_t priority, sfxHandle_t sfx,
const vec3_t origin, const vec3_t velocity, int entityNum, int volume )
{
int src;
sentity_t *sent = &entityList[ entityNum ];
src_t *curSource;
vec3_t sorigin, svelocity;
if( entityNum < 0 || entityNum >= MAX_GENTITIES )
return;
if(S_AL_CheckInput(entityNum, sfx))
return;
// Do we need to allocate a new source for this entity
if( !sent->srcAllocated )
{
// Try to get a channel
src = S_AL_SrcAlloc( sfx, priority, entityNum, -1, 0 );
if( src == -1 )
{
Com_DPrintf( S_COLOR_YELLOW "WARNING: Failed to allocate source "
"for loop sfx %d on entity %d\n", sfx, entityNum );
return;
}
curSource = &srcList[src];
sent->startLoopingSound = qtrue;
curSource->lastTimePos = -1.0;
curSource->lastSampleTime = Sys_Milliseconds();
}
else
{
src = sent->srcIndex;
curSource = &srcList[src];
}
sent->srcAllocated = qtrue;
sent->srcIndex = src;
sent->loopPriority = priority;
sent->loopSfx = sfx;
// If this is not set then the looping sound is stopped.
sent->loopAddedThisFrame = qtrue;
// UGH
// These lines should be called via S_AL_SrcSetup, but we
// can't call that yet as it buffers sfxes that may change
// with subsequent calls to S_AL_SrcLoop
curSource->entity = entityNum;
curSource->isLooping = qtrue;
if( S_AL_HearingThroughEntity( entityNum ) )
{
curSource->local = qtrue;
VectorClear(sorigin);
if ( volume > 255 ) {
volume = 255;
} else if ( volume < 0 ) {
volume = 0;
}
qalSourcefv(curSource->alSource, AL_POSITION, sorigin);
qalSourcefv(curSource->alSource, AL_VELOCITY, vec3_origin);
S_AL_Gain(curSource->alSource, volume / 255.0f);
}
else
{
curSource->local = qfalse;
if(origin)
VectorCopy(origin, sorigin);
else
VectorCopy(sent->origin, sorigin);
S_AL_SanitiseVector(sorigin);
VectorCopy(sorigin, curSource->loopSpeakerPos);
if(velocity)
{
VectorCopy(velocity, svelocity);
S_AL_SanitiseVector(svelocity);
}
else
VectorClear(svelocity);
qalSourcefv(curSource->alSource, AL_POSITION, (ALfloat *) sorigin);
qalSourcefv(curSource->alSource, AL_VELOCITY, (ALfloat *) svelocity);
}
}
/*
=================
S_AL_AddLoopingSound
=================
*/
static void S_AL_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, const int range, sfxHandle_t sfx, int volume)
{
S_AL_SrcLoop(SRCPRI_ENTITY, sfx, origin, velocity, entityNum, volume);
}
/*
=================
S_AL_AddRealLoopingSound
=================
*/
static void S_AL_AddRealLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, const int range, sfxHandle_t sfx)
{
S_AL_SrcLoop(SRCPRI_AMBIENT, sfx, origin, velocity, entityNum, 255);
}
/*
=================
S_AL_StopLoopingSound
=================
*/
static
void S_AL_StopLoopingSound(int entityNum )
{
if(entityList[entityNum].srcAllocated)
S_AL_SrcKill(entityList[entityNum].srcIndex);
}
/*
=================
S_AL_SrcUpdate
Update state (move things around, manage sources, and so on)
=================
*/
static
void S_AL_SrcUpdate( void )
{
int i;
int entityNum;
ALint state;
src_t *curSource;
for(i = 0; i < srcCount; i++)
{
entityNum = srcList[i].entity;
curSource = &srcList[i];
if(curSource->isLocked)
continue;
if(!curSource->isActive)
continue;
// Update source parameters
if((s_alGain->modified) || (s_volume->modified))
curSource->curGain = s_alGain->value * s_volume->value;
if((s_alRolloff->modified) && (!curSource->local))
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
if(s_alMinDistance->modified)
qalSourcef(curSource->alSource, AL_REFERENCE_DISTANCE, s_alMinDistance->value);
if(curSource->isLooping)
{
sentity_t *sent = &entityList[ entityNum ];
// If a looping effect hasn't been touched this frame, pause or kill it
if(sent->loopAddedThisFrame)
{
alSfx_t *curSfx;
// The sound has changed without an intervening removal
if(curSource->isActive && !sent->startLoopingSound &&
curSource->sfx != sent->loopSfx)
{
S_AL_NewLoopMaster(curSource, qtrue);
curSource->isPlaying = qfalse;
qalSourceStop(curSource->alSource);
qalSourcei(curSource->alSource, AL_BUFFER, 0);
sent->startLoopingSound = qtrue;
}
// The sound hasn't been started yet
if(sent->startLoopingSound)
{
S_AL_SrcSetup(i, sent->loopSfx, sent->loopPriority,
entityNum, -1, 0, curSource->local);
curSource->isLooping = qtrue;
knownSfx[curSource->sfx].loopCnt++;
sent->startLoopingSound = qfalse;
}
curSfx = &knownSfx[curSource->sfx];
S_AL_ScaleGain(curSource, curSource->loopSpeakerPos);
if(!curSource->scaleGain)
{
if(curSource->isPlaying)
{
// Sound is mute, stop playback until we are in range again
S_AL_NewLoopMaster(curSource, qfalse);
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
else if(!curSfx->loopActiveCnt && curSfx->masterLoopSrc < 0)
curSfx->masterLoopSrc = i;
continue;
}
if(!curSource->isPlaying)
{
qalSourcei(curSource->alSource, AL_LOOPING, AL_TRUE);
curSource->isPlaying = qtrue;
qalSourcePlay(curSource->alSource);
if(curSource->priority == SRCPRI_AMBIENT)
{
// If there are other ambient looping sources with the same sound,
// make sure the sound of these sources are in sync.
if(curSfx->loopActiveCnt)
{
int offset, error;
// we already have a master loop playing, get buffer position.
S_AL_ClearError( qfalse );
qalGetSourcei(srcList[curSfx->masterLoopSrc].alSource, AL_SAMPLE_OFFSET, &offset);
if((error = qalGetError()) != AL_NO_ERROR)
{
if(error != AL_INVALID_ENUM)
{
Com_Printf(S_COLOR_YELLOW "WARNING: Cannot get sample offset from source %d: "
"%s\n", i, S_AL_ErrorMsg(error));
}
}
else
qalSourcei(curSource->alSource, AL_SAMPLE_OFFSET, offset);
}
else if(curSfx->loopCnt && curSfx->masterLoopSrc >= 0)
{
float secofs;
src_t *master = &srcList[curSfx->masterLoopSrc];
// This loop sound used to be played, but all sources are stopped. Use last sample position/time
// to calculate offset so the player thinks the sources continued playing while they were inaudible.
if(master->lastTimePos >= 0)
{
secofs = master->lastTimePos + (Sys_Milliseconds() - master->lastSampleTime) / 1000.0f;
secofs = fmodf(secofs, (float) curSfx->info.samples / curSfx->info.rate);
qalSourcef(curSource->alSource, AL_SEC_OFFSET, secofs);
}
// I be the master now
curSfx->masterLoopSrc = i;
}
else
curSfx->masterLoopSrc = i;
}
else if(curSource->lastTimePos >= 0)
{
float secofs;
// For unsynced loops (SRCPRI_ENTITY) just carry on playing as if the sound was never stopped
secofs = curSource->lastTimePos + (Sys_Milliseconds() - curSource->lastSampleTime) / 1000.0f;
secofs = fmodf(secofs, (float) curSfx->info.samples / curSfx->info.rate);
qalSourcef(curSource->alSource, AL_SEC_OFFSET, secofs);
}
curSfx->loopActiveCnt++;
}
// Update locality
if(curSource->local)
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_TRUE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, 0.0f);
}
else
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_FALSE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
}
}
else if(curSource->priority == SRCPRI_AMBIENT)
{
if(curSource->isPlaying)
{
S_AL_NewLoopMaster(curSource, qfalse);
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
}
else
S_AL_SrcKill(i);
continue;
}
if(!curSource->isStream)
{
// Check if it's done, and flag it
qalGetSourcei(curSource->alSource, AL_SOURCE_STATE, &state);
if(state == AL_STOPPED)
{
curSource->isPlaying = qfalse;
S_AL_SrcKill(i);
continue;
}
}
// Query relativity of source, don't move if it's true
qalGetSourcei(curSource->alSource, AL_SOURCE_RELATIVE, &state);
// See if it needs to be moved
if(curSource->isTracking && !state)
{
qalSourcefv(curSource->alSource, AL_POSITION, entityList[entityNum].origin);
S_AL_ScaleGain(curSource, entityList[entityNum].origin);
}
}
}
/*
=================
S_AL_SrcShutup
=================
*/
static
void S_AL_SrcShutup( void )
{
int i;
for(i = 0; i < srcCount; i++)
S_AL_SrcKill(i);
}
/*
=================
S_AL_SrcGet
=================
*/
static
ALuint S_AL_SrcGet(srcHandle_t src)
{
return srcList[src].alSource;
}
//===========================================================================
// Q3A cinematics use up to 12 buffers at once
#define MAX_STREAM_BUFFERS 20
static srcHandle_t streamSourceHandles[MAX_RAW_STREAMS];
static qboolean streamPlaying[MAX_RAW_STREAMS];
static ALuint streamSources[MAX_RAW_STREAMS];
static ALuint streamBuffers[MAX_RAW_STREAMS][MAX_STREAM_BUFFERS];
static int streamNumBuffers[MAX_RAW_STREAMS];
static int streamBufIndex[MAX_RAW_STREAMS];
/*
=================
S_AL_AllocateStreamChannel
=================
*/
static void S_AL_AllocateStreamChannel(int stream, int entityNum)
{
srcHandle_t cursrc;
ALuint alsrc;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(entityNum >= 0)
{
// This is a stream that tracks an entity
// Allocate a streamSource at normal priority
cursrc = S_AL_SrcAlloc(-1, SRCPRI_ENTITY, entityNum, 0, 0);
if(cursrc < 0)
return;
S_AL_SrcSetup(cursrc, -1, SRCPRI_ENTITY, entityNum, 0, 0, qfalse);
alsrc = S_AL_SrcGet(cursrc);
srcList[cursrc].isTracking = qtrue;
srcList[cursrc].isStream = qtrue;
}
else
{
// Unspatialized stream source
// Allocate a streamSource at high priority
cursrc = S_AL_SrcAlloc(-1, SRCPRI_STREAM, -2, 0, 0);
if(cursrc < 0)
return;
alsrc = S_AL_SrcGet(cursrc);
// Lock the streamSource so nobody else can use it, and get the raw streamSource
S_AL_SrcLock(cursrc);
// make sure that after unmuting the S_AL_Gain in S_Update() does not turn
// volume up prematurely for this source
srcList[cursrc].scaleGain = 0.0f;
// Set some streamSource parameters
qalSourcei (alsrc, AL_BUFFER, 0 );
qalSourcei (alsrc, AL_LOOPING, AL_FALSE );
qalSource3f(alsrc, AL_POSITION, 0.0, 0.0, 0.0);
qalSource3f(alsrc, AL_VELOCITY, 0.0, 0.0, 0.0);
qalSource3f(alsrc, AL_DIRECTION, 0.0, 0.0, 0.0);
qalSourcef (alsrc, AL_ROLLOFF_FACTOR, 0.0 );
qalSourcei (alsrc, AL_SOURCE_RELATIVE, AL_TRUE );
}
streamSourceHandles[stream] = cursrc;
streamSources[stream] = alsrc;
streamNumBuffers[stream] = 0;
streamBufIndex[stream] = 0;
}
/*
=================
S_AL_FreeStreamChannel
=================
*/
static void S_AL_FreeStreamChannel( int stream )
{
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
// Detach any buffers
qalSourcei(streamSources[stream], AL_BUFFER, 0);
// Delete the buffers
if (streamNumBuffers[stream] > 0) {
qalDeleteBuffers(streamNumBuffers[stream], streamBuffers[stream]);
streamNumBuffers[stream] = 0;
}
// Release the output streamSource
S_AL_SrcUnlock(streamSourceHandles[stream]);
S_AL_SrcKill(streamSourceHandles[stream]);
streamSources[stream] = 0;
streamSourceHandles[stream] = -1;
}
/*
=================
S_AL_RawSamples
=================
*/
static
void S_AL_RawSamples(int stream, int samples, int rate, int width, int channels, const byte *data, float volume, int entityNum)
{
int numBuffers;
ALuint buffer;
ALuint format;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
format = S_AL_Format( width, channels );
// Create the streamSource if necessary
if(streamSourceHandles[stream] == -1)
{
S_AL_AllocateStreamChannel(stream, entityNum);
// Failed?
if(streamSourceHandles[stream] == -1)
{
Com_Printf( S_COLOR_RED "ERROR: Can't allocate streaming streamSource\n");
return;
}
}
qalGetSourcei(streamSources[stream], AL_BUFFERS_QUEUED, &numBuffers);
if (numBuffers == MAX_STREAM_BUFFERS)
{
Com_DPrintf(S_COLOR_RED"WARNING: Steam dropping raw samples, reached MAX_STREAM_BUFFERS\n");
return;
}
// Allocate a new AL buffer if needed
if (numBuffers == streamNumBuffers[stream])
{
ALuint oldBuffers[MAX_STREAM_BUFFERS];
int i;
if (!S_AL_GenBuffers(1, &buffer, "stream"))
return;
Com_Memcpy(oldBuffers, &streamBuffers[stream], sizeof (oldBuffers));
// Reorder buffer array in order of oldest to newest
for ( i = 0; i < streamNumBuffers[stream]; ++i )
streamBuffers[stream][i] = oldBuffers[(streamBufIndex[stream] + i) % streamNumBuffers[stream]];
// Add the new buffer to end
streamBuffers[stream][streamNumBuffers[stream]] = buffer;
streamBufIndex[stream] = streamNumBuffers[stream];
streamNumBuffers[stream]++;
}
// Select next buffer in loop
buffer = streamBuffers[stream][ streamBufIndex[stream] ];
streamBufIndex[stream] = (streamBufIndex[stream] + 1) % streamNumBuffers[stream];
// Fill buffer
qalBufferData(buffer, format, (ALvoid *)data, (samples * width * channels), rate);
// Shove the data onto the streamSource
qalSourceQueueBuffers(streamSources[stream], 1, &buffer);
if(entityNum < 0)
{
// Volume
S_AL_Gain (streamSources[stream], volume * s_volume->value * s_alGain->value);
}
// Start stream
if(!streamPlaying[stream])
{
qalSourcePlay( streamSources[stream] );
streamPlaying[stream] = qtrue;
}
}
/*
=================
S_AL_StreamUpdate
=================
*/
static
void S_AL_StreamUpdate( int stream )
{
int numBuffers;
ALint state;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(streamSourceHandles[stream] == -1)
return;
// Un-queue any buffers
qalGetSourcei( streamSources[stream], AL_BUFFERS_PROCESSED, &numBuffers );
while( numBuffers-- )
{
ALuint buffer;
qalSourceUnqueueBuffers(streamSources[stream], 1, &buffer);
}
// Start the streamSource playing if necessary
qalGetSourcei( streamSources[stream], AL_BUFFERS_QUEUED, &numBuffers );
qalGetSourcei(streamSources[stream], AL_SOURCE_STATE, &state);
if(state == AL_STOPPED)
{
streamPlaying[stream] = qfalse;
// If there are no buffers queued up, release the streamSource
if( !numBuffers )
S_AL_FreeStreamChannel( stream );
}
if( !streamPlaying[stream] && numBuffers )
{
qalSourcePlay( streamSources[stream] );
streamPlaying[stream] = qtrue;
}
}
/*
=================
S_AL_StreamDie
=================
*/
static
void S_AL_StreamDie( int stream )
{
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(streamSourceHandles[stream] == -1)
return;
streamPlaying[stream] = qfalse;
qalSourceStop(streamSources[stream]);
S_AL_FreeStreamChannel(stream);
}
//===========================================================================
#define NUM_MUSIC_BUFFERS 4
#define MUSIC_BUFFER_SIZE 4096
static qboolean musicPlaying = qfalse;
static srcHandle_t musicSourceHandle = -1;
static ALuint musicSource;
static ALuint musicBuffers[NUM_MUSIC_BUFFERS];
static snd_stream_t *mus_stream;
static snd_stream_t *intro_stream;
static char s_backgroundLoop[MAX_QPATH];
static byte decode_buffer[MUSIC_BUFFER_SIZE];
/*
=================
S_AL_MusicSourceGet
=================
*/
static void S_AL_MusicSourceGet( void )
{
// Allocate a musicSource at high priority
musicSourceHandle = S_AL_SrcAlloc(-1, SRCPRI_STREAM, -2, 0, 0);
if(musicSourceHandle == -1)
return;
// Lock the musicSource so nobody else can use it, and get the raw musicSource
S_AL_SrcLock(musicSourceHandle);
musicSource = S_AL_SrcGet(musicSourceHandle);
// make sure that after unmuting the S_AL_Gain in S_Update() does not turn
// volume up prematurely for this source
srcList[musicSourceHandle].scaleGain = 0.0f;
// Set some musicSource parameters
qalSource3f(musicSource, AL_POSITION, 0.0, 0.0, 0.0);
qalSource3f(musicSource, AL_VELOCITY, 0.0, 0.0, 0.0);
qalSource3f(musicSource, AL_DIRECTION, 0.0, 0.0, 0.0);
qalSourcef (musicSource, AL_ROLLOFF_FACTOR, 0.0 );
qalSourcei (musicSource, AL_SOURCE_RELATIVE, AL_TRUE );
}
/*
=================
S_AL_MusicSourceFree
=================
*/
static void S_AL_MusicSourceFree( void )
{
// Release the output musicSource
S_AL_SrcUnlock(musicSourceHandle);
S_AL_SrcKill(musicSourceHandle);
musicSource = 0;
musicSourceHandle = -1;
}
/*
=================
S_AL_CloseMusicFiles
=================
*/
static void S_AL_CloseMusicFiles(void)
{
if(intro_stream)
{
S_CodecCloseStream(intro_stream);
intro_stream = NULL;
}
if(mus_stream)
{
S_CodecCloseStream(mus_stream);
mus_stream = NULL;
}
}
/*
=================
S_AL_StopBackgroundTrack
=================
*/
static
void S_AL_StopBackgroundTrack( void )
{
if(!musicPlaying)
return;
// Stop playing
qalSourceStop(musicSource);
// Detach any buffers
qalSourcei(musicSource, AL_BUFFER, 0);
// Delete the buffers
qalDeleteBuffers(NUM_MUSIC_BUFFERS, musicBuffers);
// Free the musicSource
S_AL_MusicSourceFree();
// Unload the stream
S_AL_CloseMusicFiles();
musicPlaying = qfalse;
}
/*
=================
S_AL_MusicProcess
=================
*/
static
void S_AL_MusicProcess(ALuint b)
{
ALenum error;
int l;
ALuint format;
snd_stream_t *curstream;
S_AL_ClearError( qfalse );
if(intro_stream)
curstream = intro_stream;
else
curstream = mus_stream;
if(!curstream)
return;
l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
// Run out data to read, start at the beginning again
if(l == 0)
{
S_CodecCloseStream(curstream);
// the intro stream just finished playing so we don't need to reopen
// the music stream.
if(intro_stream)
intro_stream = NULL;
else
mus_stream = S_CodecOpenStream(s_backgroundLoop);
curstream = mus_stream;
if(!curstream)
{
S_AL_StopBackgroundTrack();
return;
}
l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
}
format = S_AL_Format(curstream->info.width, curstream->info.channels);
if( l == 0 )
{
// We have no data to buffer, so buffer silence
byte dummyData[ 2 ] = { 0 };
qalBufferData( b, AL_FORMAT_MONO16, (void *)dummyData, 2, 22050 );
}
else
qalBufferData(b, format, decode_buffer, l, curstream->info.rate);
if( ( error = qalGetError( ) ) != AL_NO_ERROR )
{
S_AL_StopBackgroundTrack( );
Com_Printf( S_COLOR_RED "ERROR: while buffering data for music stream - %s\n",
S_AL_ErrorMsg( error ) );
return;
}
}
/*
=================
S_AL_StartBackgroundTrack
=================
*/
static
void S_AL_StartBackgroundTrack( const char *intro, const char *loop )
{
int i;
qboolean issame;
Com_DPrintf( "S_AL_StartBackgroundTrack( %s, %s )\n", intro, loop );
// Stop any existing music that might be playing
S_AL_StopBackgroundTrack();
Cvar_Set( "s_currentMusic", "" ); //----(SA) so the savegame will have the right music
if((!intro || !*intro) && (!loop || !*loop))
return;
// Allocate a musicSource
S_AL_MusicSourceGet();
if(musicSourceHandle == -1)
return;
if (!loop || !*loop)
{
loop = intro;
issame = qtrue;
}
else if(intro && *intro && !strcmp(intro, loop))
issame = qtrue;
else
issame = qfalse;
// Copy the loop over
Q_strncpyz( s_backgroundLoop, loop, sizeof( s_backgroundLoop ) );
if(!issame)
{
// Open the intro and don't mind whether it succeeds.
// The important part is the loop.
intro_stream = S_CodecOpenStream(intro);
}
else
intro_stream = NULL;
Cvar_Set( "s_currentMusic", s_backgroundLoop ); //----(SA) so the savegame will have the right music
mus_stream = S_CodecOpenStream(s_backgroundLoop);
if(!mus_stream)
{
S_AL_CloseMusicFiles();
S_AL_MusicSourceFree();
return;
}
// Generate the musicBuffers
if (!S_AL_GenBuffers(NUM_MUSIC_BUFFERS, musicBuffers, "music"))
return;
// Queue the musicBuffers up
for(i = 0; i < NUM_MUSIC_BUFFERS; i++)
{
S_AL_MusicProcess(musicBuffers[i]);
}
qalSourceQueueBuffers(musicSource, NUM_MUSIC_BUFFERS, musicBuffers);
// Set the initial gain property
S_AL_Gain(musicSource, s_alGain->value * s_musicVolume->value);
// Start playing
qalSourcePlay(musicSource);
musicPlaying = qtrue;
}
/*
=================
S_AL_MusicUpdate
=================
*/
static
void S_AL_MusicUpdate( void )
{
int numBuffers;
ALint state;
if(!musicPlaying)
return;
qalGetSourcei( musicSource, AL_BUFFERS_PROCESSED, &numBuffers );
while( numBuffers-- )
{
ALuint b;
qalSourceUnqueueBuffers(musicSource, 1, &b);
S_AL_MusicProcess(b);
qalSourceQueueBuffers(musicSource, 1, &b);
}
// Hitches can cause OpenAL to be starved of buffers when streaming.
// If this happens, it will stop playback. This restarts the source if
// it is no longer playing, and if there are buffers available
qalGetSourcei( musicSource, AL_SOURCE_STATE, &state );
qalGetSourcei( musicSource, AL_BUFFERS_QUEUED, &numBuffers );
if( state == AL_STOPPED && numBuffers )
{
Com_DPrintf( S_COLOR_YELLOW "Restarted OpenAL music\n" );
qalSourcePlay(musicSource);
}
// Set the gain property
S_AL_Gain(musicSource, s_alGain->value * s_musicVolume->value);
}
/*
======================
S_FadeStreamingSound
======================
*/
static
void S_AL_FadeStreamingSound( float targetvol, int time, int ssNum ) {
// FIXME: Stub
}
/*
======================
S_FadeAllSounds
======================
*/
static
void S_AL_FadeAllSounds( float targetvol, int time ) {
// FIXME: Stub
}
/*
======================
S_StartStreamingSound
======================
*/
static void S_AL_StartStreamingSound( const char *intro, const char *loop, int entnum, int channel, int attenuation ) {
// FIXME: Stub
}
/*
======================
S_StopEntStreamingSound
======================
*/
static void S_AL_StopEntStreamingSound( int entnum ) {
// FIXME: Stub
}
/*
======================
S_GetVoiceAmplitude
======================
*/
int S_AL_GetVoiceAmplitude( int entityNum ) {
if ( entityNum >= MAX_CLIENTS ) {
Com_Printf( "Error: S_GetVoiceAmplitude() called for a non-client\n" );
return 0;
}
return (int)s_entityTalkAmplitude[entityNum];
}
//===========================================================================
// Local state variables
static ALCdevice *alDevice;
static ALCcontext *alContext;
#ifdef USE_VOIP
static ALCdevice *alCaptureDevice;
static cvar_t *s_alCapture;
#endif
#ifdef _WIN32
#define ALDRIVER_DEFAULT "OpenAL32.dll"
#elif defined(__APPLE__)
#define ALDRIVER_DEFAULT "libopenal.dylib"
#elif defined(__OpenBSD__)
#define ALDRIVER_DEFAULT "libopenal.so"
#else
#define ALDRIVER_DEFAULT "libopenal.so.1"
#endif
/*
=================
S_AL_ClearSoundBuffer
=================
*/
static
void S_AL_ClearSoundBuffer( void )
{
S_AL_SrcShutdown( );
S_AL_SrcInit( );
}
/*
=================
S_AL_StopAllSounds
=================
*/
static
void S_AL_StopAllSounds( void )
{
int i;
S_AL_SrcShutup();
S_AL_StopBackgroundTrack();
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamDie(i);
S_AL_ClearSoundBuffer();
}
/*
=================
S_AL_Respatialize
=================
*/
static
void S_AL_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], int inwater )
{
float orientation[6];
vec3_t sorigin;
VectorCopy( origin, sorigin );
S_AL_SanitiseVector( sorigin );
S_AL_SanitiseVector( axis[ 0 ] );
S_AL_SanitiseVector( axis[ 1 ] );
S_AL_SanitiseVector( axis[ 2 ] );
orientation[0] = axis[0][0]; orientation[1] = axis[0][1]; orientation[2] = axis[0][2];
orientation[3] = axis[2][0]; orientation[4] = axis[2][1]; orientation[5] = axis[2][2];
lastListenerNumber = entityNum;
VectorCopy( sorigin, lastListenerOrigin );
// Set OpenAL listener paramaters
qalListenerfv(AL_POSITION, (ALfloat *)sorigin);
qalListenerfv(AL_VELOCITY, vec3_origin);
qalListenerfv(AL_ORIENTATION, orientation);
}
/*
=================
S_AL_Update
=================
*/
static
void S_AL_Update( void )
{
int i;
if(s_muted->modified)
{
// muted state changed. Let S_AL_Gain turn up all sources again.
for(i = 0; i < srcCount; i++)
{
if(srcList[i].isActive)
S_AL_Gain(srcList[i].alSource, srcList[i].scaleGain);
}
s_muted->modified = qfalse;
}
// Update SFX channels
S_AL_SrcUpdate();
// Update streams
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamUpdate(i);
S_AL_MusicUpdate();
// Doppler
if(s_doppler->modified)
{
s_alDopplerFactor->modified = qtrue;
s_doppler->modified = qfalse;
}
// Doppler parameters
if(s_alDopplerFactor->modified)
{
if(s_doppler->integer)
qalDopplerFactor(s_alDopplerFactor->value);
else
qalDopplerFactor(0.0f);
s_alDopplerFactor->modified = qfalse;
}
if(s_alDopplerSpeed->modified)
{
qalSpeedOfSound(s_alDopplerSpeed->value);
s_alDopplerSpeed->modified = qfalse;
}
// Clear the modified flags on the other cvars
s_alGain->modified = qfalse;
s_volume->modified = qfalse;
s_musicVolume->modified = qfalse;
s_alMinDistance->modified = qfalse;
s_alRolloff->modified = qfalse;
}
/*
=================
S_AL_DisableSounds
=================
*/
static
void S_AL_DisableSounds( void )
{
S_AL_StopAllSounds();
}
/*
=================
S_AL_BeginRegistration
=================
*/
static
void S_AL_BeginRegistration( void )
{
if(!numSfx)
S_AL_BufferInit();
}
/*
=================
S_AL_SoundList
=================
*/
static
void S_AL_SoundList( void )
{
}
#ifdef USE_VOIP
static
void S_AL_StartCapture( void )
{
if (alCaptureDevice != NULL)
qalcCaptureStart(alCaptureDevice);
}
static
int S_AL_AvailableCaptureSamples( void )
{
int retval = 0;
if (alCaptureDevice != NULL)
{
ALint samples = 0;
qalcGetIntegerv(alCaptureDevice, ALC_CAPTURE_SAMPLES, sizeof (samples), &samples);
retval = (int) samples;
}
return retval;
}
static
void S_AL_Capture( int samples, byte *data )
{
if (alCaptureDevice != NULL)
qalcCaptureSamples(alCaptureDevice, data, samples);
}
void S_AL_StopCapture( void )
{
if (alCaptureDevice != NULL)
qalcCaptureStop(alCaptureDevice);
}
void S_AL_MasterGain( float gain )
{
qalListenerf(AL_GAIN, gain);
}
#endif
/*
=================
S_AL_SoundInfo
=================
*/
static void S_AL_SoundInfo(void)
{
Com_Printf( "OpenAL info:\n" );
Com_Printf( " Vendor: %s\n", qalGetString( AL_VENDOR ) );
Com_Printf( " Version: %s\n", qalGetString( AL_VERSION ) );
Com_Printf( " Renderer: %s\n", qalGetString( AL_RENDERER ) );
Com_Printf( " AL Extensions: %s\n", qalGetString( AL_EXTENSIONS ) );
Com_Printf( " ALC Extensions: %s\n", qalcGetString( alDevice, ALC_EXTENSIONS ) );
if(enumeration_all_ext)
Com_Printf(" Device: %s\n", qalcGetString(alDevice, ALC_ALL_DEVICES_SPECIFIER));
else if(enumeration_ext)
Com_Printf(" Device: %s\n", qalcGetString(alDevice, ALC_DEVICE_SPECIFIER));
if(enumeration_all_ext || enumeration_ext)
Com_Printf(" Available Devices:\n%s", s_alAvailableDevices->string);
#ifdef USE_VOIP
if(capture_ext)
{
#ifdef __APPLE__
Com_Printf(" Input Device: %s\n", qalcGetString(alCaptureDevice, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER));
#else
Com_Printf(" Input Device: %s\n", qalcGetString(alCaptureDevice, ALC_CAPTURE_DEVICE_SPECIFIER));
#endif
Com_Printf(" Available Input Devices:\n%s", s_alAvailableInputDevices->string);
}
#endif
}
/*
=================
S_AL_Shutdown
=================
*/
static
void S_AL_Shutdown( void )
{
// Shut down everything
int i;
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamDie(i);
S_AL_StopBackgroundTrack( );
S_AL_SrcShutdown( );
S_AL_BufferShutdown( );
qalcDestroyContext(alContext);
qalcCloseDevice(alDevice);
#ifdef USE_VOIP
if (alCaptureDevice != NULL) {
qalcCaptureStop(alCaptureDevice);
qalcCaptureCloseDevice(alCaptureDevice);
alCaptureDevice = NULL;
Com_Printf( "OpenAL capture device closed.\n" );
}
#endif
for (i = 0; i < MAX_RAW_STREAMS; i++) {
streamSourceHandles[i] = -1;
streamPlaying[i] = qfalse;
streamSources[i] = 0;
}
QAL_Shutdown();
}
#endif
/*
=================
S_AL_Init
=================
*/
qboolean S_AL_Init( soundInterface_t *si )
{
#ifdef USE_OPENAL
const char* device = NULL;
const char* inputdevice = NULL;
int i;
if( !si ) {
return qfalse;
}
for (i = 0; i < MAX_RAW_STREAMS; i++) {
streamSourceHandles[i] = -1;
streamPlaying[i] = qfalse;
streamSources[i] = 0;
streamNumBuffers[i] = 0;
streamBufIndex[i] = 0;
}
// New console variables
s_alPrecache = Cvar_Get( "s_alPrecache", "1", CVAR_ARCHIVE );
s_alGain = Cvar_Get( "s_alGain", "1.0", CVAR_ARCHIVE );
s_alSources = Cvar_Get( "s_alSources", "128", CVAR_ARCHIVE );
s_alDopplerFactor = Cvar_Get( "s_alDopplerFactor", "1.0", CVAR_ARCHIVE );
s_alDopplerSpeed = Cvar_Get( "s_alDopplerSpeed", "9000", CVAR_ARCHIVE );
s_alMinDistance = Cvar_Get( "s_alMinDistance", "256", CVAR_ARCHIVE );
s_alMaxDistance = Cvar_Get("s_alMaxDistance", "1024", CVAR_ARCHIVE);
s_alRolloff = Cvar_Get( "s_alRolloff", "1.3", CVAR_ARCHIVE);
s_alGraceDistance = Cvar_Get("s_alGraceDistance", "512", CVAR_ARCHIVE);
s_alTalkAnims = Cvar_Get("s_alTalkAnims", "160", CVAR_ARCHIVE);
s_alDriver = Cvar_Get( "s_alDriver", ALDRIVER_DEFAULT, CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED );
s_alInputDevice = Cvar_Get( "s_alInputDevice", "", CVAR_ARCHIVE | CVAR_LATCH );
s_alDevice = Cvar_Get("s_alDevice", "", CVAR_ARCHIVE | CVAR_LATCH);
if ( COM_CompareExtension( s_alDriver->string, ".pk3" ) )
{
Com_Printf( "Rejecting DLL named \"%s\"", s_alDriver->string );
return qfalse;
}
// Load QAL
if( !QAL_Init( s_alDriver->string ) )
{
#if defined( _WIN32 )
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) && !QAL_Init( "OpenAL64.dll" ) ) {
#elif defined ( __APPLE__ )
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) && !QAL_Init( "/System/Library/Frameworks/OpenAL.framework/OpenAL" ) ) {
#else
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) || !QAL_Init( ALDRIVER_DEFAULT ) ) {
#endif
return qfalse;
}
}
device = s_alDevice->string;
if(device && !*device)
device = NULL;
inputdevice = s_alInputDevice->string;
if(inputdevice && !*inputdevice)
inputdevice = NULL;
// Device enumeration support
enumeration_all_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT");
enumeration_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT");
if(enumeration_ext || enumeration_all_ext)
{
char devicenames[16384] = "";
const char *devicelist;
#ifdef _WIN32
const char *defaultdevice;
#endif
int curlen;
// get all available devices + the default device name.
if(enumeration_all_ext)
{
devicelist = qalcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_ALL_DEVICES_SPECIFIER);
#endif
}
else
{
// We don't have ALC_ENUMERATE_ALL_EXT but normal enumeration.
devicelist = qalcGetString(NULL, ALC_DEVICE_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
#endif
enumeration_ext = qtrue;
}
#ifdef _WIN32
// check whether the default device is generic hardware. If it is, change to
// Generic Software as that one works more reliably with various sound systems.
// If it's not, use OpenAL's default selection as we don't want to ignore
// native hardware acceleration.
if(!device && defaultdevice && !strcmp(defaultdevice, "Generic Hardware"))
device = "Generic Software";
#endif
// dump a list of available devices to a cvar for the user to see.
if(devicelist)
{
while((curlen = strlen(devicelist)))
{
Q_strcat(devicenames, sizeof(devicenames), devicelist);
Q_strcat(devicenames, sizeof(devicenames), "\n");
devicelist += curlen + 1;
}
}
s_alAvailableDevices = Cvar_Get("s_alAvailableDevices", devicenames, CVAR_ROM | CVAR_NORESTART);
}
alDevice = qalcOpenDevice(device);
if( !alDevice && device )
{
Com_Printf( "Failed to open OpenAL device '%s', trying default.\n", device );
alDevice = qalcOpenDevice(NULL);
}
if( !alDevice )
{
QAL_Shutdown( );
Com_Printf( "Failed to open OpenAL device.\n" );
return qfalse;
}
// Create OpenAL context
alContext = qalcCreateContext( alDevice, NULL );
if( !alContext )
{
QAL_Shutdown( );
qalcCloseDevice( alDevice );
Com_Printf( "Failed to create OpenAL context.\n" );
return qfalse;
}
qalcMakeContextCurrent( alContext );
// Initialize sources, buffers, music
S_AL_BufferInit( );
S_AL_SrcInit( );
// Print this for informational purposes
Com_Printf( "Allocated %d sources.\n", srcCount);
// Set up OpenAL parameters (doppler, etc)
qalDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
qalDopplerFactor( s_alDopplerFactor->value );
qalSpeedOfSound( s_alDopplerSpeed->value );
#ifdef USE_VOIP
// !!! FIXME: some of these alcCaptureOpenDevice() values should be cvars.
// !!! FIXME: add support for capture device enumeration.
// !!! FIXME: add some better error reporting.
s_alCapture = Cvar_Get( "s_alCapture", "1", CVAR_ARCHIVE | CVAR_LATCH );
if (!s_alCapture->integer)
{
Com_Printf("OpenAL capture support disabled by user ('+set s_alCapture 1' to enable)\n");
}
#if USE_MUMBLE
else if (cl_useMumble->integer)
{
Com_Printf("OpenAL capture support disabled for Mumble support\n");
}
#endif
else
{
#ifdef __APPLE__
// !!! FIXME: Apple has a 1.1-compliant OpenAL, which includes
// !!! FIXME: capture support, but they don't list it in the
// !!! FIXME: extension string. We need to check the version string,
// !!! FIXME: then the extension string, but that's too much trouble,
// !!! FIXME: so we'll just check the function pointer for now.
if (qalcCaptureOpenDevice == NULL)
#else
if (!qalcIsExtensionPresent(NULL, "ALC_EXT_capture"))
#endif
{
Com_Printf("No ALC_EXT_capture support, can't record audio.\n");
}
else
{
char inputdevicenames[16384] = "";
const char *inputdevicelist;
const char *defaultinputdevice;
int curlen;
capture_ext = qtrue;
// get all available input devices + the default input device name.
inputdevicelist = qalcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER);
defaultinputdevice = qalcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
// dump a list of available devices to a cvar for the user to see.
if (inputdevicelist)
{
while((curlen = strlen(inputdevicelist)))
{
Q_strcat(inputdevicenames, sizeof(inputdevicenames), inputdevicelist);
Q_strcat(inputdevicenames, sizeof(inputdevicenames), "\n");
inputdevicelist += curlen + 1;
}
}
s_alAvailableInputDevices = Cvar_Get("s_alAvailableInputDevices", inputdevicenames, CVAR_ROM | CVAR_NORESTART);
Com_Printf("OpenAL default capture device is '%s'\n", defaultinputdevice ? defaultinputdevice : "none");
alCaptureDevice = qalcCaptureOpenDevice(inputdevice, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
if( !alCaptureDevice && inputdevice )
{
Com_Printf( "Failed to open OpenAL Input device '%s', trying default.\n", inputdevice );
alCaptureDevice = qalcCaptureOpenDevice(NULL, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
}
Com_Printf( "OpenAL capture device %s.\n",
(alCaptureDevice == NULL) ? "failed to open" : "opened");
}
}
#endif
si->Shutdown = S_AL_Shutdown;
si->StartSound = S_AL_StartSound;
si->StartSoundEx = S_AL_StartSoundEx;
si->StartLocalSound = S_AL_StartLocalSound;
si->StartBackgroundTrack = S_AL_StartBackgroundTrack;
si->StopBackgroundTrack = S_AL_StopBackgroundTrack;
si->FadeStreamingSound = S_AL_FadeStreamingSound;
si->FadeAllSounds = S_AL_FadeAllSounds;
si->StartStreamingSound = S_AL_StartStreamingSound;
si->StopEntStreamingSound = S_AL_StopEntStreamingSound;
si->GetVoiceAmplitude = S_AL_GetVoiceAmplitude;
si->RawSamples = S_AL_RawSamples;
si->StopAllSounds = S_AL_StopAllSounds;
si->ClearLoopingSounds = S_AL_ClearLoopingSounds;
si->AddLoopingSound = S_AL_AddLoopingSound;
si->AddRealLoopingSound = S_AL_AddRealLoopingSound;
si->StopLoopingSound = S_AL_StopLoopingSound;
si->Respatialize = S_AL_Respatialize;
si->UpdateEntityPosition = S_AL_UpdateEntityPosition;
si->Update = S_AL_Update;
si->DisableSounds = S_AL_DisableSounds;
si->BeginRegistration = S_AL_BeginRegistration;
si->RegisterSound = S_AL_RegisterSound;
si->ClearSoundBuffer = S_AL_ClearSoundBuffer;
si->SoundInfo = S_AL_SoundInfo;
si->SoundList = S_AL_SoundList;
#ifdef USE_VOIP
si->StartCapture = S_AL_StartCapture;
si->AvailableCaptureSamples = S_AL_AvailableCaptureSamples;
si->Capture = S_AL_Capture;
si->StopCapture = S_AL_StopCapture;
si->MasterGain = S_AL_MasterGain;
#endif
return qtrue;
#else
return qfalse;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3232_1 |
crossvul-cpp_data_bad_3233_3 | /*
===========================================================================
Return to Castle Wolfenstein single player GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein single player GPL Source Code (RTCW SP Source Code).
RTCW SP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW SP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
// cl_main.c -- client main loop
#include "client.h"
#include <limits.h>
#include "../sys/sys_local.h"
#include "../sys/sys_loadlib.h"
#ifdef USE_MUMBLE
#include "libmumblelink.h"
#endif
#ifdef USE_MUMBLE
cvar_t *cl_useMumble;
cvar_t *cl_mumbleScale;
#endif
#ifdef USE_VOIP
cvar_t *cl_voipUseVAD;
cvar_t *cl_voipVADThreshold;
cvar_t *cl_voipSend;
cvar_t *cl_voipSendTarget;
cvar_t *cl_voipGainDuringCapture;
cvar_t *cl_voipCaptureMult;
cvar_t *cl_voipShowMeter;
cvar_t *cl_voipProtocol;
cvar_t *cl_voip;
#endif
#ifdef USE_RENDERER_DLOPEN
cvar_t *cl_renderer;
#endif
cvar_t *cl_nodelta;
cvar_t *cl_debugMove;
cvar_t *cl_noprint;
#ifdef UPDATE_SERVER_NAME
cvar_t *cl_motd;
#endif
cvar_t *rcon_client_password;
cvar_t *rconAddress;
cvar_t *cl_timeout;
cvar_t *cl_maxpackets;
cvar_t *cl_packetdup;
cvar_t *cl_timeNudge;
cvar_t *cl_showTimeDelta;
cvar_t *cl_freezeDemo;
cvar_t *cl_shownet = NULL; // NERVE - SMF - This is referenced in msg.c and we need to make sure it is NULL
cvar_t *cl_showSend;
cvar_t *cl_timedemo;
cvar_t *cl_timedemoLog;
cvar_t *cl_autoRecordDemo;
cvar_t *cl_aviFrameRate;
cvar_t *cl_aviMotionJpeg;
cvar_t *cl_avidemo;
cvar_t *cl_forceavidemo;
cvar_t *cl_freelook;
cvar_t *cl_sensitivity;
cvar_t *cl_mouseAccel;
cvar_t *cl_mouseAccelOffset;
cvar_t *cl_mouseAccelStyle;
cvar_t *cl_showMouseRate;
cvar_t *m_pitch;
cvar_t *m_yaw;
cvar_t *m_forward;
cvar_t *m_side;
cvar_t *m_filter;
cvar_t *j_pitch;
cvar_t *j_yaw;
cvar_t *j_forward;
cvar_t *j_side;
cvar_t *j_up;
cvar_t *j_pitch_axis;
cvar_t *j_yaw_axis;
cvar_t *j_forward_axis;
cvar_t *j_side_axis;
cvar_t *j_up_axis;
cvar_t *cl_activeAction;
cvar_t *cl_motdString;
cvar_t *cl_allowDownload;
cvar_t *cl_conXOffset;
cvar_t *cl_inGameVideo;
cvar_t *cl_serverStatusResendTime;
cvar_t *cl_missionStats;
cvar_t *cl_waitForFire;
// NERVE - SMF - localization
cvar_t *cl_language;
cvar_t *cl_debugTranslation;
// -NERVE - SMF
cvar_t *cl_lanForcePackets;
cvar_t *cl_guidServerUniq;
cvar_t *cl_consoleKeys;
cvar_t *cl_rate;
clientActive_t cl;
clientConnection_t clc;
clientStatic_t cls;
vm_t *cgvm;
char cl_reconnectArgs[MAX_OSPATH];
char cl_oldGame[MAX_QPATH];
qboolean cl_oldGameSet;
// Structure containing functions exported from refresh DLL
refexport_t re;
#ifdef USE_RENDERER_DLOPEN
static void *rendererLib = NULL;
#endif
ping_t cl_pinglist[MAX_PINGREQUESTS];
typedef struct serverStatus_s
{
char string[BIG_INFO_STRING];
netadr_t address;
int time, startTime;
qboolean pending;
qboolean print;
qboolean retrieved;
} serverStatus_t;
serverStatus_t cl_serverStatusList[MAX_SERVERSTATUSREQUESTS];
static int noGameRestart = qfalse;
extern void SV_BotFrame( int time );
void CL_CheckForResend( void );
void CL_ShowIP_f( void );
void CL_ServerStatus_f( void );
void CL_ServerStatusResponse( netadr_t from, msg_t *msg );
/*
==============
CL_EndgameMenu
Called by Com_Error when a game has ended and is dropping out to main menu in the "endgame" menu ('credits' right now)
==============
*/
void CL_EndgameMenu( void ) {
cls.endgamemenu = qtrue; // start it next frame
}
/*
===============
CL_CDDialog
Called by Com_Error when a cd is needed
===============
*/
void CL_CDDialog( void ) {
cls.cddialog = qtrue; // start it next frame
}
#ifdef USE_MUMBLE
static
void CL_UpdateMumble(void)
{
vec3_t pos, forward, up;
float scale = cl_mumbleScale->value;
float tmp;
if(!cl_useMumble->integer)
return;
// !!! FIXME: not sure if this is even close to correct.
AngleVectors( cl.snap.ps.viewangles, forward, NULL, up);
pos[0] = cl.snap.ps.origin[0] * scale;
pos[1] = cl.snap.ps.origin[2] * scale;
pos[2] = cl.snap.ps.origin[1] * scale;
tmp = forward[1];
forward[1] = forward[2];
forward[2] = tmp;
tmp = up[1];
up[1] = up[2];
up[2] = tmp;
if(cl_useMumble->integer > 1) {
fprintf(stderr, "%f %f %f, %f %f %f, %f %f %f\n",
pos[0], pos[1], pos[2],
forward[0], forward[1], forward[2],
up[0], up[1], up[2]);
}
mumble_update_coordinates(pos, forward, up);
}
#endif
#ifdef USE_VOIP
static
void CL_UpdateVoipIgnore(const char *idstr, qboolean ignore)
{
if ((*idstr >= '0') && (*idstr <= '9')) {
const int id = atoi(idstr);
if ((id >= 0) && (id < MAX_CLIENTS)) {
clc.voipIgnore[id] = ignore;
CL_AddReliableCommand(va("voip %s %d",
ignore ? "ignore" : "unignore", id), qfalse);
Com_Printf("VoIP: %s ignoring player #%d\n",
ignore ? "Now" : "No longer", id);
return;
}
}
Com_Printf("VoIP: invalid player ID#\n");
}
static
void CL_UpdateVoipGain(const char *idstr, float gain)
{
if ((*idstr >= '0') && (*idstr <= '9')) {
const int id = atoi(idstr);
if (gain < 0.0f)
gain = 0.0f;
if ((id >= 0) && (id < MAX_CLIENTS)) {
clc.voipGain[id] = gain;
Com_Printf("VoIP: player #%d gain now set to %f\n", id, gain);
}
}
}
void CL_Voip_f( void )
{
const char *cmd = Cmd_Argv(1);
const char *reason = NULL;
if (clc.state != CA_ACTIVE)
reason = "Not connected to a server";
else if (!clc.voipCodecInitialized)
reason = "Voip codec not initialized";
else if (!clc.voipEnabled)
reason = "Server doesn't support VoIP";
else if (!clc.demoplaying && (Cvar_VariableValue("g_gametype") == GT_SINGLE_PLAYER || Cvar_VariableValue("ui_singlePlayerActive")))
reason = "running in single-player mode";
if (reason != NULL) {
Com_Printf("VoIP: command ignored: %s\n", reason);
return;
}
if (strcmp(cmd, "ignore") == 0) {
CL_UpdateVoipIgnore(Cmd_Argv(2), qtrue);
} else if (strcmp(cmd, "unignore") == 0) {
CL_UpdateVoipIgnore(Cmd_Argv(2), qfalse);
} else if (strcmp(cmd, "gain") == 0) {
if (Cmd_Argc() > 3) {
CL_UpdateVoipGain(Cmd_Argv(2), atof(Cmd_Argv(3)));
} else if (Q_isanumber(Cmd_Argv(2))) {
int id = atoi(Cmd_Argv(2));
if (id >= 0 && id < MAX_CLIENTS) {
Com_Printf("VoIP: current gain for player #%d "
"is %f\n", id, clc.voipGain[id]);
} else {
Com_Printf("VoIP: invalid player ID#\n");
}
} else {
Com_Printf("usage: voip gain <playerID#> [value]\n");
}
} else if (strcmp(cmd, "muteall") == 0) {
Com_Printf("VoIP: muting incoming voice\n");
CL_AddReliableCommand("voip muteall", qfalse);
clc.voipMuteAll = qtrue;
} else if (strcmp(cmd, "unmuteall") == 0) {
Com_Printf("VoIP: unmuting incoming voice\n");
CL_AddReliableCommand("voip unmuteall", qfalse);
clc.voipMuteAll = qfalse;
} else {
Com_Printf("usage: voip [un]ignore <playerID#>\n"
" voip [un]muteall\n"
" voip gain <playerID#> [value]\n");
}
}
static
void CL_VoipNewGeneration(void)
{
// don't have a zero generation so new clients won't match, and don't
// wrap to negative so MSG_ReadLong() doesn't "fail."
clc.voipOutgoingGeneration++;
if (clc.voipOutgoingGeneration <= 0)
clc.voipOutgoingGeneration = 1;
clc.voipPower = 0.0f;
clc.voipOutgoingSequence = 0;
opus_encoder_ctl(clc.opusEncoder, OPUS_RESET_STATE);
}
/*
===============
CL_VoipParseTargets
sets clc.voipTargets according to cl_voipSendTarget
Generally we don't want who's listening to change during a transmission,
so this is only called when the key is first pressed
===============
*/
void CL_VoipParseTargets(void)
{
const char *target = cl_voipSendTarget->string;
char *end;
int val;
Com_Memset(clc.voipTargets, 0, sizeof(clc.voipTargets));
clc.voipFlags &= ~VOIP_SPATIAL;
while(target)
{
while(*target == ',' || *target == ' ')
target++;
if(!*target)
break;
if(isdigit(*target))
{
val = strtol(target, &end, 10);
target = end;
}
else
{
if(!Q_stricmpn(target, "all", 3))
{
Com_Memset(clc.voipTargets, ~0, sizeof(clc.voipTargets));
return;
}
if(!Q_stricmpn(target, "spatial", 7))
{
clc.voipFlags |= VOIP_SPATIAL;
target += 7;
continue;
}
else
{
if(!Q_stricmpn(target, "attacker", 8))
{
val = VM_Call(cgvm, CG_LAST_ATTACKER);
target += 8;
}
else if(!Q_stricmpn(target, "crosshair", 9))
{
val = VM_Call(cgvm, CG_CROSSHAIR_PLAYER);
target += 9;
}
else
{
while(*target && *target != ',' && *target != ' ')
target++;
continue;
}
if(val < 0)
continue;
}
}
if(val < 0 || val >= MAX_CLIENTS)
{
Com_Printf(S_COLOR_YELLOW "WARNING: VoIP "
"target %d is not a valid client "
"number\n", val);
continue;
}
clc.voipTargets[val / 8] |= 1 << (val % 8);
}
}
/*
===============
CL_CaptureVoip
Record more audio from the hardware if required and encode it into Opus
data for later transmission.
===============
*/
static
void CL_CaptureVoip(void)
{
const float audioMult = cl_voipCaptureMult->value;
const qboolean useVad = (cl_voipUseVAD->integer != 0);
qboolean initialFrame = qfalse;
qboolean finalFrame = qfalse;
#if USE_MUMBLE
// if we're using Mumble, don't try to handle VoIP transmission ourselves.
if (cl_useMumble->integer)
return;
#endif
// If your data rate is too low, you'll get Connection Interrupted warnings
// when VoIP packets arrive, even if you have a broadband connection.
// This might work on rates lower than 25000, but for safety's sake, we'll
// just demand it. Who doesn't have at least a DSL line now, anyhow? If
// you don't, you don't need VoIP. :)
if (cl_voip->modified || cl_rate->modified) {
if ((cl_voip->integer) && (cl_rate->integer < 25000)) {
Com_Printf(S_COLOR_YELLOW "Your network rate is too slow for VoIP.\n");
Com_Printf("Set 'Data Rate' to 'LAN/Cable/xDSL' in 'Setup/System/Network'.\n");
Com_Printf("Until then, VoIP is disabled.\n");
Cvar_Set("cl_voip", "0");
}
Cvar_Set("cl_voipProtocol", cl_voip->integer ? "opus" : "");
cl_voip->modified = qfalse;
cl_rate->modified = qfalse;
}
if (!clc.voipCodecInitialized)
return; // just in case this gets called at a bad time.
if (clc.voipOutgoingDataSize > 0)
return; // packet is pending transmission, don't record more yet.
if (cl_voipUseVAD->modified) {
Cvar_Set("cl_voipSend", (useVad) ? "1" : "0");
cl_voipUseVAD->modified = qfalse;
}
if ((useVad) && (!cl_voipSend->integer))
Cvar_Set("cl_voipSend", "1"); // lots of things reset this.
if (cl_voipSend->modified) {
qboolean dontCapture = qfalse;
if (clc.state != CA_ACTIVE)
dontCapture = qtrue; // not connected to a server.
else if (!clc.voipEnabled)
dontCapture = qtrue; // server doesn't support VoIP.
else if (clc.demoplaying)
dontCapture = qtrue; // playing back a demo.
else if ( cl_voip->integer == 0 )
dontCapture = qtrue; // client has VoIP support disabled.
else if ( audioMult == 0.0f )
dontCapture = qtrue; // basically silenced incoming audio.
cl_voipSend->modified = qfalse;
if(dontCapture)
{
Cvar_Set("cl_voipSend", "0");
return;
}
if (cl_voipSend->integer) {
initialFrame = qtrue;
} else {
finalFrame = qtrue;
}
}
// try to get more audio data from the sound card...
if (initialFrame) {
S_MasterGain(Com_Clamp(0.0f, 1.0f, cl_voipGainDuringCapture->value));
S_StartCapture();
CL_VoipNewGeneration();
CL_VoipParseTargets();
}
if ((cl_voipSend->integer) || (finalFrame)) { // user wants to capture audio?
int samples = S_AvailableCaptureSamples();
const int packetSamples = (finalFrame) ? VOIP_MAX_FRAME_SAMPLES : VOIP_MAX_PACKET_SAMPLES;
// enough data buffered in audio hardware to process yet?
if (samples >= packetSamples) {
// audio capture is always MONO16.
static int16_t sampbuffer[VOIP_MAX_PACKET_SAMPLES];
float voipPower = 0.0f;
int voipFrames;
int i, bytes;
if (samples > VOIP_MAX_PACKET_SAMPLES)
samples = VOIP_MAX_PACKET_SAMPLES;
// !!! FIXME: maybe separate recording from encoding, so voipPower
// !!! FIXME: updates faster than 4Hz?
samples -= samples % VOIP_MAX_FRAME_SAMPLES;
if (samples != 120 && samples != 240 && samples != 480 && samples != 960 && samples != 1920 && samples != 2880 ) {
Com_Printf("Voip: bad number of samples %d\n", samples);
return;
}
voipFrames = samples / VOIP_MAX_FRAME_SAMPLES;
S_Capture(samples, (byte *) sampbuffer); // grab from audio card.
// check the "power" of this packet...
for (i = 0; i < samples; i++) {
const float flsamp = (float) sampbuffer[i];
const float s = fabs(flsamp);
voipPower += s * s;
sampbuffer[i] = (int16_t) ((flsamp) * audioMult);
}
// encode raw audio samples into Opus data...
bytes = opus_encode(clc.opusEncoder, sampbuffer, samples,
(unsigned char *) clc.voipOutgoingData,
sizeof (clc.voipOutgoingData));
if ( bytes <= 0 ) {
Com_DPrintf("VoIP: Error encoding %d samples\n", samples);
bytes = 0;
}
clc.voipPower = (voipPower / (32768.0f * 32768.0f *
((float) samples))) * 100.0f;
if ((useVad) && (clc.voipPower < cl_voipVADThreshold->value)) {
CL_VoipNewGeneration(); // no "talk" for at least 1/4 second.
} else {
clc.voipOutgoingDataSize = bytes;
clc.voipOutgoingDataFrames = voipFrames;
Com_DPrintf("VoIP: Send %d frames, %d bytes, %f power\n",
voipFrames, bytes, clc.voipPower);
#if 0
static FILE *encio = NULL;
if (encio == NULL) encio = fopen("voip-outgoing-encoded.bin", "wb");
if (encio != NULL) { fwrite(clc.voipOutgoingData, bytes, 1, encio); fflush(encio); }
static FILE *decio = NULL;
if (decio == NULL) decio = fopen("voip-outgoing-decoded.bin", "wb");
if (decio != NULL) { fwrite(sampbuffer, voipFrames * VOIP_MAX_FRAME_SAMPLES * 2, 1, decio); fflush(decio); }
#endif
}
}
}
// User requested we stop recording, and we've now processed the last of
// any previously-buffered data. Pause the capture device, etc.
if (finalFrame) {
S_StopCapture();
S_MasterGain(1.0f);
clc.voipPower = 0.0f; // force this value so it doesn't linger.
}
}
#endif
/*
=======================================================================
CLIENT RELIABLE COMMAND COMMUNICATION
=======================================================================
*/
/*
======================
CL_AddReliableCommand
The given command will be transmitted to the server, and is gauranteed to
not have future usercmd_t executed before it is executed
======================
*/
void CL_AddReliableCommand(const char *cmd, qboolean isDisconnectCmd)
{
int unacknowledged = clc.reliableSequence - clc.reliableAcknowledge;
// if we would be losing an old command that hasn't been acknowledged,
// we must drop the connection
// also leave one slot open for the disconnect command in this case.
if ((isDisconnectCmd && unacknowledged > MAX_RELIABLE_COMMANDS) ||
(!isDisconnectCmd && unacknowledged >= MAX_RELIABLE_COMMANDS))
{
if(com_errorEntered)
return;
else
Com_Error(ERR_DROP, "Client command overflow");
}
Q_strncpyz(clc.reliableCommands[++clc.reliableSequence & (MAX_RELIABLE_COMMANDS - 1)],
cmd, sizeof(*clc.reliableCommands));
}
/*
=======================================================================
CLIENT SIDE DEMO RECORDING
=======================================================================
*/
/*
====================
CL_WriteDemoMessage
Dumps the current net message, prefixed by the length
====================
*/
void CL_WriteDemoMessage( msg_t *msg, int headerBytes ) {
int len, swlen;
// write the packet sequence
len = clc.serverMessageSequence;
swlen = LittleLong( len );
FS_Write( &swlen, 4, clc.demofile );
// skip the packet sequencing information
len = msg->cursize - headerBytes;
swlen = LittleLong( len );
FS_Write( &swlen, 4, clc.demofile );
FS_Write( msg->data + headerBytes, len, clc.demofile );
}
/*
====================
CL_StopRecording_f
stop recording a demo
====================
*/
void CL_StopRecord_f( void ) {
int len;
if ( !clc.demorecording ) {
Com_Printf( "Not recording a demo.\n" );
return;
}
// finish up
len = -1;
FS_Write( &len, 4, clc.demofile );
FS_Write( &len, 4, clc.demofile );
FS_FCloseFile( clc.demofile );
clc.demofile = 0;
clc.demorecording = qfalse;
Com_Printf( "Stopped demo.\n" );
}
/*
==================
CL_DemoFilename
==================
*/
void CL_DemoFilename( int number, char *fileName, int fileNameSize ) {
int a,b,c,d;
if(number < 0 || number > 9999)
number = 9999;
a = number / 1000;
number -= a * 1000;
b = number / 100;
number -= b * 100;
c = number / 10;
number -= c * 10;
d = number;
Com_sprintf( fileName, fileNameSize, "demo%i%i%i%i"
, a, b, c, d );
}
/*
====================
CL_Record_f
record <demoname>
Begins recording a demo from the current position
====================
*/
static char demoName[MAX_QPATH]; // compiler bug workaround
void CL_Record_f( void ) {
char name[MAX_OSPATH];
byte bufData[MAX_MSGLEN];
msg_t buf;
int i;
int len;
entityState_t *ent;
entityState_t nullstate;
char *s;
if ( Cmd_Argc() > 2 ) {
Com_Printf( "record <demoname>\n" );
return;
}
if ( clc.demorecording ) {
Com_Printf( "Already recording.\n" );
return;
}
if ( clc.state != CA_ACTIVE ) {
Com_Printf( "You must be in a level to record.\n" );
return;
}
// sync 0 doesn't prevent recording, so not forcing it off .. everyone does g_sync 1 ; record ; g_sync 0 ..
if ( NET_IsLocalAddress( clc.serverAddress ) && !Cvar_VariableValue( "g_synchronousClients" ) ) {
Com_Printf (S_COLOR_YELLOW "WARNING: You should set 'g_synchronousClients 1' for smoother demo recording\n");
}
if ( Cmd_Argc() == 2 ) {
s = Cmd_Argv( 1 );
Q_strncpyz( demoName, s, sizeof( demoName ) );
#ifdef LEGACY_PROTOCOL
if(clc.compat)
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_legacyprotocol->integer);
else
#endif
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_protocol->integer);
} else {
int number;
// scan for a free demo name
for ( number = 0 ; number <= 9999 ; number++ ) {
CL_DemoFilename( number, demoName, sizeof( demoName ) );
#ifdef LEGACY_PROTOCOL
if(clc.compat)
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_legacyprotocol->integer);
else
#endif
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_protocol->integer);
if (!FS_FileExists(name))
break; // file doesn't exist
}
}
// open the demo file
Com_Printf( "recording to %s.\n", name );
clc.demofile = FS_FOpenFileWrite( name );
if ( !clc.demofile ) {
Com_Printf( "ERROR: couldn't open.\n" );
return;
}
clc.demorecording = qtrue;
Q_strncpyz( clc.demoName, demoName, sizeof( clc.demoName ) );
// don't start saving messages until a non-delta compressed message is received
clc.demowaiting = qtrue;
// write out the gamestate message
MSG_Init( &buf, bufData, sizeof( bufData ) );
MSG_Bitstream( &buf );
// NOTE, MRE: all server->client messages now acknowledge
MSG_WriteLong( &buf, clc.reliableSequence );
MSG_WriteByte( &buf, svc_gamestate );
MSG_WriteLong( &buf, clc.serverCommandSequence );
// configstrings
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
if ( !cl.gameState.stringOffsets[i] ) {
continue;
}
s = cl.gameState.stringData + cl.gameState.stringOffsets[i];
MSG_WriteByte( &buf, svc_configstring );
MSG_WriteShort( &buf, i );
MSG_WriteBigString( &buf, s );
}
// baselines
Com_Memset( &nullstate, 0, sizeof( nullstate ) );
for ( i = 0; i < MAX_GENTITIES ; i++ ) {
ent = &cl.entityBaselines[i];
if ( !ent->number ) {
continue;
}
MSG_WriteByte( &buf, svc_baseline );
MSG_WriteDeltaEntity( &buf, &nullstate, ent, qtrue );
}
MSG_WriteByte( &buf, svc_EOF );
// finished writing the gamestate stuff
// write the client num
MSG_WriteLong( &buf, clc.clientNum );
// write the checksum feed
MSG_WriteLong( &buf, clc.checksumFeed );
// finished writing the client packet
MSG_WriteByte( &buf, svc_EOF );
// write it to the demo file
len = LittleLong( clc.serverMessageSequence - 1 );
FS_Write( &len, 4, clc.demofile );
len = LittleLong( buf.cursize );
FS_Write( &len, 4, clc.demofile );
FS_Write( buf.data, buf.cursize, clc.demofile );
// the rest of the demo file will be copied from net messages
}
/*
=======================================================================
CLIENT SIDE DEMO PLAYBACK
=======================================================================
*/
/*
=================
CL_DemoFrameDurationSDev
=================
*/
static float CL_DemoFrameDurationSDev( void )
{
int i;
int numFrames;
float mean = 0.0f;
float variance = 0.0f;
if( ( clc.timeDemoFrames - 1 ) > MAX_TIMEDEMO_DURATIONS )
numFrames = MAX_TIMEDEMO_DURATIONS;
else
numFrames = clc.timeDemoFrames - 1;
for( i = 0; i < numFrames; i++ )
mean += clc.timeDemoDurations[ i ];
mean /= numFrames;
for( i = 0; i < numFrames; i++ )
{
float x = clc.timeDemoDurations[ i ];
variance += ( ( x - mean ) * ( x - mean ) );
}
variance /= numFrames;
return sqrt( variance );
}
/*
=================
CL_DemoCompleted
=================
*/
void CL_DemoCompleted( void )
{
char buffer[ MAX_STRING_CHARS ];
if( cl_timedemo && cl_timedemo->integer )
{
int time;
time = Sys_Milliseconds() - clc.timeDemoStart;
if( time > 0 )
{
// Millisecond times are frame durations:
// minimum/average/maximum/std deviation
Com_sprintf( buffer, sizeof( buffer ),
"%i frames %3.1f seconds %3.1f fps %d.0/%.1f/%d.0/%.1f ms\n",
clc.timeDemoFrames,
time/1000.0,
clc.timeDemoFrames*1000.0 / time,
clc.timeDemoMinDuration,
time / (float)clc.timeDemoFrames,
clc.timeDemoMaxDuration,
CL_DemoFrameDurationSDev( ) );
Com_Printf( "%s", buffer );
// Write a log of all the frame durations
if( cl_timedemoLog && strlen( cl_timedemoLog->string ) > 0 )
{
int i;
int numFrames;
fileHandle_t f;
if( ( clc.timeDemoFrames - 1 ) > MAX_TIMEDEMO_DURATIONS )
numFrames = MAX_TIMEDEMO_DURATIONS;
else
numFrames = clc.timeDemoFrames - 1;
f = FS_FOpenFileWrite( cl_timedemoLog->string );
if( f )
{
FS_Printf( f, "# %s", buffer );
for( i = 0; i < numFrames; i++ )
FS_Printf( f, "%d\n", clc.timeDemoDurations[ i ] );
FS_FCloseFile( f );
Com_Printf( "%s written\n", cl_timedemoLog->string );
}
else
{
Com_Printf( "Couldn't open %s for writing\n",
cl_timedemoLog->string );
}
}
}
}
CL_Disconnect( qtrue );
CL_NextDemo();
}
/*
=================
CL_ReadDemoMessage
=================
*/
void CL_ReadDemoMessage( void ) {
int r;
msg_t buf;
byte bufData[ MAX_MSGLEN ];
int s;
if ( !clc.demofile ) {
CL_DemoCompleted();
return;
}
// get the sequence number
r = FS_Read( &s, 4, clc.demofile );
if ( r != 4 ) {
CL_DemoCompleted();
return;
}
clc.serverMessageSequence = LittleLong( s );
// init the message
MSG_Init( &buf, bufData, sizeof( bufData ) );
// get the length
r = FS_Read( &buf.cursize, 4, clc.demofile );
if ( r != 4 ) {
CL_DemoCompleted();
return;
}
buf.cursize = LittleLong( buf.cursize );
if ( buf.cursize == -1 ) {
CL_DemoCompleted();
return;
}
if ( buf.cursize > buf.maxsize ) {
Com_Error( ERR_DROP, "CL_ReadDemoMessage: demoMsglen > MAX_MSGLEN" );
}
r = FS_Read( buf.data, buf.cursize, clc.demofile );
if ( r != buf.cursize ) {
Com_Printf( "Demo file was truncated.\n" );
CL_DemoCompleted();
return;
}
clc.lastPacketTime = cls.realtime;
buf.readcount = 0;
CL_ParseServerMessage( &buf );
}
/*
====================
CL_WalkDemoExt
====================
*/
static int CL_WalkDemoExt(char *arg, char *name, int *demofile)
{
int i = 0;
*demofile = 0;
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer > 0)
{
Com_sprintf(name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, com_legacyprotocol->integer);
FS_FOpenFileRead(name, demofile, qtrue);
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return com_legacyprotocol->integer;
}
}
if(com_protocol->integer != com_legacyprotocol->integer)
#endif
{
Com_sprintf(name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, com_protocol->integer);
FS_FOpenFileRead(name, demofile, qtrue);
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return com_protocol->integer;
}
}
Com_Printf("Not found: %s\n", name);
while(demo_protocols[i])
{
#ifdef LEGACY_PROTOCOL
if(demo_protocols[i] == com_legacyprotocol->integer)
continue;
#endif
if(demo_protocols[i] == com_protocol->integer)
continue;
Com_sprintf (name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, demo_protocols[i]);
FS_FOpenFileRead( name, demofile, qtrue );
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return demo_protocols[i];
}
else
Com_Printf("Not found: %s\n", name);
i++;
}
return -1;
}
/*
====================
CL_CompleteDemoName
====================
*/
static void CL_CompleteDemoName( char *args, int argNum )
{
if( argNum == 2 )
{
char demoExt[ 16 ];
Com_sprintf(demoExt, sizeof(demoExt), ".%s%d", DEMOEXT, com_protocol->integer);
Field_CompleteFilename( "demos", demoExt, qtrue, qtrue );
}
}
/*
====================
CL_PlayDemo_f
demo <demoname>
====================
*/
void CL_PlayDemo_f( void ) {
char name[MAX_OSPATH];
char *arg, *ext_test;
int protocol, i;
char retry[MAX_OSPATH];
if (Cmd_Argc() != 2) {
Com_Printf ("demo <demoname>\n");
return;
}
// make sure a local server is killed
// 2 means don't force disconnect of local client
Cvar_Set( "sv_killserver", "2" );
// open the demo file
arg = Cmd_Argv(1);
CL_Disconnect( qtrue );
// check for an extension .DEMOEXT_?? (?? is protocol)
ext_test = strrchr(arg, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMOEXT, ARRAY_LEN(DEMOEXT) - 1))
{
protocol = atoi(ext_test + ARRAY_LEN(DEMOEXT));
for(i = 0; demo_protocols[i]; i++)
{
if(demo_protocols[i] == protocol)
break;
}
if(demo_protocols[i] || protocol == com_protocol->integer
#ifdef LEGACY_PROTOCOL
|| protocol == com_legacyprotocol->integer
#endif
)
{
Com_sprintf(name, sizeof(name), "demos/%s", arg);
FS_FOpenFileRead(name, &clc.demofile, qtrue);
}
else
{
int len;
Com_Printf("Protocol %d not supported for demos\n", protocol);
len = ext_test - arg;
if(len >= ARRAY_LEN(retry))
len = ARRAY_LEN(retry) - 1;
Q_strncpyz(retry, arg, len + 1);
retry[len] = '\0';
protocol = CL_WalkDemoExt(retry, name, &clc.demofile);
}
}
else
protocol = CL_WalkDemoExt(arg, name, &clc.demofile);
if (!clc.demofile) {
Com_Error( ERR_DROP, "couldn't open %s", name);
return;
}
Q_strncpyz( clc.demoName, arg, sizeof( clc.demoName ) );
Con_Close();
clc.state = CA_CONNECTED;
clc.demoplaying = qtrue;
Q_strncpyz( clc.servername, arg, sizeof( clc.servername ) );
#ifdef LEGACY_PROTOCOL
if(protocol <= com_legacyprotocol->integer)
clc.compat = qtrue;
else
clc.compat = qfalse;
#endif
// read demo messages until connected
while ( clc.state >= CA_CONNECTED && clc.state < CA_PRIMED ) {
CL_ReadDemoMessage();
}
// don't get the first snapshot this frame, to prevent the long
// time from the gamestate load from messing causing a time skip
clc.firstDemoFrameSkipped = qfalse;
}
/*
====================
CL_StartDemoLoop
Closing the main menu will restart the demo loop
====================
*/
void CL_StartDemoLoop( void ) {
// start the demo loop again
Cbuf_AddText( "d1\n" );
Key_SetCatcher( 0 );
}
/*
==================
CL_NextDemo
Called when a demo or cinematic finishes
If the "nextdemo" cvar is set, that command will be issued
==================
*/
void CL_NextDemo( void ) {
char v[MAX_STRING_CHARS];
Q_strncpyz( v, Cvar_VariableString( "nextdemo" ), sizeof( v ) );
v[MAX_STRING_CHARS - 1] = 0;
Com_DPrintf( "CL_NextDemo: %s\n", v );
if ( !v[0] ) {
return;
}
Cvar_Set( "nextdemo","" );
Cbuf_AddText( v );
Cbuf_AddText( "\n" );
Cbuf_Execute();
}
//======================================================================
/*
=====================
CL_ShutdownAll
=====================
*/
void CL_ShutdownAll(qboolean shutdownRef)
{
if(CL_VideoRecording())
CL_CloseAVI();
if(clc.demorecording)
CL_StopRecord_f();
#ifdef USE_CURL
CL_cURL_Shutdown();
#endif
// clear sounds
S_DisableSounds();
// shutdown CGame
CL_ShutdownCGame();
// shutdown UI
CL_ShutdownUI();
// shutdown the renderer
if(shutdownRef)
CL_ShutdownRef();
else if(re.Shutdown)
re.Shutdown(qfalse); // don't destroy window or context
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.rendererStarted = qfalse;
cls.soundRegistered = qfalse;
}
/*
=================
CL_ClearMemory
Called by Com_GameRestart
=================
*/
void CL_ClearMemory(qboolean shutdownRef)
{
// shutdown all the client stuff
CL_ShutdownAll(shutdownRef);
// if not running a server clear the whole hunk
if ( !com_sv_running->integer ) {
// clear the whole hunk
Hunk_Clear();
// clear collision map data
CM_ClearMap();
} else {
// clear all the client data on the hunk
Hunk_ClearToMark();
}
}
/*
=================
CL_FlushMemory
Called by CL_MapLoading, CL_Connect_f, CL_PlayDemo_f, and CL_ParseGamestate the only
ways a client gets into a game
Also called by Com_Error
=================
*/
void CL_FlushMemory(void)
{
CL_ClearMemory(qfalse);
CL_StartHunkUsers(qfalse);
}
/*
=====================
CL_MapLoading
A local server is starting to load a map, so update the
screen to let the user know about it, then dump all client
memory on the hunk from cgame, ui, and renderer
=====================
*/
void CL_MapLoading( void ) {
if ( com_dedicated->integer ) {
clc.state = CA_DISCONNECTED;
Key_SetCatcher( KEYCATCH_CONSOLE );
return;
}
if ( !com_cl_running->integer ) {
return;
}
Con_Close();
Key_SetCatcher( 0 );
// if we are already connected to the local host, stay connected
if ( clc.state >= CA_CONNECTED && !Q_stricmp( clc.servername, "localhost" ) ) {
clc.state = CA_CONNECTED; // so the connect screen is drawn
Com_Memset( cls.updateInfoString, 0, sizeof( cls.updateInfoString ) );
Com_Memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) );
Com_Memset( &cl.gameState, 0, sizeof( cl.gameState ) );
clc.lastPacketSentTime = -9999;
SCR_UpdateScreen();
} else {
// clear nextmap so the cinematic shutdown doesn't execute it
Cvar_Set( "nextmap", "" );
CL_Disconnect( qtrue );
Q_strncpyz( clc.servername, "localhost", sizeof(clc.servername) );
clc.state = CA_CHALLENGING; // so the connect screen is drawn
Key_SetCatcher( 0 );
SCR_UpdateScreen();
clc.connectTime = -RETRANSMIT_TIMEOUT;
NET_StringToAdr( clc.servername, &clc.serverAddress, NA_UNSPEC);
// we don't need a challenge on the localhost
CL_CheckForResend();
}
// make sure sound is quiet
// S_FadeAllSounds( 0, 0 );
}
/*
=====================
CL_ClearState
Called before parsing a gamestate
=====================
*/
void CL_ClearState( void ) {
S_StopAllSounds();
memset( &cl, 0, sizeof( cl ) );
}
/*
====================
CL_UpdateGUID
update cl_guid using QKEY_FILE and optional prefix
====================
*/
static void CL_UpdateGUID( const char *prefix, int prefix_len )
{
fileHandle_t f;
int len;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
if( len != QKEY_SIZE )
Cvar_Set( "cl_guid", "" );
else
Cvar_Set( "cl_guid", Com_MD5File( QKEY_FILE, QKEY_SIZE,
prefix, prefix_len ) );
}
static void CL_OldGame(void)
{
if(cl_oldGameSet)
{
// change back to previous fs_game
cl_oldGameSet = qfalse;
Cvar_Set2("fs_game", cl_oldGame, qtrue);
FS_ConditionalRestart(clc.checksumFeed, qfalse);
}
}
/*
=====================
CL_Disconnect
Called when a connection, demo, or cinematic is being terminated.
Goes from a connected state to either a menu state or a console state
Sends a disconnect message to the server
This is also called on Com_Error and Com_Quit, so it shouldn't cause any errors
=====================
*/
void CL_Disconnect( qboolean showMainMenu ) {
if ( !com_cl_running || !com_cl_running->integer ) {
return;
}
// shutting down the client so enter full screen ui mode
Cvar_Set( "r_uiFullScreen", "1" );
if ( clc.demorecording ) {
CL_StopRecord_f();
}
if ( clc.download ) {
FS_FCloseFile( clc.download );
clc.download = 0;
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
#ifdef USE_MUMBLE
if (cl_useMumble->integer && mumble_islinked()) {
Com_Printf("Mumble: Unlinking from Mumble application\n");
mumble_unlink();
}
#endif
#ifdef USE_VOIP
if (cl_voipSend->integer) {
int tmp = cl_voipUseVAD->integer;
cl_voipUseVAD->integer = 0; // disable this for a moment.
clc.voipOutgoingDataSize = 0; // dump any pending VoIP transmission.
Cvar_Set("cl_voipSend", "0");
CL_CaptureVoip(); // clean up any state...
cl_voipUseVAD->integer = tmp;
}
if (clc.voipCodecInitialized) {
int i;
opus_encoder_destroy(clc.opusEncoder);
for (i = 0; i < MAX_CLIENTS; i++) {
opus_decoder_destroy(clc.opusDecoder[i]);
}
clc.voipCodecInitialized = qfalse;
}
Cmd_RemoveCommand ("voip");
#endif
if ( clc.demofile ) {
FS_FCloseFile( clc.demofile );
clc.demofile = 0;
}
if ( uivm && showMainMenu ) {
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NONE );
}
SCR_StopCinematic();
S_ClearSoundBuffer();
// send a disconnect message to the server
// send it a few times in case one is dropped
if ( clc.state >= CA_CONNECTED ) {
CL_AddReliableCommand("disconnect", qtrue);
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
// Remove pure paks
FS_PureServerSetLoadedPaks("", "");
FS_PureServerSetReferencedPaks( "", "" );
CL_ClearState();
// wipe the client connection
Com_Memset( &clc, 0, sizeof( clc ) );
clc.state = CA_DISCONNECTED;
// allow cheats locally
#ifndef WOLF_SP_DEMO
// except for demo
Cvar_Set( "sv_cheats", "1" );
#endif
// not connected to a pure server anymore
cl_connectedToPureServer = qfalse;
#ifdef USE_VOIP
// not connected to voip server anymore.
clc.voipEnabled = qfalse;
#endif
// Stop recording any video
if( CL_VideoRecording( ) ) {
// Finish rendering current frame
SCR_UpdateScreen( );
CL_CloseAVI( );
}
CL_UpdateGUID( NULL, 0 );
if(!noGameRestart)
CL_OldGame();
else
noGameRestart = qfalse;
}
/*
===================
CL_ForwardCommandToServer
adds the current command line as a clientCommand
things like godmode, noclip, etc, are commands directed to the server,
so when they are typed in at the console, they will need to be forwarded.
===================
*/
void CL_ForwardCommandToServer( const char *string ) {
char *cmd;
cmd = Cmd_Argv( 0 );
// ignore key up commands
if ( cmd[0] == '-' ) {
return;
}
if ( clc.demoplaying || clc.state < CA_CONNECTED || cmd[0] == '+' ) {
Com_Printf ("Unknown command \"%s" S_COLOR_WHITE "\"\n", cmd);
return;
}
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand(string, qfalse);
} else {
CL_AddReliableCommand(cmd, qfalse);
}
}
/*
===================
CL_RequestMotd
===================
*/
void CL_RequestMotd( void ) {
#ifdef UPDATE_SERVER_NAME
char info[MAX_INFO_STRING];
if ( !cl_motd->integer ) {
return;
}
Com_Printf( "Resolving %s\n", UPDATE_SERVER_NAME );
if ( !NET_StringToAdr( UPDATE_SERVER_NAME, &cls.updateServer, NA_IP ) ) {
Com_Printf( "Couldn't resolve address\n" );
return;
}
cls.updateServer.port = BigShort( PORT_UPDATE );
Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", UPDATE_SERVER_NAME,
cls.updateServer.ip[0], cls.updateServer.ip[1],
cls.updateServer.ip[2], cls.updateServer.ip[3],
BigShort( cls.updateServer.port ) );
info[0] = 0;
Com_sprintf( cls.updateChallenge, sizeof( cls.updateChallenge ), "%i", rand() );
Info_SetValueForKey( info, "challenge", cls.updateChallenge );
Info_SetValueForKey( info, "renderer", cls.glconfig.renderer_string );
Info_SetValueForKey( info, "version", com_version->string );
NET_OutOfBandPrint( NS_CLIENT, cls.updateServer, "getmotd \"%s\"\n", info );
#endif
}
/*
===================
CL_RequestAuthorization
Authorization server protocol
-----------------------------
All commands are text in Q3 out of band packets (leading 0xff 0xff 0xff 0xff).
Whenever the client tries to get a challenge from the server it wants to
connect to, it also blindly fires off a packet to the authorize server:
getKeyAuthorize <challenge> <cdkey>
cdkey may be "demo"
#OLD The authorize server returns a:
#OLD
#OLD keyAthorize <challenge> <accept | deny>
#OLD
#OLD A client will be accepted if the cdkey is valid and it has not been used by any other IP
#OLD address in the last 15 minutes.
The server sends a:
getIpAuthorize <challenge> <ip>
The authorize server returns a:
ipAuthorize <challenge> <accept | deny | demo | unknown >
A client will be accepted if a valid cdkey was sent by that ip (only) in the last 15 minutes.
If no response is received from the authorize server after two tries, the client will be let
in anyway.
===================
*/
#ifndef STANDALONE
#ifdef USE_AUTHORIZE_SERVER
void CL_RequestAuthorization( void ) {
char nums[64];
int i, j, l;
cvar_t *fs;
if ( !cls.authorizeServer.port ) {
Com_Printf( "Resolving %s\n", AUTHORIZE_SERVER_NAME );
if ( !NET_StringToAdr( AUTHORIZE_SERVER_NAME, &cls.authorizeServer, NA_IP ) ) {
Com_Printf( "Couldn't resolve address\n" );
return;
}
cls.authorizeServer.port = BigShort( PORT_AUTHORIZE );
Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", AUTHORIZE_SERVER_NAME,
cls.authorizeServer.ip[0], cls.authorizeServer.ip[1],
cls.authorizeServer.ip[2], cls.authorizeServer.ip[3],
BigShort( cls.authorizeServer.port ) );
}
if ( cls.authorizeServer.type == NA_BAD ) {
return;
}
// only grab the alphanumeric values from the cdkey, to avoid any dashes or spaces
j = 0;
l = strlen( cl_cdkey );
if ( l > 32 ) {
l = 32;
}
for ( i = 0 ; i < l ; i++ ) {
if ( ( cl_cdkey[i] >= '0' && cl_cdkey[i] <= '9' )
|| ( cl_cdkey[i] >= 'a' && cl_cdkey[i] <= 'z' )
|| ( cl_cdkey[i] >= 'A' && cl_cdkey[i] <= 'Z' ) ) {
nums[j] = cl_cdkey[i];
j++;
}
}
nums[j] = 0;
fs = Cvar_Get( "cl_anonymous", "0", CVAR_INIT | CVAR_SYSTEMINFO );
NET_OutOfBandPrint(NS_CLIENT, cls.authorizeServer, "getKeyAuthorize %i %s", fs->integer, nums );
}
#endif
#endif
/*
======================================================================
CONSOLE COMMANDS
======================================================================
*/
/*
==================
CL_ForwardToServer_f
==================
*/
void CL_ForwardToServer_f( void ) {
if ( clc.state != CA_ACTIVE || clc.demoplaying ) {
Com_Printf( "Not connected to a server.\n" );
return;
}
// don't forward the first argument
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand(Cmd_Args(), qfalse);
}
}
/*
==================
CL_Disconnect_f
==================
*/
void CL_Disconnect_f( void ) {
SCR_StopCinematic();
// RF, make sure loading variables are turned off
Cvar_Set( "savegame_loading", "0" );
Cvar_Set( "g_reloading", "0" );
if ( clc.state != CA_DISCONNECTED && clc.state != CA_CINEMATIC ) {
Com_Error( ERR_DISCONNECT, "Disconnected from server" );
}
}
/*
================
CL_Reconnect_f
================
*/
void CL_Reconnect_f( void ) {
if ( !strlen( cl_reconnectArgs ) )
return;
Cbuf_AddText( va("connect %s\n", cl_reconnectArgs ) );
}
/*
================
CL_Connect_f
================
*/
void CL_Connect_f( void ) {
char *server;
const char *serverString;
int argc = Cmd_Argc();
netadrtype_t family = NA_UNSPEC;
if ( argc != 2 && argc != 3 ) {
Com_Printf( "usage: connect [-4|-6] server\n");
return;
}
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
// save arguments for reconnect
Q_strncpyz( cl_reconnectArgs, Cmd_Args(), sizeof( cl_reconnectArgs ) );
// starting to load a map so we get out of full screen ui mode
Cvar_Set( "r_uiFullScreen", "0" );
// fire a message off to the motd server
CL_RequestMotd();
// clear any previous "server full" type messages
clc.serverMessage[0] = 0;
if ( com_sv_running->integer && !strcmp( server, "localhost" ) ) {
// if running a local server, kill it
SV_Shutdown( "Server quit" );
}
// make sure a local server is killed
Cvar_Set( "sv_killserver", "1" );
SV_Frame( 0 );
noGameRestart = qtrue;
CL_Disconnect( qtrue );
Con_Close();
Q_strncpyz( clc.servername, server, sizeof(clc.servername) );
if (!NET_StringToAdr(clc.servername, &clc.serverAddress, family) ) {
Com_Printf( "Bad server address\n" );
clc.state = CA_DISCONNECTED;
return;
}
if ( clc.serverAddress.port == 0 ) {
clc.serverAddress.port = BigShort( PORT_SERVER );
}
serverString = NET_AdrToStringwPort(clc.serverAddress);
Com_Printf( "%s resolved to %s\n", clc.servername, serverString);
if( cl_guidServerUniq->integer )
CL_UpdateGUID( serverString, strlen( serverString ) );
else
CL_UpdateGUID( NULL, 0 );
// if we aren't playing on a lan, we need to authenticate
// with the cd key
if(NET_IsLocalAddress(clc.serverAddress))
clc.state = CA_CHALLENGING;
else
{
clc.state = CA_CONNECTING;
// Set a client challenge number that ideally is mirrored back by the server.
clc.challenge = ((rand() << 16) ^ rand()) ^ Com_Milliseconds();
}
Key_SetCatcher( 0 );
clc.connectTime = -99999; // CL_CheckForResend() will fire immediately
clc.connectPacketCount = 0;
// server connection string
Cvar_Set( "cl_currentServerAddress", server );
}
#define MAX_RCON_MESSAGE 1024
/*
==================
CL_CompleteRcon
==================
*/
static void CL_CompleteRcon( char *args, int argNum )
{
if( argNum == 2 )
{
// Skip "rcon "
char *p = Com_SkipTokens( args, 1, " " );
if( p > args )
Field_CompleteCommand( p, qtrue, qtrue );
}
}
/*
=====================
CL_Rcon_f
Send the rest of the command line over as
an unconnected command.
=====================
*/
void CL_Rcon_f( void ) {
char message[MAX_RCON_MESSAGE];
netadr_t to;
if ( !rcon_client_password->string[0] ) {
Com_Printf( "You must set 'rconpassword' before\n"
"issuing an rcon command.\n" );
return;
}
message[0] = -1;
message[1] = -1;
message[2] = -1;
message[3] = -1;
message[4] = 0;
Q_strcat (message, MAX_RCON_MESSAGE, "rcon ");
Q_strcat (message, MAX_RCON_MESSAGE, rcon_client_password->string);
Q_strcat (message, MAX_RCON_MESSAGE, " ");
Q_strcat (message, MAX_RCON_MESSAGE, Cmd_Cmd()+5);
if ( clc.state >= CA_CONNECTED ) {
to = clc.netchan.remoteAddress;
} else {
if ( !strlen( rconAddress->string ) ) {
Com_Printf( "You must either be connected,\n"
"or set the 'rconAddress' cvar\n"
"to issue rcon commands\n" );
return;
}
NET_StringToAdr (rconAddress->string, &to, NA_UNSPEC);
if ( to.port == 0 ) {
to.port = BigShort( PORT_SERVER );
}
}
NET_SendPacket( NS_CLIENT, strlen( message ) + 1, message, to );
}
/*
=================
CL_SendPureChecksums
=================
*/
void CL_SendPureChecksums( void ) {
char cMsg[MAX_INFO_VALUE];
// if we are pure we need to send back a command with our referenced pk3 checksums
Com_sprintf(cMsg, sizeof(cMsg), "cp %d %s", cl.serverId, FS_ReferencedPakPureChecksums());
CL_AddReliableCommand(cMsg, qfalse);
}
/*
=================
CL_ResetPureClientAtServer
=================
*/
void CL_ResetPureClientAtServer( void ) {
CL_AddReliableCommand("vdr", qfalse);
}
/*
=================
CL_Vid_Restart_f
Restart the video subsystem
we also have to reload the UI and CGame because the renderer
doesn't know what graphics to reload
=================
*/
void CL_Vid_Restart_f( void ) {
vmCvar_t musicCvar;
// RF, don't show percent bar, since the memory usage will just sit at the same level anyway
Cvar_Set( "com_expectedhunkusage", "-1" );
// Settings may have changed so stop recording now
if( CL_VideoRecording( ) ) {
CL_CloseAVI( );
}
if(clc.demorecording)
CL_StopRecord_f();
// don't let them loop during the restart
S_StopAllSounds();
if(!FS_ConditionalRestart(clc.checksumFeed, qtrue))
{
// if not running a server clear the whole hunk
if(com_sv_running->integer)
{
// clear all the client data on the hunk
Hunk_ClearToMark();
}
else
{
// clear the whole hunk
Hunk_Clear();
}
// shutdown the UI
CL_ShutdownUI();
// shutdown the CGame
CL_ShutdownCGame();
// shutdown the renderer and clear the renderer interface
CL_ShutdownRef();
// client is no longer pure untill new checksums are sent
CL_ResetPureClientAtServer();
// clear pak references
FS_ClearPakReferences( FS_UI_REF | FS_CGAME_REF );
// reinitialize the filesystem if the game directory or checksum has changed
cls.rendererStarted = qfalse;
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.soundRegistered = qfalse;
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
// initialize the renderer interface
CL_InitRef();
// startup all the client stuff
CL_StartHunkUsers(qfalse);
// start the cgame if connected
if(clc.state > CA_CONNECTED && clc.state != CA_CINEMATIC)
{
cls.cgameStarted = qtrue;
CL_InitCGame();
// send pure checksums
CL_SendPureChecksums();
}
// start music if there was any
Cvar_Register( &musicCvar, "s_currentMusic", "", CVAR_ROM );
if ( strlen( musicCvar.string ) ) {
S_StartBackgroundTrack( musicCvar.string, musicCvar.string );
}
// fade up volume
// S_FadeAllSounds( 1, 0 );
}
}
/*
=================
CL_Snd_Shutdown
Shut down the sound subsystem
=================
*/
void CL_Snd_Shutdown(void)
{
S_Shutdown();
cls.soundStarted = qfalse;
}
/*
=================
CL_Snd_Restart_f
Restart the sound subsystem
The cgame and game must also be forced to restart because
handles will be invalid
=================
*/
void CL_Snd_Restart_f(void)
{
CL_Snd_Shutdown();
// sound will be reinitialized by vid_restart
CL_Vid_Restart_f();
}
/*
==================
CL_PK3List_f
==================
*/
void CL_OpenedPK3List_f( void ) {
Com_Printf( "Opened PK3 Names: %s\n", FS_LoadedPakNames() );
}
/*
==================
CL_PureList_f
==================
*/
void CL_ReferencedPK3List_f( void ) {
Com_Printf( "Referenced PK3 Names: %s\n", FS_ReferencedPakNames() );
}
/*
==================
CL_Configstrings_f
==================
*/
void CL_Configstrings_f( void ) {
int i;
int ofs;
if ( clc.state != CA_ACTIVE ) {
Com_Printf( "Not connected to a server.\n" );
return;
}
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
ofs = cl.gameState.stringOffsets[ i ];
if ( !ofs ) {
continue;
}
Com_Printf( "%4i: %s\n", i, cl.gameState.stringData + ofs );
}
}
/*
==============
CL_Clientinfo_f
==============
*/
void CL_Clientinfo_f( void ) {
Com_Printf( "--------- Client Information ---------\n" );
Com_Printf( "state: %i\n", clc.state );
Com_Printf( "Server: %s\n", clc.servername );
Com_Printf( "User info settings:\n" );
Info_Print( Cvar_InfoString( CVAR_USERINFO ) );
Com_Printf( "--------------------------------------\n" );
}
//====================================================================
/*
=================
CL_DownloadsComplete
Called when all downloading has been completed
=================
*/
void CL_DownloadsComplete( void ) {
#ifdef USE_CURL
// if we downloaded with cURL
if(clc.cURLUsed) {
clc.cURLUsed = qfalse;
CL_cURL_Shutdown();
if( clc.cURLDisconnected ) {
if(clc.downloadRestart) {
FS_Restart(clc.checksumFeed);
clc.downloadRestart = qfalse;
}
clc.cURLDisconnected = qfalse;
CL_Reconnect_f();
return;
}
}
#endif
// if we downloaded files we need to restart the file system
if ( clc.downloadRestart ) {
clc.downloadRestart = qfalse;
FS_Restart( clc.checksumFeed ); // We possibly downloaded a pak, restart the file system to load it
// inform the server so we get new gamestate info
CL_AddReliableCommand( "donedl", qfalse );
// by sending the donedl command we request a new gamestate
// so we don't want to load stuff yet
return;
}
// let the client game init and load data
clc.state = CA_LOADING;
Com_EventLoop();
// if the gamestate was changed by calling Com_EventLoop
// then we loaded everything already and we don't want to do it again.
if ( clc.state != CA_LOADING ) {
return;
}
// starting to load a map so we get out of full screen ui mode
Cvar_Set( "r_uiFullScreen", "0" );
// flush client memory and start loading stuff
// this will also (re)load the UI
// if this is a local client then only the client part of the hunk
// will be cleared, note that this is done after the hunk mark has been set
CL_FlushMemory();
// initialize the CGame
cls.cgameStarted = qtrue;
CL_InitCGame();
// set pure checksums
CL_SendPureChecksums();
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
/*
=================
CL_BeginDownload
Requests a file to download from the server. Stores it in the current
game directory.
=================
*/
void CL_BeginDownload( const char *localName, const char *remoteName ) {
Com_DPrintf( "***** CL_BeginDownload *****\n"
"Localname: %s\n"
"Remotename: %s\n"
"****************************\n", localName, remoteName );
Q_strncpyz( clc.downloadName, localName, sizeof( clc.downloadName ) );
Com_sprintf( clc.downloadTempName, sizeof( clc.downloadTempName ), "%s.tmp", localName );
// Set so UI gets access to it
Cvar_Set( "cl_downloadName", remoteName );
Cvar_Set( "cl_downloadSize", "0" );
Cvar_Set( "cl_downloadCount", "0" );
Cvar_SetValue( "cl_downloadTime", cls.realtime );
clc.downloadBlock = 0; // Starting new file
clc.downloadCount = 0;
CL_AddReliableCommand( va( "download %s", remoteName ), qfalse );
}
/*
=================
CL_NextDownload
A download completed or failed
=================
*/
void CL_NextDownload( void ) {
char *s;
char *remoteName, *localName;
qboolean useCURL = qfalse;
// A download has finished, check whether this matches a referenced checksum
if( *clc.downloadName ) {
char *zippath = FS_BuildOSPath(Cvar_VariableString("fs_homepath"), clc.downloadName, "");
zippath[strlen(zippath)-1] = '\0';
if(!FS_CompareZipChecksum(zippath))
Com_Error(ERR_DROP, "Incorrect checksum for file: %s", clc.downloadName);
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set("cl_downloadName", "");
// We are looking to start a download here
if ( *clc.downloadList ) {
s = clc.downloadList;
// format is:
// @remotename@localname@remotename@localname, etc.
if ( *s == '@' ) {
s++;
}
remoteName = s;
if ( ( s = strchr( s, '@' ) ) == NULL ) {
CL_DownloadsComplete();
return;
}
*s++ = 0;
localName = s;
if ( ( s = strchr( s, '@' ) ) != NULL ) {
*s++ = 0;
} else {
s = localName + strlen( localName ); // point at the nul byte
}
#ifdef USE_CURL
if(!(cl_allowDownload->integer & DLF_NO_REDIRECT)) {
if(clc.sv_allowDownload & DLF_NO_REDIRECT) {
Com_Printf("WARNING: server does not "
"allow download redirection "
"(sv_allowDownload is %d)\n",
clc.sv_allowDownload);
}
else if(!*clc.sv_dlURL) {
Com_Printf("WARNING: server allows "
"download redirection, but does not "
"have sv_dlURL set\n");
}
else if(!CL_cURL_Init()) {
Com_Printf("WARNING: could not load "
"cURL library\n");
}
else {
CL_cURL_BeginDownload(localName, va("%s/%s",
clc.sv_dlURL, remoteName));
useCURL = qtrue;
}
}
else if(!(clc.sv_allowDownload & DLF_NO_REDIRECT)) {
Com_Printf("WARNING: server allows download "
"redirection, but it disabled by client "
"configuration (cl_allowDownload is %d)\n",
cl_allowDownload->integer);
}
#endif /* USE_CURL */
if(!useCURL) {
if((cl_allowDownload->integer & DLF_NO_UDP)) {
Com_Error(ERR_DROP, "UDP Downloads are "
"disabled on your client. "
"(cl_allowDownload is %d)",
cl_allowDownload->integer);
return;
}
else {
CL_BeginDownload( localName, remoteName );
}
}
clc.downloadRestart = qtrue;
// move over the rest
memmove( clc.downloadList, s, strlen( s ) + 1 );
return;
}
CL_DownloadsComplete();
}
/*
=================
CL_InitDownloads
After receiving a valid game state, we valid the cgame and local zip files here
and determine if we need to download them
=================
*/
void CL_InitDownloads( void ) {
char missingfiles[1024];
if ( !(cl_allowDownload->integer & DLF_ENABLE) ) {
// autodownload is disabled on the client
// but it's possible that some referenced files on the server are missing
if (FS_ComparePaks( missingfiles, sizeof( missingfiles ), qfalse ) ) {
// NOTE TTimo I would rather have that printed as a modal message box
// but at this point while joining the game we don't know wether we will successfully join or not
Com_Printf( "\nWARNING: You are missing some files referenced by the server:\n%s"
"You might not be able to join the game\n"
"Go to the setting menu to turn on autodownload, or get the file elsewhere\n\n", missingfiles );
}
}
else if ( FS_ComparePaks( clc.downloadList, sizeof( clc.downloadList ) , qtrue ) ) {
Com_Printf("Need paks: %s\n", clc.downloadList );
if ( *clc.downloadList ) {
// if autodownloading is not enabled on the server
clc.state = CA_CONNECTED;
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
CL_NextDownload();
return;
}
}
CL_DownloadsComplete();
}
/*
=================
CL_CheckForResend
Resend a connect message if the last one has timed out
=================
*/
void CL_CheckForResend( void ) {
int port;
char info[MAX_INFO_STRING];
char data[MAX_INFO_STRING + 10];
// don't send anything if playing back a demo
if ( clc.demoplaying ) {
return;
}
// resend if we haven't gotten a reply yet
if ( clc.state != CA_CONNECTING && clc.state != CA_CHALLENGING ) {
return;
}
if ( cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT ) {
return;
}
clc.connectTime = cls.realtime; // for retransmit requests
clc.connectPacketCount++;
switch ( clc.state ) {
case CA_CONNECTING:
// requesting a challenge .. IPv6 users always get in as authorize server supports no ipv6.
#ifndef STANDALONE
#ifdef USE_AUTHORIZE_SERVER
if (!com_standalone->integer && clc.serverAddress.type == NA_IP && !Sys_IsLANAddress( clc.serverAddress ) )
CL_RequestAuthorization();
#endif
#endif
// The challenge request shall be followed by a client challenge so no malicious server can hijack this connection.
// Add the gamename so the server knows we're running the correct game or can reject the client
// with a meaningful message
Com_sprintf(data, sizeof(data), "getchallenge %d %s", clc.challenge, com_gamename->string);
NET_OutOfBandPrint(NS_CLIENT, clc.serverAddress, "%s", data);
break;
case CA_CHALLENGING:
// sending back the challenge
port = Cvar_VariableValue( "net_qport" );
Q_strncpyz( info, Cvar_InfoString( CVAR_USERINFO ), sizeof( info ) );
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer == com_protocol->integer)
clc.compat = qtrue;
if(clc.compat)
Info_SetValueForKey(info, "protocol", va("%i", com_legacyprotocol->integer));
else
#endif
Info_SetValueForKey( info, "protocol", va("%i", com_protocol->integer ) );
Info_SetValueForKey( info, "qport", va( "%i", port ) );
Info_SetValueForKey( info, "challenge", va( "%i", clc.challenge ) );
Com_sprintf( data, sizeof(data), "connect \"%s\"", info );
NET_OutOfBandData( NS_CLIENT, clc.serverAddress, (byte *) data, strlen ( data ) );
// the most current userinfo has been sent, so watch for any
// newer changes to userinfo variables
cvar_modifiedFlags &= ~CVAR_USERINFO;
break;
default:
Com_Error( ERR_FATAL, "CL_CheckForResend: bad clc.state" );
}
}
/*
===================
CL_MotdPacket
===================
*/
void CL_MotdPacket( netadr_t from ) {
#ifdef UPDATE_SERVER_NAME
char *challenge;
char *info;
// if not from our server, ignore it
if ( !NET_CompareAdr( from, cls.updateServer ) ) {
return;
}
info = Cmd_Argv( 1 );
// check challenge
challenge = Info_ValueForKey( info, "challenge" );
if ( strcmp( challenge, cls.updateChallenge ) ) {
return;
}
challenge = Info_ValueForKey( info, "motd" );
Q_strncpyz( cls.updateInfoString, info, sizeof( cls.updateInfoString ) );
Cvar_Set( "cl_motdString", challenge );
#endif
}
/*
===================
CL_InitServerInfo
===================
*/
void CL_InitServerInfo( serverInfo_t *server, netadr_t *address ) {
server->adr = *address;
server->clients = 0;
server->hostName[0] = '\0';
server->mapName[0] = '\0';
server->maxClients = 0;
server->maxPing = 0;
server->minPing = 0;
server->ping = -1;
server->game[0] = '\0';
server->gameType = 0;
server->netType = 0;
server->g_humanplayers = 0;
server->g_needpass = 0;
server->allowAnonymous = 0;
}
#define MAX_SERVERSPERPACKET 256
/*
===================
CL_ServersResponsePacket
===================
*/
void CL_ServersResponsePacket( const netadr_t* from, msg_t *msg, qboolean extended ) {
int i, j, count, total;
netadr_t addresses[MAX_SERVERSPERPACKET];
int numservers;
byte* buffptr;
byte* buffend;
Com_Printf( "CL_ServersResponsePacket\n" );
if ( cls.numglobalservers == -1 ) {
// state to detect lack of servers or lack of response
cls.numglobalservers = 0;
cls.numGlobalServerAddresses = 0;
}
// parse through server response string
numservers = 0;
buffptr = msg->data;
buffend = buffptr + msg->cursize;
// advance to initial token
do
{
if(*buffptr == '\\' || (extended && *buffptr == '/'))
break;
buffptr++;
} while (buffptr < buffend);
while (buffptr + 1 < buffend)
{
// IPv4 address
if (*buffptr == '\\')
{
buffptr++;
if (buffend - buffptr < sizeof(addresses[numservers].ip) + sizeof(addresses[numservers].port) + 1)
break;
for(i = 0; i < sizeof(addresses[numservers].ip); i++)
addresses[numservers].ip[i] = *buffptr++;
addresses[numservers].type = NA_IP;
}
// IPv6 address, if it's an extended response
else if (extended && *buffptr == '/')
{
buffptr++;
if (buffend - buffptr < sizeof(addresses[numservers].ip6) + sizeof(addresses[numservers].port) + 1)
break;
for(i = 0; i < sizeof(addresses[numservers].ip6); i++)
addresses[numservers].ip6[i] = *buffptr++;
addresses[numservers].type = NA_IP6;
addresses[numservers].scope_id = from->scope_id;
}
else
// syntax error!
break;
// parse out port
addresses[numservers].port = (*buffptr++) << 8;
addresses[numservers].port += *buffptr++;
addresses[numservers].port = BigShort( addresses[numservers].port );
// syntax check
if (*buffptr != '\\' && *buffptr != '/')
break;
numservers++;
if (numservers >= MAX_SERVERSPERPACKET)
break;
}
count = cls.numglobalservers;
for (i = 0; i < numservers && count < MAX_GLOBAL_SERVERS; i++) {
// build net address
serverInfo_t *server = &cls.globalServers[count];
// Tequila: It's possible to have sent many master server requests. Then
// we may receive many times the same addresses from the master server.
// We just avoid to add a server if it is still in the global servers list.
for (j = 0; j < count; j++)
{
if (NET_CompareAdr(cls.globalServers[j].adr, addresses[i]))
break;
}
if (j < count)
continue;
CL_InitServerInfo( server, &addresses[i] );
// advance to next slot
count++;
}
// if getting the global list
if ( count >= MAX_GLOBAL_SERVERS && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS )
{
// if we couldn't store the servers in the main list anymore
for (; i < numservers && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS; i++)
{
// just store the addresses in an additional list
cls.globalServerAddresses[cls.numGlobalServerAddresses++] = addresses[i];
}
}
cls.numglobalservers = count;
total = count + cls.numGlobalServerAddresses;
Com_Printf( "%d servers parsed (total %d)\n", numservers, total );
}
/*
=================
CL_ConnectionlessPacket
Responses to broadcasts, etc
=================
*/
void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) {
char *s;
char *c;
int challenge = 0;
MSG_BeginReadingOOB( msg );
MSG_ReadLong( msg ); // skip the -1
s = MSG_ReadStringLine( msg );
Cmd_TokenizeString( s );
c = Cmd_Argv( 0 );
Com_DPrintf ("CL packet %s: %s\n", NET_AdrToStringwPort(from), c);
// challenge from the server we are connecting to
if (!Q_stricmp(c, "challengeResponse"))
{
char *strver;
int ver;
if (clc.state != CA_CONNECTING)
{
Com_DPrintf("Unwanted challenge response received. Ignored.\n");
return;
}
c = Cmd_Argv( 2 );
if(*c)
challenge = atoi(c);
strver = Cmd_Argv( 3 );
if(*strver)
{
ver = atoi(strver);
if(ver != com_protocol->integer)
{
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer > 0)
{
// Server is ioq3 but has a different protocol than we do.
// Fall back to idq3 protocol.
clc.compat = qtrue;
Com_Printf(S_COLOR_YELLOW "Warning: Server reports protocol version %d, "
"we have %d. Trying legacy protocol %d.\n",
ver, com_protocol->integer, com_legacyprotocol->integer);
}
else
#endif
{
Com_Printf(S_COLOR_YELLOW "Warning: Server reports protocol version %d, we have %d. "
"Trying anyways.\n", ver, com_protocol->integer);
}
}
}
#ifdef LEGACY_PROTOCOL
else
clc.compat = qtrue;
if(clc.compat)
{
if(!NET_CompareAdr(from, clc.serverAddress))
{
// This challenge response is not coming from the expected address.
// Check whether we have a matching client challenge to prevent
// connection hi-jacking.
if(!*c || challenge != clc.challenge)
{
Com_DPrintf("Challenge response received from unexpected source. Ignored.\n");
return;
}
}
}
else
#endif
{
if(!*c || challenge != clc.challenge)
{
Com_Printf("Bad challenge for challengeResponse. Ignored.\n");
return;
}
}
// start sending challenge response instead of challenge request packets
clc.challenge = atoi(Cmd_Argv(1));
clc.state = CA_CHALLENGING;
clc.connectPacketCount = 0;
clc.connectTime = -99999;
// take this address as the new server address. This allows
// a server proxy to hand off connections to multiple servers
clc.serverAddress = from;
Com_DPrintf ("challengeResponse: %d\n", clc.challenge);
return;
}
// server connection
if ( !Q_stricmp( c, "connectResponse" ) ) {
if ( clc.state >= CA_CONNECTED ) {
Com_Printf( "Dup connect received. Ignored.\n" );
return;
}
if ( clc.state != CA_CHALLENGING ) {
Com_Printf( "connectResponse packet while not connecting. Ignored.\n" );
return;
}
if ( !NET_CompareAdr( from, clc.serverAddress ) ) {
Com_Printf( "connectResponse from wrong address. Ignored.\n" );
return;
}
#ifdef LEGACY_PROTOCOL
if(!clc.compat)
#endif
{
c = Cmd_Argv(1);
if(*c)
challenge = atoi(c);
else
{
Com_Printf("Bad connectResponse received. Ignored.\n");
return;
}
if(challenge != clc.challenge)
{
Com_Printf("ConnectResponse with bad challenge received. Ignored.\n");
return;
}
}
#ifdef LEGACY_PROTOCOL
Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableValue("net_qport"),
clc.challenge, clc.compat);
#else
Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableValue("net_qport"),
clc.challenge, qfalse);
#endif
clc.state = CA_CONNECTED;
clc.lastPacketSentTime = -9999; // send first packet immediately
return;
}
// server responding to an info broadcast
if ( !Q_stricmp( c, "infoResponse" ) ) {
CL_ServerInfoPacket( from, msg );
return;
}
// server responding to a get playerlist
if ( !Q_stricmp( c, "statusResponse" ) ) {
CL_ServerStatusResponse( from, msg );
return;
}
// echo request from server
if ( !Q_stricmp( c, "echo" ) ) {
NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv( 1 ) );
return;
}
// cd check
if ( !Q_stricmp( c, "keyAuthorize" ) ) {
// we don't use these now, so dump them on the floor
return;
}
// global MOTD from id
if ( !Q_stricmp( c, "motd" ) ) {
CL_MotdPacket( from );
return;
}
// echo request from server
if ( !Q_stricmp( c, "print" ) ) {
s = MSG_ReadString( msg );
Q_strncpyz( clc.serverMessage, s, sizeof( clc.serverMessage ) );
Com_Printf( "%s", s );
return;
}
// list of servers sent back by a master server (classic)
if ( !Q_strncmp( c, "getserversResponse", 18 ) ) {
CL_ServersResponsePacket( &from, msg, qfalse );
return;
}
// list of servers sent back by a master server (extended)
if ( !Q_strncmp(c, "getserversExtResponse", 21) ) {
CL_ServersResponsePacket( &from, msg, qtrue );
return;
}
Com_DPrintf( "Unknown connectionless packet command.\n" );
}
/*
=================
CL_PacketEvent
A packet has arrived from the main event loop
=================
*/
void CL_PacketEvent( netadr_t from, msg_t *msg ) {
int headerBytes;
clc.lastPacketTime = cls.realtime;
if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) {
CL_ConnectionlessPacket( from, msg );
return;
}
if ( clc.state < CA_CONNECTED ) {
return; // can't be a valid sequenced packet
}
if ( msg->cursize < 4 ) {
Com_Printf ("%s: Runt packet\n", NET_AdrToStringwPort( from ));
return;
}
//
// packet from server
//
if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
Com_DPrintf( "%s:sequenced packet without connection\n"
, NET_AdrToStringwPort( from ) );
// FIXME: send a client disconnect?
return;
}
if ( !CL_Netchan_Process( &clc.netchan, msg ) ) {
return; // out of order, duplicated, etc
}
// the header is different lengths for reliable and unreliable messages
headerBytes = msg->readcount;
// track the last message received so it can be returned in
// client messages, allowing the server to detect a dropped
// gamestate
clc.serverMessageSequence = LittleLong( *(int *)msg->data );
clc.lastPacketTime = cls.realtime;
CL_ParseServerMessage( msg );
//
// we don't know if it is ok to save a demo message until
// after we have parsed the frame
//
if ( clc.demorecording && !clc.demowaiting ) {
CL_WriteDemoMessage( msg, headerBytes );
}
}
/*
==================
CL_CheckTimeout
==================
*/
void CL_CheckTimeout( void ) {
//
// check timeout
//
if ( ( !CL_CheckPaused() || !sv_paused->integer )
&& clc.state >= CA_CONNECTED && clc.state != CA_CINEMATIC
&& cls.realtime - clc.lastPacketTime > cl_timeout->value * 1000 ) {
if ( ++cl.timeoutcount > 5 ) { // timeoutcount saves debugger
Com_Printf( "\nServer connection timed out.\n" );
CL_Disconnect( qtrue );
return;
}
} else {
cl.timeoutcount = 0;
}
}
/*
==================
CL_CheckPaused
Check whether client has been paused.
==================
*/
qboolean CL_CheckPaused(void)
{
// if cl_paused->modified is set, the cvar has only been changed in
// this frame. Keep paused in this frame to ensure the server doesn't
// lag behind.
if(cl_paused->integer || cl_paused->modified)
return qtrue;
return qfalse;
}
//============================================================================
/*
==================
CL_CheckUserinfo
==================
*/
void CL_CheckUserinfo( void ) {
// don't add reliable commands when not yet connected
if(clc.state < CA_CONNECTED)
return;
// don't overflow the reliable command buffer when paused
if(CL_CheckPaused())
return;
// send a reliable userinfo update if needed
if ( cvar_modifiedFlags & CVAR_USERINFO ) {
cvar_modifiedFlags &= ~CVAR_USERINFO;
CL_AddReliableCommand(va("userinfo \"%s\"", Cvar_InfoString( CVAR_USERINFO ) ), qfalse);
}
}
/*
==================
CL_Frame
==================
*/
void CL_Frame( int msec ) {
if ( !com_cl_running->integer ) {
return;
}
#ifdef USE_CURL
if(clc.downloadCURLM) {
CL_cURL_PerformDownload();
// we can't process frames normally when in disconnected
// download mode since the ui vm expects clc.state to be
// CA_CONNECTED
if(clc.cURLDisconnected) {
cls.realFrametime = msec;
cls.frametime = msec;
cls.realtime += cls.frametime;
SCR_UpdateScreen();
S_Update();
Con_RunConsole();
cls.framecount++;
return;
}
}
#endif
if ( cls.cddialog ) {
// bring up the cd error dialog if needed
cls.cddialog = qfalse;
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NEED_CD );
} else if ( cls.endgamemenu ) {
cls.endgamemenu = qfalse;
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_ENDGAME );
} else if ( clc.state == CA_DISCONNECTED && !( Key_GetCatcher( ) & KEYCATCH_UI )
&& !com_sv_running->integer && uivm ) {
// if disconnected, bring up the menu
S_StopAllSounds();
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_MAIN );
}
// if recording an avi, lock to a fixed fps
if ( ( CL_VideoRecording( ) && cl_aviFrameRate->integer && msec ) || ( cl_avidemo->integer && msec ) ) {
// save the current screen
if ( clc.state == CA_ACTIVE || cl_forceavidemo->integer ) {
if ( cl_avidemo->integer ) { // Legacy (screenshot) method
Cbuf_ExecuteText( EXEC_NOW, "screenshot silent\n" );
// fixed time for next frame
msec = ( 1000 / cl_avidemo->integer ) * com_timescale->value;
if ( msec == 0 ) {
msec = 1;
}
} else { // ioquake3 method
float fps = MIN(cl_aviFrameRate->value * com_timescale->value, 1000.0f);
float frameDuration = MAX(1000.0f / fps, 1.0f) + clc.aviVideoFrameRemainder;
CL_TakeVideoFrame( );
msec = (int)frameDuration;
clc.aviVideoFrameRemainder = frameDuration - msec;
}
}
}
if( cl_autoRecordDemo->integer ) {
if( clc.state == CA_ACTIVE && !clc.demorecording && !clc.demoplaying ) {
// If not recording a demo, and we should be, start one
qtime_t now;
char *nowString;
char *p;
char mapName[ MAX_QPATH ];
char serverName[ MAX_OSPATH ];
Com_RealTime( &now );
nowString = va( "%04d%02d%02d%02d%02d%02d",
1900 + now.tm_year,
1 + now.tm_mon,
now.tm_mday,
now.tm_hour,
now.tm_min,
now.tm_sec );
Q_strncpyz( serverName, clc.servername, MAX_OSPATH );
// Replace the ":" in the address as it is not a valid
// file name character
p = strstr( serverName, ":" );
if( p ) {
*p = '.';
}
Q_strncpyz( mapName, COM_SkipPath( cl.mapname ), sizeof( cl.mapname ) );
COM_StripExtension(mapName, mapName, sizeof(mapName));
Cbuf_ExecuteText( EXEC_NOW,
va( "record %s-%s-%s", nowString, serverName, mapName ) );
}
else if( clc.state != CA_ACTIVE && clc.demorecording ) {
// Recording, but not CA_ACTIVE, so stop recording
CL_StopRecord_f( );
}
}
// save the msec before checking pause
cls.realFrametime = msec;
// decide the simulation time
cls.frametime = msec;
cls.realtime += cls.frametime;
if ( cl_timegraph->integer ) {
SCR_DebugGraph ( cls.realFrametime * 0.25 );
}
// see if we need to update any userinfo
CL_CheckUserinfo();
// if we haven't gotten a packet in a long time,
// drop the connection
CL_CheckTimeout();
// send intentions now
CL_SendCmd();
// resend a connection request if necessary
CL_CheckForResend();
// decide on the serverTime to render
CL_SetCGameTime();
// update the screen
SCR_UpdateScreen();
// update audio
S_Update();
#ifdef USE_VOIP
CL_CaptureVoip();
#endif
#ifdef USE_MUMBLE
CL_UpdateMumble();
#endif
// advance local effects for next frame
SCR_RunCinematic();
Con_RunConsole();
cls.framecount++;
}
//============================================================================
// Ridah, startup-caching system
typedef struct {
char name[MAX_QPATH];
int hits;
int lastSetIndex;
} cacheItem_t;
typedef enum {
CACHE_SOUNDS,
CACHE_MODELS,
CACHE_IMAGES,
CACHE_NUMGROUPS
} cacheGroup_t;
static cacheItem_t cacheGroups[CACHE_NUMGROUPS] = {
{{'s','o','u','n','d',0}, CACHE_SOUNDS},
{{'m','o','d','e','l',0}, CACHE_MODELS},
{{'i','m','a','g','e',0}, CACHE_IMAGES},
};
#define MAX_CACHE_ITEMS 4096
#define CACHE_HIT_RATIO 0.75 // if hit on this percentage of maps, it'll get cached
static int cacheIndex;
static cacheItem_t cacheItems[CACHE_NUMGROUPS][MAX_CACHE_ITEMS];
static void CL_Cache_StartGather_f( void ) {
cacheIndex = 0;
memset( cacheItems, 0, sizeof( cacheItems ) );
Cvar_Set( "cl_cacheGathering", "1" );
}
static void CL_Cache_UsedFile_f( void ) {
char groupStr[MAX_QPATH];
char itemStr[MAX_QPATH];
int i,group;
cacheItem_t *item;
if ( Cmd_Argc() < 2 ) {
Com_Error( ERR_DROP, "usedfile without enough parameters\n" );
return;
}
strcpy( groupStr, Cmd_Argv( 1 ) );
strcpy( itemStr, Cmd_Argv( 2 ) );
for ( i = 3; i < Cmd_Argc(); i++ ) {
strcat( itemStr, " " );
strcat( itemStr, Cmd_Argv( i ) );
}
Q_strlwr( itemStr );
// find the cache group
for ( i = 0; i < CACHE_NUMGROUPS; i++ ) {
if ( !Q_strncmp( groupStr, cacheGroups[i].name, MAX_QPATH ) ) {
break;
}
}
if ( i == CACHE_NUMGROUPS ) {
Com_Error( ERR_DROP, "usedfile without a valid cache group\n" );
return;
}
// see if it's already there
group = i;
for ( i = 0, item = cacheItems[group]; i < MAX_CACHE_ITEMS; i++, item++ ) {
if ( !item->name[0] ) {
// didn't find it, so add it here
Q_strncpyz( item->name, itemStr, MAX_QPATH );
if ( cacheIndex > 9999 ) { // hack, but yeh
item->hits = cacheIndex;
} else {
item->hits++;
}
item->lastSetIndex = cacheIndex;
break;
}
if ( item->name[0] == itemStr[0] && !Q_strncmp( item->name, itemStr, MAX_QPATH ) ) {
if ( item->lastSetIndex != cacheIndex ) {
item->hits++;
item->lastSetIndex = cacheIndex;
}
break;
}
}
}
static void CL_Cache_SetIndex_f( void ) {
if ( Cmd_Argc() < 2 ) {
Com_Error( ERR_DROP, "setindex needs an index\n" );
return;
}
cacheIndex = atoi( Cmd_Argv( 1 ) );
}
static void CL_Cache_MapChange_f( void ) {
cacheIndex++;
}
static void CL_Cache_EndGather_f( void ) {
// save the frequently used files to the cache list file
int i, j, handle, cachePass;
char filename[MAX_QPATH];
cachePass = (int)floor( (float)cacheIndex * CACHE_HIT_RATIO );
for ( i = 0; i < CACHE_NUMGROUPS; i++ ) {
Q_strncpyz( filename, cacheGroups[i].name, MAX_QPATH );
Q_strcat( filename, MAX_QPATH, ".cache" );
handle = FS_FOpenFileWrite( filename );
for ( j = 0; j < MAX_CACHE_ITEMS; j++ ) {
// if it's a valid filename, and it's been hit enough times, cache it
if ( cacheItems[i][j].hits >= cachePass && strstr( cacheItems[i][j].name, "/" ) ) {
FS_Write( cacheItems[i][j].name, strlen( cacheItems[i][j].name ), handle );
FS_Write( "\n", 1, handle );
}
}
FS_FCloseFile( handle );
}
Cvar_Set( "cl_cacheGathering", "0" );
}
// done.
//============================================================================
/*
================
CL_MapRestart_f
================
*/
void CL_MapRestart_f( void ) {
if ( !com_cl_running ) {
return;
}
if ( !com_cl_running->integer ) {
return;
}
Com_Printf( "This command is no longer functional.\nUse \"loadgame current\" to load the current map." );
}
/*
================
CL_SetRecommended_f
================
*/
void CL_SetRecommended_f( void ) {
if ( Cmd_Argc() > 1 ) {
Com_SetRecommended( qtrue );
} else {
Com_SetRecommended( qfalse );
}
}
/*
================
CL_RefPrintf
DLL glue
================
*/
static __attribute__ ((format (printf, 2, 3))) void QDECL CL_RefPrintf( int print_level, const char *fmt, ...) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof ( msg ), fmt, argptr );
va_end( argptr );
if ( print_level == PRINT_ALL ) {
Com_Printf( "%s", msg );
} else if ( print_level == PRINT_WARNING ) {
Com_Printf( S_COLOR_YELLOW "%s", msg ); // yellow
} else if ( print_level == PRINT_DEVELOPER ) {
Com_DPrintf( S_COLOR_RED "%s", msg ); // red
}
}
/*
============
CL_ShutdownRef
============
*/
void CL_ShutdownRef( void ) {
if ( re.Shutdown ) {
re.Shutdown( qtrue );
}
memset( &re, 0, sizeof( re ) );
#ifdef USE_RENDERER_DLOPEN
if ( rendererLib ) {
Sys_UnloadLibrary( rendererLib );
rendererLib = NULL;
}
#endif
}
/*
============
CL_InitRenderer
============
*/
void CL_InitRenderer( void ) {
// this sets up the renderer and calls R_Init
re.BeginRegistration( &cls.glconfig );
// load character sets
cls.charSetShader = re.RegisterShader( "gfx/2d/bigchars" );
cls.whiteShader = re.RegisterShader( "white" );
cls.consoleShader = re.RegisterShader( "console" );
cls.consoleShader2 = re.RegisterShader( "console2" );
g_console_field_width = cls.glconfig.vidWidth / SMALLCHAR_WIDTH - 2;
g_consoleField.widthInChars = g_console_field_width;
}
/*
============================
CL_StartHunkUsers
After the server has cleared the hunk, these will need to be restarted
This is the only place that any of these functions are called from
============================
*/
void CL_StartHunkUsers( qboolean rendererOnly ) {
if ( !com_cl_running ) {
return;
}
if ( !com_cl_running->integer ) {
return;
}
if ( !cls.rendererStarted ) {
cls.rendererStarted = qtrue;
CL_InitRenderer();
}
if ( rendererOnly ) {
return;
}
if ( !cls.soundStarted ) {
cls.soundStarted = qtrue;
S_Init();
}
if ( !cls.soundRegistered ) {
cls.soundRegistered = qtrue;
S_BeginRegistration();
}
if( com_dedicated->integer ) {
return;
}
if ( !cls.uiStarted ) {
cls.uiStarted = qtrue;
CL_InitUI();
}
}
int CL_ScaledMilliseconds( void ) {
return Sys_Milliseconds() * com_timescale->value;
}
/*
============
CL_InitRef
============
*/
void CL_InitRef( void ) {
refimport_t ri;
refexport_t *ret;
#ifdef USE_RENDERER_DLOPEN
GetRefAPI_t GetRefAPI;
char dllName[MAX_OSPATH];
#endif
Com_Printf( "----- Initializing Renderer ----\n" );
#ifdef USE_RENDERER_DLOPEN
cl_renderer = Cvar_Get("cl_renderer", "opengl1", CVAR_ARCHIVE | CVAR_LATCH);
Com_sprintf(dllName, sizeof(dllName), "renderer_sp_%s_" ARCH_STRING DLL_EXT, cl_renderer->string);
if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString))
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Cvar_ForceReset("cl_renderer");
Com_sprintf(dllName, sizeof(dllName), "renderer_sp_opengl1_" ARCH_STRING DLL_EXT);
rendererLib = Sys_LoadDll(dllName, qfalse);
}
if(!rendererLib)
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Com_Error(ERR_FATAL, "Failed to load renderer");
}
GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI");
if(!GetRefAPI)
{
Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError());
}
#endif
ri.Cmd_AddCommand = Cmd_AddCommand;
ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
ri.Cmd_Argc = Cmd_Argc;
ri.Cmd_Argv = Cmd_Argv;
ri.Cmd_ExecuteText = Cbuf_ExecuteText;
ri.Printf = CL_RefPrintf;
ri.Error = Com_Error;
ri.Milliseconds = CL_ScaledMilliseconds;
ri.Z_Malloc = Z_Malloc;
ri.Free = Z_Free;
ri.Hunk_Clear = Hunk_ClearToMark;
#ifdef HUNK_DEBUG
ri.Hunk_AllocDebug = Hunk_AllocDebug;
#else
ri.Hunk_Alloc = Hunk_Alloc;
#endif
ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
ri.CM_ClusterPVS = CM_ClusterPVS;
ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
ri.FS_ReadFile = FS_ReadFile;
ri.FS_FreeFile = FS_FreeFile;
ri.FS_WriteFile = FS_WriteFile;
ri.FS_FreeFileList = FS_FreeFileList;
ri.FS_ListFiles = FS_ListFiles;
ri.FS_FileIsInPAK = FS_FileIsInPAK;
ri.FS_FileExists = FS_FileExists;
ri.Cvar_Get = Cvar_Get;
ri.Cvar_Set = Cvar_Set;
ri.Cvar_SetValue = Cvar_SetValue;
ri.Cvar_CheckRange = Cvar_CheckRange;
ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
// cinematic stuff
ri.CIN_UploadCinematic = CIN_UploadCinematic;
ri.CIN_PlayCinematic = CIN_PlayCinematic;
ri.CIN_RunCinematic = CIN_RunCinematic;
ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;
ri.IN_Init = IN_Init;
ri.IN_Shutdown = IN_Shutdown;
ri.IN_Restart = IN_Restart;
ri.ftol = Q_ftol;
ri.Sys_SetEnv = Sys_SetEnv;
ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit;
ri.Sys_GLimpInit = Sys_GLimpInit;
ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;
ret = GetRefAPI( REF_API_VERSION, &ri );
if ( !ret ) {
Com_Error( ERR_FATAL, "Couldn't initialize refresh" );
}
re = *ret;
Com_Printf( "---- Renderer Initialization Complete ----\n" );
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
}
// RF, trap manual client damage commands so users can't issue them manually
void CL_ClientDamageCommand( void ) {
// do nothing
}
#if defined (__i386__)
#define BIN_STRING "x86"
#endif
// NERVE - SMF
void CL_startMultiplayer_f( void ) {
char binName[MAX_OSPATH];
#if defined(_WIN64) || defined(__WIN64__)
Com_sprintf(binName, sizeof(binName), "ioWolfMP." ARCH_STRING ".exe");
Sys_StartProcess( binName, qtrue );
#elif defined(_WIN32) || defined(__WIN32__)
Com_sprintf(binName, sizeof(binName), "ioWolfMP." ARCH_STRING ".exe");
Sys_StartProcess( binName, qtrue );
#elif defined(__i386__) && (!defined(_WIN32) || !defined(__WIN32__))
Com_sprintf(binName, sizeof(binName), "./iowolfmp." BIN_STRING );
Sys_StartProcess( binName, qtrue );
#else
Com_sprintf(binName, sizeof(binName), "./iowolfmp." ARCH_STRING );
Sys_StartProcess( binName, qtrue );
#endif
}
// -NERVE - SMF
//----(SA) added
/*
==============
CL_ShellExecute_URL_f
Format:
shellExecute "open" <url> <doExit>
TTimo
show_bug.cgi?id=447
only supporting "open" syntax for URL openings, others are not portable or need to be added on a case-by-case basis
the shellExecute syntax as been kept to remain compatible with win32 SP demo pk3, but this thing only does open URL
==============
*/
void CL_ShellExecute_URL_f( void ) {
qboolean doexit;
Com_DPrintf( "CL_ShellExecute_URL_f\n" );
if ( Q_stricmp( Cmd_Argv( 1 ),"open" ) ) {
Com_DPrintf( "invalid CL_ShellExecute_URL_f syntax (shellExecute \"open\" <url> <doExit>)\n" );
return;
}
if ( Cmd_Argc() < 4 ) {
doexit = qtrue;
} else {
doexit = (qboolean)( atoi( Cmd_Argv( 3 ) ) );
}
Sys_OpenURL( Cmd_Argv( 2 ),doexit );
}
//----(SA) end
//===========================================================================================
/*
===============
CL_Video_f
video
video [filename]
===============
*/
void CL_Video_f( void )
{
char filename[ MAX_OSPATH ];
int i, last;
if( !clc.demoplaying )
{
Com_Printf( "The video command can only be used when playing back demos\n" );
return;
}
if( Cmd_Argc( ) == 2 )
{
// explicit filename
Com_sprintf( filename, MAX_OSPATH, "videos/%s.avi", Cmd_Argv( 1 ) );
}
else
{
// scan for a free filename
for( i = 0; i <= 9999; i++ )
{
int a, b, c, d;
last = i;
a = last / 1000;
last -= a * 1000;
b = last / 100;
last -= b * 100;
c = last / 10;
last -= c * 10;
d = last;
Com_sprintf( filename, MAX_OSPATH, "videos/video%d%d%d%d.avi", a, b, c, d );
if( !FS_FileExists( filename ) )
break; // file doesn't exist
}
if( i > 9999 )
{
Com_Printf( S_COLOR_RED "ERROR: no free file names to create video\n" );
return;
}
}
CL_OpenAVIForWriting( filename );
}
/*
===============
CL_StopVideo_f
===============
*/
void CL_StopVideo_f( void )
{
CL_CloseAVI( );
}
/*
===============
CL_GenerateQKey
test to see if a valid QKEY_FILE exists. If one does not, try to generate
it by filling it with 2048 bytes of random data.
===============
*/
static void CL_GenerateQKey(void)
{
int len = 0;
unsigned char buff[ QKEY_SIZE ];
fileHandle_t f;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
if( len == QKEY_SIZE ) {
Com_Printf( "RTCWKEY found.\n" );
return;
}
else {
if( len > 0 ) {
Com_Printf( "RTCWKEY file size != %d, regenerating\n",
QKEY_SIZE );
}
Com_Printf( "RTCWKEY building random string\n" );
Com_RandomBytes( buff, sizeof(buff) );
f = FS_SV_FOpenFileWrite( QKEY_FILE );
if( !f ) {
Com_Printf( "RTCWKEY could not open %s for write\n",
QKEY_FILE );
return;
}
FS_Write( buff, sizeof(buff), f );
FS_FCloseFile( f );
Com_Printf( "RTCWKEY generated\n" );
}
}
/*
====================
CL_Init
====================
*/
void CL_Init( void ) {
Com_Printf( "----- Client Initialization -----\n" );
Con_Init();
if(!com_fullyInitialized)
{
CL_ClearState();
clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
cl_oldGameSet = qfalse;
}
cls.realtime = 0;
CL_InitInput();
//
// register our variables
//
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
#ifdef UPDATE_SERVER_NAME
cl_motd = Cvar_Get( "cl_motd", "1", 0 );
#endif
cl_timeout = Cvar_Get( "cl_timeout", "200", 0 );
cl_timeNudge = Cvar_Get( "cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get( "cl_shownet", "0", CVAR_TEMP );
cl_showSend = Cvar_Get( "cl_showSend", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get( "cl_showTimeDelta", "0", CVAR_TEMP );
cl_freezeDemo = Cvar_Get( "cl_freezeDemo", "0", CVAR_TEMP );
rcon_client_password = Cvar_Get( "rconPassword", "", CVAR_TEMP );
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_timedemo = Cvar_Get( "timedemo", "0", 0 );
cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE);
cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE);
cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE);
cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE);
cl_avidemo = Cvar_Get( "cl_avidemo", "0", 0 );
cl_forceavidemo = Cvar_Get( "cl_forceavidemo", "0", 0 );
rconAddress = Cvar_Get( "rconAddress", "", 0 );
cl_yawspeed = Cvar_Get( "cl_yawspeed", "140", CVAR_ARCHIVE );
cl_pitchspeed = Cvar_Get( "cl_pitchspeed", "140", CVAR_ARCHIVE );
cl_anglespeedkey = Cvar_Get( "cl_anglespeedkey", "1.5", 0 );
cl_maxpackets = Cvar_Get( "cl_maxpackets", "38", CVAR_ARCHIVE );
cl_packetdup = Cvar_Get( "cl_packetdup", "1", CVAR_ARCHIVE );
cl_run = Cvar_Get( "cl_run", "1", CVAR_ARCHIVE );
cl_sensitivity = Cvar_Get( "sensitivity", "5", CVAR_ARCHIVE );
cl_mouseAccel = Cvar_Get( "cl_mouseAccel", "0", CVAR_ARCHIVE );
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE );
// 0: legacy mouse acceleration
// 1: new implementation
cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE );
// offset for the power function (for style 1, ignored otherwise)
// this should be set to the max rate value
cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE );
Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse);
cl_showMouseRate = Cvar_Get( "cl_showmouserate", "0", 0 );
cl_allowDownload = Cvar_Get( "cl_allowDownload", "0", CVAR_ARCHIVE );
#ifdef USE_CURL_DLOPEN
cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE);
#endif
// init autoswitch so the ui will have it correctly even
// if the cgame hasn't been started
Cvar_Get( "cg_autoswitch", "2", CVAR_ARCHIVE );
// Rafael - particle switch
Cvar_Get( "cg_wolfparticles", "1", CVAR_ARCHIVE );
// done
cl_conXOffset = Cvar_Get( "cl_conXOffset", "0", 0 );
cl_inGameVideo = Cvar_Get( "r_inGameVideo", "1", CVAR_ARCHIVE );
cl_serverStatusResendTime = Cvar_Get( "cl_serverStatusResendTime", "750", 0 );
// RF
cl_recoilPitch = Cvar_Get( "cg_recoilPitch", "0", CVAR_ROM );
m_pitch = Cvar_Get( "m_pitch", "0.022", CVAR_ARCHIVE );
m_yaw = Cvar_Get( "m_yaw", "0.022", CVAR_ARCHIVE );
m_forward = Cvar_Get( "m_forward", "0.25", CVAR_ARCHIVE );
m_side = Cvar_Get( "m_side", "0.25", CVAR_ARCHIVE );
m_filter = Cvar_Get( "m_filter", "0", CVAR_ARCHIVE );
j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE);
j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE);
j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE);
j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE);
j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE);
j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE);
j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE);
j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE);
j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE);
j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE);
Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM );
Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE );
cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE);
cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE);
// ~ and `, as keys and characters
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE);
// userinfo
Cvar_Get( "name", "WolfPlayer", CVAR_USERINFO | CVAR_ARCHIVE );
cl_rate = Cvar_Get( "rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE ); // NERVE - SMF - changed from 3000
Cvar_Get( "snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "model", "bj2", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "head", "default", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "color", "4", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "sex", "male", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "password", "", CVAR_USERINFO );
Cvar_Get( "cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE );
#ifdef USE_MUMBLE
cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH);
cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE);
#endif
#ifdef USE_VOIP
cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0);
cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0);
cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE);
cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE);
cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE);
cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE);
cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE);
cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE);
Cvar_CheckRange( cl_voip, 0, 1, qtrue );
cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM);
#endif
//----(SA) added
Cvar_Get( "cg_autoactivate", "1", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "cg_emptyswitch", "0", CVAR_USERINFO | CVAR_ARCHIVE );
//----(SA) end
// cgame might not be initialized before menu is used
Cvar_Get( "cg_viewsize", "100", CVAR_ARCHIVE );
// Make sure cg_stereoSeparation is zero as that variable is deprecated and should not be used anymore.
Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM);
cl_missionStats = Cvar_Get( "g_missionStats", "0", CVAR_ROM );
cl_waitForFire = Cvar_Get( "cl_waitForFire", "0", CVAR_ROM );
// NERVE - SMF - localization
cl_language = Cvar_Get( "cl_language", "0", CVAR_ARCHIVE );
cl_debugTranslation = Cvar_Get( "cl_debugTranslation", "0", 0 );
// -NERVE - SMF
//
// register our commands
//
Cmd_AddCommand( "cmd", CL_ForwardToServer_f );
Cmd_AddCommand( "configstrings", CL_Configstrings_f );
Cmd_AddCommand( "clientinfo", CL_Clientinfo_f );
Cmd_AddCommand( "snd_restart", CL_Snd_Restart_f );
Cmd_AddCommand( "vid_restart", CL_Vid_Restart_f );
Cmd_AddCommand( "disconnect", CL_Disconnect_f );
Cmd_AddCommand( "record", CL_Record_f );
Cmd_AddCommand( "demo", CL_PlayDemo_f );
Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName );
Cmd_AddCommand( "cinematic", CL_PlayCinematic_f );
Cmd_AddCommand( "stoprecord", CL_StopRecord_f );
Cmd_AddCommand( "connect", CL_Connect_f );
Cmd_AddCommand( "reconnect", CL_Reconnect_f );
Cmd_AddCommand( "localservers", CL_LocalServers_f );
Cmd_AddCommand( "globalservers", CL_GlobalServers_f );
Cmd_AddCommand( "rcon", CL_Rcon_f );
Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon );
Cmd_AddCommand( "ping", CL_Ping_f );
Cmd_AddCommand( "serverstatus", CL_ServerStatus_f );
Cmd_AddCommand( "showip", CL_ShowIP_f );
Cmd_AddCommand( "fs_openedList", CL_OpenedPK3List_f );
Cmd_AddCommand( "fs_referencedList", CL_ReferencedPK3List_f );
Cmd_AddCommand ("video", CL_Video_f );
Cmd_AddCommand ("stopvideo", CL_StopVideo_f );
// Ridah, startup-caching system
Cmd_AddCommand( "cache_startgather", CL_Cache_StartGather_f );
Cmd_AddCommand( "cache_usedfile", CL_Cache_UsedFile_f );
Cmd_AddCommand( "cache_setindex", CL_Cache_SetIndex_f );
Cmd_AddCommand( "cache_mapchange", CL_Cache_MapChange_f );
Cmd_AddCommand( "cache_endgather", CL_Cache_EndGather_f );
Cmd_AddCommand( "updatehunkusage", CL_UpdateLevelHunkUsage );
Cmd_AddCommand( "updatescreen", SCR_UpdateScreen );
// done.
// RF, add this command so clients can't bind a key to send client damage commands to the server
Cmd_AddCommand( "cld", CL_ClientDamageCommand );
Cmd_AddCommand( "startMultiplayer", CL_startMultiplayer_f ); // NERVE - SMF
Cmd_AddCommand( "shellExecute", CL_ShellExecute_URL_f );
// RF, prevent users from issuing a map_restart manually
Cmd_AddCommand( "map_restart", CL_MapRestart_f );
Cmd_AddCommand( "setRecommended", CL_SetRecommended_f );
CL_InitRef();
SCR_Init();
// Cbuf_Execute();
Cvar_Set( "cl_running", "1" );
CL_GenerateQKey();
Cvar_Get( "cl_guid", "", CVAR_USERINFO | CVAR_ROM );
CL_UpdateGUID( NULL, 0 );
Com_Printf( "----- Client Initialization Complete -----\n" );
}
/*
===============
CL_Shutdown
===============
*/
void CL_Shutdown( char *finalmsg, qboolean disconnect, qboolean quit ) {
static qboolean recursive = qfalse;
// check whether the client is running at all.
if(!(com_cl_running && com_cl_running->integer))
return;
Com_Printf( "----- Client Shutdown (%s) -----\n", finalmsg );
if ( recursive ) {
Com_Printf( "WARNING: Recursive shutdown\n" );
return;
}
recursive = qtrue;
noGameRestart = quit;
if(disconnect)
CL_Disconnect(qtrue);
CL_ClearMemory(qtrue);
CL_Snd_Shutdown();
Cmd_RemoveCommand( "cmd" );
Cmd_RemoveCommand( "configstrings" );
Cmd_RemoveCommand ("clientinfo");
Cmd_RemoveCommand( "snd_restart" );
Cmd_RemoveCommand( "vid_restart" );
Cmd_RemoveCommand( "disconnect" );
Cmd_RemoveCommand( "record" );
Cmd_RemoveCommand( "demo" );
Cmd_RemoveCommand( "cinematic" );
Cmd_RemoveCommand( "stoprecord" );
Cmd_RemoveCommand( "connect" );
Cmd_RemoveCommand ("reconnect");
Cmd_RemoveCommand( "localservers" );
Cmd_RemoveCommand( "globalservers" );
Cmd_RemoveCommand( "rcon" );
Cmd_RemoveCommand( "ping" );
Cmd_RemoveCommand( "serverstatus" );
Cmd_RemoveCommand( "showip" );
Cmd_RemoveCommand ("fs_openedList");
Cmd_RemoveCommand ("fs_referencedList");
Cmd_RemoveCommand( "model" );
Cmd_RemoveCommand ("video");
Cmd_RemoveCommand ("stopvideo");
// Ridah, startup-caching system
Cmd_RemoveCommand( "cache_startgather" );
Cmd_RemoveCommand( "cache_usedfile" );
Cmd_RemoveCommand( "cache_setindex" );
Cmd_RemoveCommand( "cache_mapchange" );
Cmd_RemoveCommand( "cache_endgather" );
Cmd_RemoveCommand( "updatehunkusage" );
// done.
CL_ShutdownInput();
Con_Shutdown();
Cvar_Set( "cl_running", "0" );
recursive = qfalse;
memset( &cls, 0, sizeof( cls ) );
Key_SetCatcher( 0 );
Com_Printf( "-----------------------\n" );
}
static void CL_SetServerInfo( serverInfo_t *server, const char *info, int ping ) {
if ( server ) {
if ( info ) {
server->clients = atoi( Info_ValueForKey( info, "clients" ) );
Q_strncpyz( server->hostName,Info_ValueForKey( info, "hostname" ), MAX_NAME_LENGTH );
Q_strncpyz( server->mapName, Info_ValueForKey( info, "mapname" ), MAX_NAME_LENGTH );
server->maxClients = atoi( Info_ValueForKey( info, "sv_maxclients" ) );
Q_strncpyz( server->game,Info_ValueForKey( info, "game" ), MAX_NAME_LENGTH );
server->gameType = atoi( Info_ValueForKey( info, "gametype" ) );
server->netType = atoi( Info_ValueForKey( info, "nettype" ) );
server->minPing = atoi( Info_ValueForKey( info, "minping" ) );
server->maxPing = atoi( Info_ValueForKey( info, "maxping" ) );
server->g_humanplayers = atoi( Info_ValueForKey( info, "g_humanplayers" ) );
server->g_needpass = atoi( Info_ValueForKey( info, "g_needpass" ) );
server->allowAnonymous = atoi( Info_ValueForKey( info, "sv_allowAnonymous" ) );
}
server->ping = ping;
}
}
static void CL_SetServerInfoByAddress( netadr_t from, const char *info, int ping ) {
int i;
for ( i = 0; i < MAX_OTHER_SERVERS; i++ ) {
if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) {
CL_SetServerInfo( &cls.localServers[i], info, ping );
}
}
for ( i = 0; i < MAX_GLOBAL_SERVERS; i++ ) {
if ( NET_CompareAdr( from, cls.globalServers[i].adr ) ) {
CL_SetServerInfo( &cls.globalServers[i], info, ping );
}
}
for ( i = 0; i < MAX_OTHER_SERVERS; i++ ) {
if ( NET_CompareAdr( from, cls.favoriteServers[i].adr ) ) {
CL_SetServerInfo( &cls.favoriteServers[i], info, ping );
}
}
}
/*
===================
CL_ServerInfoPacket
===================
*/
void CL_ServerInfoPacket( netadr_t from, msg_t *msg ) {
int i, type;
char info[MAX_INFO_STRING];
char *infoString;
int prot;
char *gamename;
qboolean gameMismatch;
infoString = MSG_ReadString( msg );
// if this isn't the correct gamename, ignore it
gamename = Info_ValueForKey( infoString, "gamename" );
#ifdef LEGACY_PROTOCOL
// gamename is optional for legacy protocol
if (com_legacyprotocol->integer && !*gamename)
gameMismatch = qfalse;
else
#endif
gameMismatch = !*gamename || strcmp(gamename, com_gamename->string) != 0;
if (gameMismatch)
{
Com_DPrintf( "Game mismatch in info packet: %s\n", infoString );
return;
}
// if this isn't the correct protocol version, ignore it
prot = atoi( Info_ValueForKey( infoString, "protocol" ) );
if(prot != com_protocol->integer
#ifdef LEGACY_PROTOCOL
&& prot != com_legacyprotocol->integer
#endif
)
{
Com_DPrintf( "Different protocol info packet: %s\n", infoString );
// return;
}
// iterate servers waiting for ping response
for ( i = 0; i < MAX_PINGREQUESTS; i++ )
{
if ( cl_pinglist[i].adr.port && !cl_pinglist[i].time && NET_CompareAdr( from, cl_pinglist[i].adr ) ) {
// calc ping time
cl_pinglist[i].time = Sys_Milliseconds() - cl_pinglist[i].start;
Com_DPrintf( "ping time %dms from %s\n", cl_pinglist[i].time, NET_AdrToString( from ) );
// save of info
Q_strncpyz( cl_pinglist[i].info, infoString, sizeof( cl_pinglist[i].info ) );
// tack on the net type
// NOTE: make sure these types are in sync with the netnames strings in the UI
switch ( from.type )
{
case NA_BROADCAST:
case NA_IP:
type = 1;
break;
case NA_IP6:
type = 2;
break;
default:
type = 0;
break;
}
Info_SetValueForKey( cl_pinglist[i].info, "nettype", va( "%d", type ) );
CL_SetServerInfoByAddress( from, infoString, cl_pinglist[i].time );
return;
}
}
// if not just sent a local broadcast or pinging local servers
if ( cls.pingUpdateSource != AS_LOCAL ) {
return;
}
for ( i = 0 ; i < MAX_OTHER_SERVERS ; i++ ) {
// empty slot
if ( cls.localServers[i].adr.port == 0 ) {
break;
}
// avoid duplicate
if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) {
return;
}
}
if ( i == MAX_OTHER_SERVERS ) {
Com_DPrintf( "MAX_OTHER_SERVERS hit, dropping infoResponse\n" );
return;
}
// add this to the list
cls.numlocalservers = i + 1;
CL_InitServerInfo( &cls.localServers[i], &from );
Q_strncpyz( info, MSG_ReadString( msg ), MAX_INFO_STRING );
if ( strlen( info ) ) {
if ( info[strlen( info ) - 1] != '\n' ) {
Q_strcat( info, sizeof(info), "\n" );
}
Com_Printf( "%s: %s", NET_AdrToStringwPort( from ), info );
}
}
/*
===================
CL_GetServerStatus
===================
*/
serverStatus_t *CL_GetServerStatus( netadr_t from ) {
int i, oldest, oldestTime;
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
return &cl_serverStatusList[i];
}
}
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( cl_serverStatusList[i].retrieved ) {
return &cl_serverStatusList[i];
}
}
oldest = -1;
oldestTime = 0;
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( oldest == -1 || cl_serverStatusList[i].startTime < oldestTime ) {
oldest = i;
oldestTime = cl_serverStatusList[i].startTime;
}
}
return &cl_serverStatusList[oldest];
}
/*
===================
CL_ServerStatus
===================
*/
int CL_ServerStatus( char *serverAddress, char *serverStatusString, int maxLen ) {
int i;
netadr_t to;
serverStatus_t *serverStatus;
// if no server address then reset all server status requests
if ( !serverAddress ) {
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
cl_serverStatusList[i].address.port = 0;
cl_serverStatusList[i].retrieved = qtrue;
}
return qfalse;
}
// get the address
if ( !NET_StringToAdr( serverAddress, &to, NA_UNSPEC) ) {
return qfalse;
}
serverStatus = CL_GetServerStatus( to );
// if no server status string then reset the server status request for this address
if ( !serverStatusString ) {
serverStatus->retrieved = qtrue;
return qfalse;
}
// if this server status request has the same address
if ( NET_CompareAdr( to, serverStatus->address ) ) {
// if we received a response for this server status request
if ( !serverStatus->pending ) {
Q_strncpyz( serverStatusString, serverStatus->string, maxLen );
serverStatus->retrieved = qtrue;
serverStatus->startTime = 0;
return qtrue;
}
// resend the request regularly
else if ( serverStatus->startTime < Com_Milliseconds() - cl_serverStatusResendTime->integer ) {
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->time = 0;
serverStatus->startTime = Com_Milliseconds();
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
}
// if retrieved
else if ( serverStatus->retrieved ) {
serverStatus->address = to;
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->startTime = Com_Milliseconds();
serverStatus->time = 0;
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
return qfalse;
}
/*
===================
CL_ServerStatusResponse
===================
*/
void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) {
char *s;
char info[MAX_INFO_STRING];
int i, l, score, ping;
int len;
serverStatus_t *serverStatus;
serverStatus = NULL;
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
serverStatus = &cl_serverStatusList[i];
break;
}
}
// if we didn't request this server status
if ( !serverStatus ) {
return;
}
s = MSG_ReadStringLine( msg );
len = 0;
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "%s", s );
if ( serverStatus->print ) {
Com_Printf( "Server settings:\n" );
// print cvars
while ( *s ) {
for ( i = 0; i < 2 && *s; i++ ) {
if ( *s == '\\' ) {
s++;
}
l = 0;
while ( *s ) {
info[l++] = *s;
if ( l >= MAX_INFO_STRING - 1 ) {
break;
}
s++;
if ( *s == '\\' ) {
break;
}
}
info[l] = '\0';
if ( i ) {
Com_Printf( "%s\n", info );
} else {
Com_Printf( "%-24s", info );
}
}
}
}
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\" );
if ( serverStatus->print ) {
Com_Printf( "\nPlayers:\n" );
Com_Printf( "num: score: ping: name:\n" );
}
for ( i = 0, s = MSG_ReadStringLine( msg ); *s; s = MSG_ReadStringLine( msg ), i++ ) {
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\%s", s );
if ( serverStatus->print ) {
score = ping = 0;
sscanf( s, "%d %d", &score, &ping );
s = strchr( s, ' ' );
if ( s ) {
s = strchr( s + 1, ' ' );
}
if ( s ) {
s++;
} else {
s = "unknown";
}
Com_Printf( "%-2d %-3d %-3d %s\n", i, score, ping, s );
}
}
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\" );
serverStatus->time = Com_Milliseconds();
serverStatus->address = from;
serverStatus->pending = qfalse;
if (serverStatus->print) {
serverStatus->retrieved = qtrue;
}
}
/*
==================
CL_LocalServers_f
==================
*/
void CL_LocalServers_f( void ) {
char *message;
int i, j;
netadr_t to;
Com_Printf( "Scanning for servers on the local network...\n" );
// reset the list, waiting for response
cls.numlocalservers = 0;
cls.pingUpdateSource = AS_LOCAL;
for ( i = 0; i < MAX_OTHER_SERVERS; i++ ) {
qboolean b = cls.localServers[i].visible;
Com_Memset( &cls.localServers[i], 0, sizeof( cls.localServers[i] ) );
cls.localServers[i].visible = b;
}
Com_Memset( &to, 0, sizeof( to ) );
// The 'xxx' in the message is a challenge that will be echoed back
// by the server. We don't care about that here, but master servers
// can use that to prevent spoofed server responses from invalid ip
message = "\377\377\377\377getinfo xxx";
// send each message twice in case one is dropped
for ( i = 0 ; i < 2 ; i++ ) {
// send a broadcast packet on each server port
// we support multiple server ports so a single machine
// can nicely run multiple servers
for ( j = 0 ; j < NUM_SERVER_PORTS ; j++ ) {
to.port = BigShort( (short)( PORT_SERVER + j ) );
to.type = NA_BROADCAST;
NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
to.type = NA_MULTICAST6;
NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
}
}
}
/*
==================
CL_GlobalServers_f
==================
*/
void CL_GlobalServers_f( void ) {
netadr_t to;
int count, i, masterNum;
char command[1024], *masteraddress;
if ((count = Cmd_Argc()) < 3 || (masterNum = atoi(Cmd_Argv(1))) < 0 || masterNum > MAX_MASTER_SERVERS - 1)
{
Com_Printf("usage: globalservers <master# 0-%d> <protocol> [keywords]\n", MAX_MASTER_SERVERS - 1);
return;
}
sprintf(command, "sv_master%d", masterNum + 1);
masteraddress = Cvar_VariableString(command);
if(!*masteraddress)
{
Com_Printf( "CL_GlobalServers_f: Error: No master server address given.\n");
return;
}
// reset the list, waiting for response
// -1 is used to distinguish a "no response"
i = NET_StringToAdr(masteraddress, &to, NA_UNSPEC);
if(!i)
{
Com_Printf( "CL_GlobalServers_f: Error: could not resolve address of master %s\n", masteraddress);
return;
}
else if(i == 2)
to.port = BigShort(PORT_MASTER);
Com_Printf("Requesting servers from master %s...\n", masteraddress);
cls.numglobalservers = -1;
cls.pingUpdateSource = AS_GLOBAL;
// Use the extended query for IPv6 masters
if (to.type == NA_IP6 || to.type == NA_MULTICAST6)
{
int v4enabled = Cvar_VariableIntegerValue("net_enabled") & NET_ENABLEV4;
if(v4enabled)
{
Com_sprintf(command, sizeof(command), "getserversExt %s %s",
com_gamename->string, Cmd_Argv(2));
}
else
{
Com_sprintf(command, sizeof(command), "getserversExt %s %s ipv6",
com_gamename->string, Cmd_Argv(2));
}
}
else if ( !Q_stricmp( com_gamename->string, LEGACY_MASTER_GAMENAME ) )
Com_sprintf(command, sizeof(command), "getservers %s",
Cmd_Argv(2));
else
Com_sprintf(command, sizeof(command), "getservers %s %s",
com_gamename->string, Cmd_Argv(2));
for (i=3; i < count; i++)
{
Q_strcat(command, sizeof(command), " ");
Q_strcat(command, sizeof(command), Cmd_Argv(i));
}
NET_OutOfBandPrint( NS_SERVER, to, "%s", command );
}
/*
==================
CL_GetPing
==================
*/
void CL_GetPing( int n, char *buf, int buflen, int *pingtime ) {
const char *str;
int time;
int maxPing;
if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port)
{
// empty or invalid slot
buf[0] = '\0';
*pingtime = 0;
return;
}
str = NET_AdrToStringwPort( cl_pinglist[n].adr );
Q_strncpyz( buf, str, buflen );
time = cl_pinglist[n].time;
if ( !time ) {
// check for timeout
time = Sys_Milliseconds() - cl_pinglist[n].start;
maxPing = Cvar_VariableIntegerValue( "cl_maxPing" );
if ( maxPing < 100 ) {
maxPing = 100;
}
if ( time < maxPing ) {
// not timed out yet
time = 0;
}
}
CL_SetServerInfoByAddress( cl_pinglist[n].adr, cl_pinglist[n].info, cl_pinglist[n].time );
*pingtime = time;
}
/*
==================
CL_GetPingInfo
==================
*/
void CL_GetPingInfo( int n, char *buf, int buflen ) {
if ( n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port ) {
// empty or invalid slot
if ( buflen ) {
buf[0] = '\0';
}
return;
}
Q_strncpyz( buf, cl_pinglist[n].info, buflen );
}
/*
==================
CL_ClearPing
==================
*/
void CL_ClearPing( int n ) {
if ( n < 0 || n >= MAX_PINGREQUESTS ) {
return;
}
cl_pinglist[n].adr.port = 0;
}
/*
==================
CL_GetPingQueueCount
==================
*/
int CL_GetPingQueueCount( void ) {
int i;
int count;
ping_t* pingptr;
count = 0;
pingptr = cl_pinglist;
for ( i = 0; i < MAX_PINGREQUESTS; i++, pingptr++ ) {
if ( pingptr->adr.port ) {
count++;
}
}
return ( count );
}
/*
==================
CL_GetFreePing
==================
*/
ping_t* CL_GetFreePing( void ) {
ping_t* pingptr;
ping_t* best;
int oldest;
int i;
int time;
pingptr = cl_pinglist;
for ( i = 0; i < MAX_PINGREQUESTS; i++, pingptr++ )
{
// find free ping slot
if ( pingptr->adr.port ) {
if ( !pingptr->time ) {
if (Sys_Milliseconds() - pingptr->start < 500)
{
// still waiting for response
continue;
}
} else if ( pingptr->time < 500 ) {
// results have not been queried
continue;
}
}
// clear it
pingptr->adr.port = 0;
return ( pingptr );
}
// use oldest entry
pingptr = cl_pinglist;
best = cl_pinglist;
oldest = INT_MIN;
for ( i = 0; i < MAX_PINGREQUESTS; i++, pingptr++ )
{
// scan for oldest
time = Sys_Milliseconds() - pingptr->start;
if ( time > oldest ) {
oldest = time;
best = pingptr;
}
}
return ( best );
}
/*
==================
CL_Ping_f
==================
*/
void CL_Ping_f( void ) {
netadr_t to;
ping_t* pingptr;
char* server;
int argc;
netadrtype_t family = NA_UNSPEC;
argc = Cmd_Argc();
if ( argc != 2 && argc != 3 ) {
Com_Printf( "usage: ping [-4|-6] server\n");
return;
}
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
Com_Memset( &to, 0, sizeof( netadr_t ) );
if ( !NET_StringToAdr( server, &to, family ) ) {
return;
}
pingptr = CL_GetFreePing();
memcpy( &pingptr->adr, &to, sizeof( netadr_t ) );
pingptr->start = Sys_Milliseconds();
pingptr->time = 0;
CL_SetServerInfoByAddress( pingptr->adr, NULL, 0 );
NET_OutOfBandPrint( NS_CLIENT, to, "getinfo xxx" );
}
/*
==================
CL_UpdateVisiblePings_f
==================
*/
qboolean CL_UpdateVisiblePings_f( int source ) {
int slots, i;
char buff[MAX_STRING_CHARS];
int pingTime;
int max;
qboolean status = qfalse;
if ( source < 0 || source > AS_FAVORITES ) {
return qfalse;
}
cls.pingUpdateSource = source;
slots = CL_GetPingQueueCount();
if ( slots < MAX_PINGREQUESTS ) {
serverInfo_t *server = NULL;
switch ( source ) {
case AS_LOCAL:
server = &cls.localServers[0];
max = cls.numlocalservers;
break;
case AS_GLOBAL:
server = &cls.globalServers[0];
max = cls.numglobalservers;
break;
case AS_FAVORITES:
server = &cls.favoriteServers[0];
max = cls.numfavoriteservers;
break;
default:
return qfalse;
}
for ( i = 0; i < max; i++ ) {
if ( server[i].visible ) {
if ( server[i].ping == -1 ) {
int j;
if ( slots >= MAX_PINGREQUESTS ) {
break;
}
for ( j = 0; j < MAX_PINGREQUESTS; j++ ) {
if ( !cl_pinglist[j].adr.port ) {
continue;
}
if ( NET_CompareAdr( cl_pinglist[j].adr, server[i].adr ) ) {
// already on the list
break;
}
}
if ( j >= MAX_PINGREQUESTS ) {
status = qtrue;
for ( j = 0; j < MAX_PINGREQUESTS; j++ ) {
if ( !cl_pinglist[j].adr.port ) {
break;
}
}
memcpy( &cl_pinglist[j].adr, &server[i].adr, sizeof( netadr_t ) );
cl_pinglist[j].start = Sys_Milliseconds();
cl_pinglist[j].time = 0;
NET_OutOfBandPrint( NS_CLIENT, cl_pinglist[j].adr, "getinfo xxx" );
slots++;
}
}
// if the server has a ping higher than cl_maxPing or
// the ping packet got lost
else if ( server[i].ping == 0 ) {
// if we are updating global servers
if ( source == AS_GLOBAL ) {
//
if ( cls.numGlobalServerAddresses > 0 ) {
// overwrite this server with one from the additional global servers
cls.numGlobalServerAddresses--;
CL_InitServerInfo( &server[i], &cls.globalServerAddresses[cls.numGlobalServerAddresses] );
// NOTE: the server[i].visible flag stays untouched
}
}
}
}
}
}
if ( slots ) {
status = qtrue;
}
for ( i = 0; i < MAX_PINGREQUESTS; i++ ) {
if ( !cl_pinglist[i].adr.port ) {
continue;
}
CL_GetPing( i, buff, MAX_STRING_CHARS, &pingTime );
if ( pingTime != 0 ) {
CL_ClearPing( i );
status = qtrue;
}
}
return status;
}
/*
==================
CL_ServerStatus_f
==================
*/
void CL_ServerStatus_f( void ) {
netadr_t to, *toptr = NULL;
char *server;
serverStatus_t *serverStatus;
int argc;
netadrtype_t family = NA_UNSPEC;
argc = Cmd_Argc();
if ( argc != 2 && argc != 3 )
{
if (clc.state != CA_ACTIVE || clc.demoplaying)
{
Com_Printf( "Not connected to a server.\n" );
Com_Printf( "usage: serverstatus [-4|-6] server\n");
return;
}
toptr = &clc.serverAddress;
}
if(!toptr)
{
Com_Memset( &to, 0, sizeof(netadr_t) );
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
toptr = &to;
if ( !NET_StringToAdr( server, toptr, family ) )
return;
}
NET_OutOfBandPrint( NS_CLIENT, *toptr, "getstatus" );
serverStatus = CL_GetServerStatus( *toptr );
serverStatus->address = *toptr;
serverStatus->print = qtrue;
serverStatus->pending = qtrue;
}
/*
==================
CL_ShowIP_f
==================
*/
void CL_ShowIP_f( void ) {
Sys_ShowIP();
}
/*
=================
CL_CDKeyValidate
=================
*/
qboolean CL_CDKeyValidate( const char *key, const char *checksum ) {
#ifdef STANDALONE
return qtrue;
#else
char ch;
byte sum;
char chs[3];
int i, len;
len = strlen( key );
if ( len != CDKEY_LEN ) {
return qfalse;
}
if ( checksum && strlen( checksum ) != CDCHKSUM_LEN ) {
return qfalse;
}
sum = 0;
// for loop gets rid of conditional assignment warning
for ( i = 0; i < len; i++ ) {
ch = *key++;
if ( ch >= 'a' && ch <= 'z' ) {
ch -= 32;
}
switch ( ch ) {
case '2':
case '3':
case '7':
case 'A':
case 'B':
case 'C':
case 'D':
case 'G':
case 'H':
case 'J':
case 'L':
case 'P':
case 'R':
case 'S':
case 'T':
case 'W':
sum += ch;
continue;
default:
return qfalse;
}
}
sprintf( chs, "%02x", sum );
if ( checksum && !Q_stricmp( chs, checksum ) ) {
return qtrue;
}
if ( !checksum ) {
return qtrue;
}
return qfalse;
#endif
}
// NERVE - SMF
/*
=======================
CL_AddToLimboChat
=======================
*/
void CL_AddToLimboChat( const char *str ) {
int len = 0;
char *p;
int i;
cl.limboChatPos = LIMBOCHAT_HEIGHT - 1;
// copy old strings
for ( i = cl.limboChatPos; i > 0; i-- ) {
strcpy( cl.limboChatMsgs[i], cl.limboChatMsgs[i - 1] );
}
// copy new string
p = cl.limboChatMsgs[0];
*p = 0;
while ( *str ) {
if ( len > LIMBOCHAT_WIDTH - 1 ) {
break;
}
if ( Q_IsColorString( str ) ) {
*p++ = *str++;
*p++ = *str++;
continue;
}
*p++ = *str++;
len++;
}
*p = 0;
}
/*
=======================
CL_GetLimboString
=======================
*/
qboolean CL_GetLimboString( int index, char *buf ) {
if ( index >= LIMBOCHAT_HEIGHT ) {
return qfalse;
}
strncpy( buf, cl.limboChatMsgs[index], 140 );
return qtrue;
}
// -NERVE - SMF
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3233_3 |
crossvul-cpp_data_good_3228_0 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// cl_main.c -- client main loop
#include "client.h"
#include <limits.h>
#include "../sys/sys_local.h"
#include "../sys/sys_loadlib.h"
#ifdef USE_MUMBLE
#include "libmumblelink.h"
#endif
#ifdef USE_MUMBLE
cvar_t *cl_useMumble;
cvar_t *cl_mumbleScale;
#endif
#ifdef USE_VOIP
cvar_t *cl_voipUseVAD;
cvar_t *cl_voipVADThreshold;
cvar_t *cl_voipSend;
cvar_t *cl_voipSendTarget;
cvar_t *cl_voipGainDuringCapture;
cvar_t *cl_voipCaptureMult;
cvar_t *cl_voipShowMeter;
cvar_t *cl_voipProtocol;
cvar_t *cl_voip;
#endif
#ifdef USE_RENDERER_DLOPEN
cvar_t *cl_renderer;
#endif
cvar_t *cl_nodelta;
cvar_t *cl_debugMove;
cvar_t *cl_noprint;
#ifdef UPDATE_SERVER_NAME
cvar_t *cl_motd;
#endif
cvar_t *rcon_client_password;
cvar_t *rconAddress;
cvar_t *cl_timeout;
cvar_t *cl_maxpackets;
cvar_t *cl_packetdup;
cvar_t *cl_timeNudge;
cvar_t *cl_showTimeDelta;
cvar_t *cl_freezeDemo;
cvar_t *cl_shownet;
cvar_t *cl_showSend;
cvar_t *cl_timedemo;
cvar_t *cl_timedemoLog;
cvar_t *cl_autoRecordDemo;
cvar_t *cl_aviFrameRate;
cvar_t *cl_aviMotionJpeg;
cvar_t *cl_forceavidemo;
cvar_t *cl_freelook;
cvar_t *cl_sensitivity;
cvar_t *cl_mouseAccel;
cvar_t *cl_mouseAccelOffset;
cvar_t *cl_mouseAccelStyle;
cvar_t *cl_showMouseRate;
cvar_t *m_pitch;
cvar_t *m_yaw;
cvar_t *m_forward;
cvar_t *m_side;
cvar_t *m_filter;
cvar_t *j_pitch;
cvar_t *j_yaw;
cvar_t *j_forward;
cvar_t *j_side;
cvar_t *j_up;
cvar_t *j_pitch_axis;
cvar_t *j_yaw_axis;
cvar_t *j_forward_axis;
cvar_t *j_side_axis;
cvar_t *j_up_axis;
cvar_t *cl_activeAction;
cvar_t *cl_motdString;
cvar_t *cl_allowDownload;
cvar_t *cl_conXOffset;
cvar_t *cl_inGameVideo;
cvar_t *cl_serverStatusResendTime;
cvar_t *cl_lanForcePackets;
cvar_t *cl_guidServerUniq;
cvar_t *cl_consoleKeys;
cvar_t *cl_rate;
clientActive_t cl;
clientConnection_t clc;
clientStatic_t cls;
vm_t *cgvm;
char cl_reconnectArgs[MAX_OSPATH];
char cl_oldGame[MAX_QPATH];
qboolean cl_oldGameSet;
// Structure containing functions exported from refresh DLL
refexport_t re;
#ifdef USE_RENDERER_DLOPEN
static void *rendererLib = NULL;
#endif
ping_t cl_pinglist[MAX_PINGREQUESTS];
typedef struct serverStatus_s
{
char string[BIG_INFO_STRING];
netadr_t address;
int time, startTime;
qboolean pending;
qboolean print;
qboolean retrieved;
} serverStatus_t;
serverStatus_t cl_serverStatusList[MAX_SERVERSTATUSREQUESTS];
#if defined __USEA3D && defined __A3D_GEOM
void hA3Dg_ExportRenderGeom (refexport_t *incoming_re);
#endif
static int noGameRestart = qfalse;
extern void SV_BotFrame( int time );
void CL_CheckForResend( void );
void CL_ShowIP_f(void);
void CL_ServerStatus_f(void);
void CL_ServerStatusResponse( netadr_t from, msg_t *msg );
/*
===============
CL_CDDialog
Called by Com_Error when a cd is needed
===============
*/
void CL_CDDialog( void ) {
cls.cddialog = qtrue; // start it next frame
}
#ifdef USE_MUMBLE
static
void CL_UpdateMumble(void)
{
vec3_t pos, forward, up;
float scale = cl_mumbleScale->value;
float tmp;
if(!cl_useMumble->integer)
return;
// !!! FIXME: not sure if this is even close to correct.
AngleVectors( cl.snap.ps.viewangles, forward, NULL, up);
pos[0] = cl.snap.ps.origin[0] * scale;
pos[1] = cl.snap.ps.origin[2] * scale;
pos[2] = cl.snap.ps.origin[1] * scale;
tmp = forward[1];
forward[1] = forward[2];
forward[2] = tmp;
tmp = up[1];
up[1] = up[2];
up[2] = tmp;
if(cl_useMumble->integer > 1) {
fprintf(stderr, "%f %f %f, %f %f %f, %f %f %f\n",
pos[0], pos[1], pos[2],
forward[0], forward[1], forward[2],
up[0], up[1], up[2]);
}
mumble_update_coordinates(pos, forward, up);
}
#endif
#ifdef USE_VOIP
static
void CL_UpdateVoipIgnore(const char *idstr, qboolean ignore)
{
if ((*idstr >= '0') && (*idstr <= '9')) {
const int id = atoi(idstr);
if ((id >= 0) && (id < MAX_CLIENTS)) {
clc.voipIgnore[id] = ignore;
CL_AddReliableCommand(va("voip %s %d",
ignore ? "ignore" : "unignore", id), qfalse);
Com_Printf("VoIP: %s ignoring player #%d\n",
ignore ? "Now" : "No longer", id);
return;
}
}
Com_Printf("VoIP: invalid player ID#\n");
}
static
void CL_UpdateVoipGain(const char *idstr, float gain)
{
if ((*idstr >= '0') && (*idstr <= '9')) {
const int id = atoi(idstr);
if (gain < 0.0f)
gain = 0.0f;
if ((id >= 0) && (id < MAX_CLIENTS)) {
clc.voipGain[id] = gain;
Com_Printf("VoIP: player #%d gain now set to %f\n", id, gain);
}
}
}
void CL_Voip_f( void )
{
const char *cmd = Cmd_Argv(1);
const char *reason = NULL;
if (clc.state != CA_ACTIVE)
reason = "Not connected to a server";
else if (!clc.voipCodecInitialized)
reason = "Voip codec not initialized";
else if (!clc.voipEnabled)
reason = "Server doesn't support VoIP";
else if (!clc.demoplaying && (Cvar_VariableValue( "g_gametype" ) == GT_SINGLE_PLAYER || Cvar_VariableValue("ui_singlePlayerActive")))
reason = "running in single-player mode";
if (reason != NULL) {
Com_Printf("VoIP: command ignored: %s\n", reason);
return;
}
if (strcmp(cmd, "ignore") == 0) {
CL_UpdateVoipIgnore(Cmd_Argv(2), qtrue);
} else if (strcmp(cmd, "unignore") == 0) {
CL_UpdateVoipIgnore(Cmd_Argv(2), qfalse);
} else if (strcmp(cmd, "gain") == 0) {
if (Cmd_Argc() > 3) {
CL_UpdateVoipGain(Cmd_Argv(2), atof(Cmd_Argv(3)));
} else if (Q_isanumber(Cmd_Argv(2))) {
int id = atoi(Cmd_Argv(2));
if (id >= 0 && id < MAX_CLIENTS) {
Com_Printf("VoIP: current gain for player #%d "
"is %f\n", id, clc.voipGain[id]);
} else {
Com_Printf("VoIP: invalid player ID#\n");
}
} else {
Com_Printf("usage: voip gain <playerID#> [value]\n");
}
} else if (strcmp(cmd, "muteall") == 0) {
Com_Printf("VoIP: muting incoming voice\n");
CL_AddReliableCommand("voip muteall", qfalse);
clc.voipMuteAll = qtrue;
} else if (strcmp(cmd, "unmuteall") == 0) {
Com_Printf("VoIP: unmuting incoming voice\n");
CL_AddReliableCommand("voip unmuteall", qfalse);
clc.voipMuteAll = qfalse;
} else {
Com_Printf("usage: voip [un]ignore <playerID#>\n"
" voip [un]muteall\n"
" voip gain <playerID#> [value]\n");
}
}
static
void CL_VoipNewGeneration(void)
{
// don't have a zero generation so new clients won't match, and don't
// wrap to negative so MSG_ReadLong() doesn't "fail."
clc.voipOutgoingGeneration++;
if (clc.voipOutgoingGeneration <= 0)
clc.voipOutgoingGeneration = 1;
clc.voipPower = 0.0f;
clc.voipOutgoingSequence = 0;
opus_encoder_ctl(clc.opusEncoder, OPUS_RESET_STATE);
}
/*
===============
CL_VoipParseTargets
sets clc.voipTargets according to cl_voipSendTarget
Generally we don't want who's listening to change during a transmission,
so this is only called when the key is first pressed
===============
*/
void CL_VoipParseTargets(void)
{
const char *target = cl_voipSendTarget->string;
char *end;
int val;
Com_Memset(clc.voipTargets, 0, sizeof(clc.voipTargets));
clc.voipFlags &= ~VOIP_SPATIAL;
while(target)
{
while(*target == ',' || *target == ' ')
target++;
if(!*target)
break;
if(isdigit(*target))
{
val = strtol(target, &end, 10);
target = end;
}
else
{
if(!Q_stricmpn(target, "all", 3))
{
Com_Memset(clc.voipTargets, ~0, sizeof(clc.voipTargets));
return;
}
if(!Q_stricmpn(target, "spatial", 7))
{
clc.voipFlags |= VOIP_SPATIAL;
target += 7;
continue;
}
else
{
if(!Q_stricmpn(target, "attacker", 8))
{
val = VM_Call(cgvm, CG_LAST_ATTACKER);
target += 8;
}
else if(!Q_stricmpn(target, "crosshair", 9))
{
val = VM_Call(cgvm, CG_CROSSHAIR_PLAYER);
target += 9;
}
else
{
while(*target && *target != ',' && *target != ' ')
target++;
continue;
}
if(val < 0)
continue;
}
}
if(val < 0 || val >= MAX_CLIENTS)
{
Com_Printf(S_COLOR_YELLOW "WARNING: VoIP "
"target %d is not a valid client "
"number\n", val);
continue;
}
clc.voipTargets[val / 8] |= 1 << (val % 8);
}
}
/*
===============
CL_CaptureVoip
Record more audio from the hardware if required and encode it into Opus
data for later transmission.
===============
*/
static
void CL_CaptureVoip(void)
{
const float audioMult = cl_voipCaptureMult->value;
const qboolean useVad = (cl_voipUseVAD->integer != 0);
qboolean initialFrame = qfalse;
qboolean finalFrame = qfalse;
#if USE_MUMBLE
// if we're using Mumble, don't try to handle VoIP transmission ourselves.
if (cl_useMumble->integer)
return;
#endif
// If your data rate is too low, you'll get Connection Interrupted warnings
// when VoIP packets arrive, even if you have a broadband connection.
// This might work on rates lower than 25000, but for safety's sake, we'll
// just demand it. Who doesn't have at least a DSL line now, anyhow? If
// you don't, you don't need VoIP. :)
if (cl_voip->modified || cl_rate->modified) {
if ((cl_voip->integer) && (cl_rate->integer < 25000)) {
Com_Printf(S_COLOR_YELLOW "Your network rate is too slow for VoIP.\n");
Com_Printf("Set 'Data Rate' to 'LAN/Cable/xDSL' in 'Setup/System/Network'.\n");
Com_Printf("Until then, VoIP is disabled.\n");
Cvar_Set("cl_voip", "0");
}
Cvar_Set("cl_voipProtocol", cl_voip->integer ? "opus" : "");
cl_voip->modified = qfalse;
cl_rate->modified = qfalse;
}
if (!clc.voipCodecInitialized)
return; // just in case this gets called at a bad time.
if (clc.voipOutgoingDataSize > 0)
return; // packet is pending transmission, don't record more yet.
if (cl_voipUseVAD->modified) {
Cvar_Set("cl_voipSend", (useVad) ? "1" : "0");
cl_voipUseVAD->modified = qfalse;
}
if ((useVad) && (!cl_voipSend->integer))
Cvar_Set("cl_voipSend", "1"); // lots of things reset this.
if (cl_voipSend->modified) {
qboolean dontCapture = qfalse;
if (clc.state != CA_ACTIVE)
dontCapture = qtrue; // not connected to a server.
else if (!clc.voipEnabled)
dontCapture = qtrue; // server doesn't support VoIP.
else if (clc.demoplaying)
dontCapture = qtrue; // playing back a demo.
else if ( cl_voip->integer == 0 )
dontCapture = qtrue; // client has VoIP support disabled.
else if ( audioMult == 0.0f )
dontCapture = qtrue; // basically silenced incoming audio.
cl_voipSend->modified = qfalse;
if(dontCapture)
{
Cvar_Set("cl_voipSend", "0");
return;
}
if (cl_voipSend->integer) {
initialFrame = qtrue;
} else {
finalFrame = qtrue;
}
}
// try to get more audio data from the sound card...
if (initialFrame) {
S_MasterGain(Com_Clamp(0.0f, 1.0f, cl_voipGainDuringCapture->value));
S_StartCapture();
CL_VoipNewGeneration();
CL_VoipParseTargets();
}
if ((cl_voipSend->integer) || (finalFrame)) { // user wants to capture audio?
int samples = S_AvailableCaptureSamples();
const int packetSamples = (finalFrame) ? VOIP_MAX_FRAME_SAMPLES : VOIP_MAX_PACKET_SAMPLES;
// enough data buffered in audio hardware to process yet?
if (samples >= packetSamples) {
// audio capture is always MONO16.
static int16_t sampbuffer[VOIP_MAX_PACKET_SAMPLES];
float voipPower = 0.0f;
int voipFrames;
int i, bytes;
if (samples > VOIP_MAX_PACKET_SAMPLES)
samples = VOIP_MAX_PACKET_SAMPLES;
// !!! FIXME: maybe separate recording from encoding, so voipPower
// !!! FIXME: updates faster than 4Hz?
samples -= samples % VOIP_MAX_FRAME_SAMPLES;
if (samples != 120 && samples != 240 && samples != 480 && samples != 960 && samples != 1920 && samples != 2880 ) {
Com_Printf("Voip: bad number of samples %d\n", samples);
return;
}
voipFrames = samples / VOIP_MAX_FRAME_SAMPLES;
S_Capture(samples, (byte *) sampbuffer); // grab from audio card.
// check the "power" of this packet...
for (i = 0; i < samples; i++) {
const float flsamp = (float) sampbuffer[i];
const float s = fabs(flsamp);
voipPower += s * s;
sampbuffer[i] = (int16_t) ((flsamp) * audioMult);
}
// encode raw audio samples into Opus data...
bytes = opus_encode(clc.opusEncoder, sampbuffer, samples,
(unsigned char *) clc.voipOutgoingData,
sizeof (clc.voipOutgoingData));
if ( bytes <= 0 ) {
Com_DPrintf("VoIP: Error encoding %d samples\n", samples);
bytes = 0;
}
clc.voipPower = (voipPower / (32768.0f * 32768.0f *
((float) samples))) * 100.0f;
if ((useVad) && (clc.voipPower < cl_voipVADThreshold->value)) {
CL_VoipNewGeneration(); // no "talk" for at least 1/4 second.
} else {
clc.voipOutgoingDataSize = bytes;
clc.voipOutgoingDataFrames = voipFrames;
Com_DPrintf("VoIP: Send %d frames, %d bytes, %f power\n",
voipFrames, bytes, clc.voipPower);
#if 0
static FILE *encio = NULL;
if (encio == NULL) encio = fopen("voip-outgoing-encoded.bin", "wb");
if (encio != NULL) { fwrite(clc.voipOutgoingData, bytes, 1, encio); fflush(encio); }
static FILE *decio = NULL;
if (decio == NULL) decio = fopen("voip-outgoing-decoded.bin", "wb");
if (decio != NULL) { fwrite(sampbuffer, voipFrames * VOIP_MAX_FRAME_SAMPLES * 2, 1, decio); fflush(decio); }
#endif
}
}
}
// User requested we stop recording, and we've now processed the last of
// any previously-buffered data. Pause the capture device, etc.
if (finalFrame) {
S_StopCapture();
S_MasterGain(1.0f);
clc.voipPower = 0.0f; // force this value so it doesn't linger.
}
}
#endif
/*
=======================================================================
CLIENT RELIABLE COMMAND COMMUNICATION
=======================================================================
*/
/*
======================
CL_AddReliableCommand
The given command will be transmitted to the server, and is gauranteed to
not have future usercmd_t executed before it is executed
======================
*/
void CL_AddReliableCommand(const char *cmd, qboolean isDisconnectCmd)
{
int unacknowledged = clc.reliableSequence - clc.reliableAcknowledge;
// if we would be losing an old command that hasn't been acknowledged,
// we must drop the connection
// also leave one slot open for the disconnect command in this case.
if ((isDisconnectCmd && unacknowledged > MAX_RELIABLE_COMMANDS) ||
(!isDisconnectCmd && unacknowledged >= MAX_RELIABLE_COMMANDS))
{
if(com_errorEntered)
return;
else
Com_Error(ERR_DROP, "Client command overflow");
}
Q_strncpyz(clc.reliableCommands[++clc.reliableSequence & (MAX_RELIABLE_COMMANDS - 1)],
cmd, sizeof(*clc.reliableCommands));
}
/*
=======================================================================
CLIENT SIDE DEMO RECORDING
=======================================================================
*/
/*
====================
CL_WriteDemoMessage
Dumps the current net message, prefixed by the length
====================
*/
void CL_WriteDemoMessage ( msg_t *msg, int headerBytes ) {
int len, swlen;
// write the packet sequence
len = clc.serverMessageSequence;
swlen = LittleLong( len );
FS_Write (&swlen, 4, clc.demofile);
// skip the packet sequencing information
len = msg->cursize - headerBytes;
swlen = LittleLong(len);
FS_Write (&swlen, 4, clc.demofile);
FS_Write ( msg->data + headerBytes, len, clc.demofile );
}
/*
====================
CL_StopRecording_f
stop recording a demo
====================
*/
void CL_StopRecord_f( void ) {
int len;
if ( !clc.demorecording ) {
Com_Printf ("Not recording a demo.\n");
return;
}
// finish up
len = -1;
FS_Write (&len, 4, clc.demofile);
FS_Write (&len, 4, clc.demofile);
FS_FCloseFile (clc.demofile);
clc.demofile = 0;
clc.demorecording = qfalse;
clc.spDemoRecording = qfalse;
Com_Printf ("Stopped demo.\n");
}
/*
==================
CL_DemoFilename
==================
*/
void CL_DemoFilename( int number, char *fileName, int fileNameSize ) {
int a,b,c,d;
if(number < 0 || number > 9999)
number = 9999;
a = number / 1000;
number -= a*1000;
b = number / 100;
number -= b*100;
c = number / 10;
number -= c*10;
d = number;
Com_sprintf( fileName, fileNameSize, "demo%i%i%i%i"
, a, b, c, d );
}
/*
====================
CL_Record_f
record <demoname>
Begins recording a demo from the current position
====================
*/
static char demoName[MAX_QPATH]; // compiler bug workaround
void CL_Record_f( void ) {
char name[MAX_OSPATH];
byte bufData[MAX_MSGLEN];
msg_t buf;
int i;
int len;
entityState_t *ent;
entityState_t nullstate;
char *s;
if ( Cmd_Argc() > 2 ) {
Com_Printf ("record <demoname>\n");
return;
}
if ( clc.demorecording ) {
if (!clc.spDemoRecording) {
Com_Printf ("Already recording.\n");
}
return;
}
if ( clc.state != CA_ACTIVE ) {
Com_Printf ("You must be in a level to record.\n");
return;
}
// sync 0 doesn't prevent recording, so not forcing it off .. everyone does g_sync 1 ; record ; g_sync 0 ..
if ( NET_IsLocalAddress( clc.serverAddress ) && !Cvar_VariableValue( "g_synchronousClients" ) ) {
Com_Printf (S_COLOR_YELLOW "WARNING: You should set 'g_synchronousClients 1' for smoother demo recording\n");
}
if ( Cmd_Argc() == 2 ) {
s = Cmd_Argv(1);
Q_strncpyz( demoName, s, sizeof( demoName ) );
#ifdef LEGACY_PROTOCOL
if(clc.compat)
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_legacyprotocol->integer);
else
#endif
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_protocol->integer);
} else {
int number;
// scan for a free demo name
for ( number = 0 ; number <= 9999 ; number++ ) {
CL_DemoFilename( number, demoName, sizeof( demoName ) );
#ifdef LEGACY_PROTOCOL
if(clc.compat)
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_legacyprotocol->integer);
else
#endif
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_protocol->integer);
if (!FS_FileExists(name))
break; // file doesn't exist
}
}
// open the demo file
Com_Printf ("recording to %s.\n", name);
clc.demofile = FS_FOpenFileWrite( name );
if ( !clc.demofile ) {
Com_Printf ("ERROR: couldn't open.\n");
return;
}
clc.demorecording = qtrue;
if (Cvar_VariableValue("ui_recordSPDemo")) {
clc.spDemoRecording = qtrue;
} else {
clc.spDemoRecording = qfalse;
}
Q_strncpyz( clc.demoName, demoName, sizeof( clc.demoName ) );
// don't start saving messages until a non-delta compressed message is received
clc.demowaiting = qtrue;
// write out the gamestate message
MSG_Init (&buf, bufData, sizeof(bufData));
MSG_Bitstream(&buf);
// NOTE, MRE: all server->client messages now acknowledge
MSG_WriteLong( &buf, clc.reliableSequence );
MSG_WriteByte (&buf, svc_gamestate);
MSG_WriteLong (&buf, clc.serverCommandSequence );
// configstrings
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
if ( !cl.gameState.stringOffsets[i] ) {
continue;
}
s = cl.gameState.stringData + cl.gameState.stringOffsets[i];
MSG_WriteByte (&buf, svc_configstring);
MSG_WriteShort (&buf, i);
MSG_WriteBigString (&buf, s);
}
// baselines
Com_Memset (&nullstate, 0, sizeof(nullstate));
for ( i = 0; i < MAX_GENTITIES ; i++ ) {
ent = &cl.entityBaselines[i];
if ( !ent->number ) {
continue;
}
MSG_WriteByte (&buf, svc_baseline);
MSG_WriteDeltaEntity (&buf, &nullstate, ent, qtrue );
}
MSG_WriteByte( &buf, svc_EOF );
// finished writing the gamestate stuff
// write the client num
MSG_WriteLong(&buf, clc.clientNum);
// write the checksum feed
MSG_WriteLong(&buf, clc.checksumFeed);
// finished writing the client packet
MSG_WriteByte( &buf, svc_EOF );
// write it to the demo file
len = LittleLong( clc.serverMessageSequence - 1 );
FS_Write (&len, 4, clc.demofile);
len = LittleLong (buf.cursize);
FS_Write (&len, 4, clc.demofile);
FS_Write (buf.data, buf.cursize, clc.demofile);
// the rest of the demo file will be copied from net messages
}
/*
=======================================================================
CLIENT SIDE DEMO PLAYBACK
=======================================================================
*/
/*
=================
CL_DemoFrameDurationSDev
=================
*/
static float CL_DemoFrameDurationSDev( void )
{
int i;
int numFrames;
float mean = 0.0f;
float variance = 0.0f;
if( ( clc.timeDemoFrames - 1 ) > MAX_TIMEDEMO_DURATIONS )
numFrames = MAX_TIMEDEMO_DURATIONS;
else
numFrames = clc.timeDemoFrames - 1;
for( i = 0; i < numFrames; i++ )
mean += clc.timeDemoDurations[ i ];
mean /= numFrames;
for( i = 0; i < numFrames; i++ )
{
float x = clc.timeDemoDurations[ i ];
variance += ( ( x - mean ) * ( x - mean ) );
}
variance /= numFrames;
return sqrt( variance );
}
/*
=================
CL_DemoCompleted
=================
*/
void CL_DemoCompleted( void )
{
char buffer[ MAX_STRING_CHARS ];
if( cl_timedemo && cl_timedemo->integer )
{
int time;
time = Sys_Milliseconds() - clc.timeDemoStart;
if( time > 0 )
{
// Millisecond times are frame durations:
// minimum/average/maximum/std deviation
Com_sprintf( buffer, sizeof( buffer ),
"%i frames %3.1f seconds %3.1f fps %d.0/%.1f/%d.0/%.1f ms\n",
clc.timeDemoFrames,
time/1000.0,
clc.timeDemoFrames*1000.0 / time,
clc.timeDemoMinDuration,
time / (float)clc.timeDemoFrames,
clc.timeDemoMaxDuration,
CL_DemoFrameDurationSDev( ) );
Com_Printf( "%s", buffer );
// Write a log of all the frame durations
if( cl_timedemoLog && strlen( cl_timedemoLog->string ) > 0 )
{
int i;
int numFrames;
fileHandle_t f;
if( ( clc.timeDemoFrames - 1 ) > MAX_TIMEDEMO_DURATIONS )
numFrames = MAX_TIMEDEMO_DURATIONS;
else
numFrames = clc.timeDemoFrames - 1;
f = FS_FOpenFileWrite( cl_timedemoLog->string );
if( f )
{
FS_Printf( f, "# %s", buffer );
for( i = 0; i < numFrames; i++ )
FS_Printf( f, "%d\n", clc.timeDemoDurations[ i ] );
FS_FCloseFile( f );
Com_Printf( "%s written\n", cl_timedemoLog->string );
}
else
{
Com_Printf( "Couldn't open %s for writing\n",
cl_timedemoLog->string );
}
}
}
}
CL_Disconnect( qtrue );
CL_NextDemo();
}
/*
=================
CL_ReadDemoMessage
=================
*/
void CL_ReadDemoMessage( void ) {
int r;
msg_t buf;
byte bufData[ MAX_MSGLEN ];
int s;
if ( !clc.demofile ) {
CL_DemoCompleted ();
return;
}
// get the sequence number
r = FS_Read( &s, 4, clc.demofile);
if ( r != 4 ) {
CL_DemoCompleted ();
return;
}
clc.serverMessageSequence = LittleLong( s );
// init the message
MSG_Init( &buf, bufData, sizeof( bufData ) );
// get the length
r = FS_Read (&buf.cursize, 4, clc.demofile);
if ( r != 4 ) {
CL_DemoCompleted ();
return;
}
buf.cursize = LittleLong( buf.cursize );
if ( buf.cursize == -1 ) {
CL_DemoCompleted ();
return;
}
if ( buf.cursize > buf.maxsize ) {
Com_Error (ERR_DROP, "CL_ReadDemoMessage: demoMsglen > MAX_MSGLEN");
}
r = FS_Read( buf.data, buf.cursize, clc.demofile );
if ( r != buf.cursize ) {
Com_Printf( "Demo file was truncated.\n");
CL_DemoCompleted ();
return;
}
clc.lastPacketTime = cls.realtime;
buf.readcount = 0;
CL_ParseServerMessage( &buf );
}
/*
====================
CL_WalkDemoExt
====================
*/
static int CL_WalkDemoExt(char *arg, char *name, int *demofile)
{
int i = 0;
*demofile = 0;
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer > 0)
{
Com_sprintf(name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, com_legacyprotocol->integer);
FS_FOpenFileRead(name, demofile, qtrue);
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return com_legacyprotocol->integer;
}
}
if(com_protocol->integer != com_legacyprotocol->integer)
#endif
{
Com_sprintf(name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, com_protocol->integer);
FS_FOpenFileRead(name, demofile, qtrue);
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return com_protocol->integer;
}
}
Com_Printf("Not found: %s\n", name);
while(demo_protocols[i])
{
#ifdef LEGACY_PROTOCOL
if(demo_protocols[i] == com_legacyprotocol->integer)
continue;
#endif
if(demo_protocols[i] == com_protocol->integer)
continue;
Com_sprintf (name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, demo_protocols[i]);
FS_FOpenFileRead( name, demofile, qtrue );
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return demo_protocols[i];
}
else
Com_Printf("Not found: %s\n", name);
i++;
}
return -1;
}
/*
====================
CL_CompleteDemoName
====================
*/
static void CL_CompleteDemoName( char *args, int argNum )
{
if( argNum == 2 )
{
char demoExt[ 16 ];
Com_sprintf(demoExt, sizeof(demoExt), ".%s%d", DEMOEXT, com_protocol->integer);
Field_CompleteFilename( "demos", demoExt, qtrue, qtrue );
}
}
/*
====================
CL_PlayDemo_f
demo <demoname>
====================
*/
void CL_PlayDemo_f( void ) {
char name[MAX_OSPATH];
char *arg, *ext_test;
int protocol, i;
char retry[MAX_OSPATH];
if (Cmd_Argc() != 2) {
Com_Printf ("demo <demoname>\n");
return;
}
// make sure a local server is killed
// 2 means don't force disconnect of local client
Cvar_Set( "sv_killserver", "2" );
// open the demo file
arg = Cmd_Argv(1);
CL_Disconnect( qtrue );
// check for an extension .DEMOEXT_?? (?? is protocol)
ext_test = strrchr(arg, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMOEXT, ARRAY_LEN(DEMOEXT) - 1))
{
protocol = atoi(ext_test + ARRAY_LEN(DEMOEXT));
for(i = 0; demo_protocols[i]; i++)
{
if(demo_protocols[i] == protocol)
break;
}
if(demo_protocols[i] || protocol == com_protocol->integer
#ifdef LEGACY_PROTOCOL
|| protocol == com_legacyprotocol->integer
#endif
)
{
Com_sprintf(name, sizeof(name), "demos/%s", arg);
FS_FOpenFileRead(name, &clc.demofile, qtrue);
}
else
{
int len;
Com_Printf("Protocol %d not supported for demos\n", protocol);
len = ext_test - arg;
if(len >= ARRAY_LEN(retry))
len = ARRAY_LEN(retry) - 1;
Q_strncpyz(retry, arg, len + 1);
retry[len] = '\0';
protocol = CL_WalkDemoExt(retry, name, &clc.demofile);
}
}
else
protocol = CL_WalkDemoExt(arg, name, &clc.demofile);
if (!clc.demofile) {
Com_Error( ERR_DROP, "couldn't open %s", name);
return;
}
Q_strncpyz( clc.demoName, arg, sizeof( clc.demoName ) );
Con_Close();
clc.state = CA_CONNECTED;
clc.demoplaying = qtrue;
Q_strncpyz( clc.servername, arg, sizeof( clc.servername ) );
#ifdef LEGACY_PROTOCOL
if(protocol <= com_legacyprotocol->integer)
clc.compat = qtrue;
else
clc.compat = qfalse;
#endif
// read demo messages until connected
while ( clc.state >= CA_CONNECTED && clc.state < CA_PRIMED ) {
CL_ReadDemoMessage();
}
// don't get the first snapshot this frame, to prevent the long
// time from the gamestate load from messing causing a time skip
clc.firstDemoFrameSkipped = qfalse;
}
/*
====================
CL_StartDemoLoop
Closing the main menu will restart the demo loop
====================
*/
void CL_StartDemoLoop( void ) {
// start the demo loop again
Cbuf_AddText ("d1\n");
Key_SetCatcher( 0 );
}
/*
==================
CL_NextDemo
Called when a demo or cinematic finishes
If the "nextdemo" cvar is set, that command will be issued
==================
*/
void CL_NextDemo( void ) {
char v[MAX_STRING_CHARS];
Q_strncpyz( v, Cvar_VariableString ("nextdemo"), sizeof(v) );
v[MAX_STRING_CHARS-1] = 0;
Com_DPrintf("CL_NextDemo: %s\n", v );
if (!v[0]) {
return;
}
Cvar_Set ("nextdemo","");
Cbuf_AddText (v);
Cbuf_AddText ("\n");
Cbuf_Execute();
}
//======================================================================
/*
=====================
CL_ShutdownAll
=====================
*/
void CL_ShutdownAll(qboolean shutdownRef)
{
if(CL_VideoRecording())
CL_CloseAVI();
if(clc.demorecording)
CL_StopRecord_f();
#ifdef USE_CURL
CL_cURL_Shutdown();
#endif
// clear sounds
S_DisableSounds();
// shutdown CGame
CL_ShutdownCGame();
// shutdown UI
CL_ShutdownUI();
// shutdown the renderer
if(shutdownRef)
CL_ShutdownRef();
else if(re.Shutdown)
re.Shutdown(qfalse); // don't destroy window or context
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.rendererStarted = qfalse;
cls.soundRegistered = qfalse;
}
/*
=================
CL_ClearMemory
Called by Com_GameRestart
=================
*/
void CL_ClearMemory(qboolean shutdownRef)
{
// shutdown all the client stuff
CL_ShutdownAll(shutdownRef);
// if not running a server clear the whole hunk
if ( !com_sv_running->integer ) {
// clear the whole hunk
Hunk_Clear();
// clear collision map data
CM_ClearMap();
}
else {
// clear all the client data on the hunk
Hunk_ClearToMark();
}
}
/*
=================
CL_FlushMemory
Called by CL_MapLoading, CL_Connect_f, CL_PlayDemo_f, and CL_ParseGamestate the only
ways a client gets into a game
Also called by Com_Error
=================
*/
void CL_FlushMemory(void)
{
CL_ClearMemory(qfalse);
CL_StartHunkUsers(qfalse);
}
/*
=====================
CL_MapLoading
A local server is starting to load a map, so update the
screen to let the user know about it, then dump all client
memory on the hunk from cgame, ui, and renderer
=====================
*/
void CL_MapLoading( void ) {
if ( com_dedicated->integer ) {
clc.state = CA_DISCONNECTED;
Key_SetCatcher( KEYCATCH_CONSOLE );
return;
}
if ( !com_cl_running->integer ) {
return;
}
Con_Close();
Key_SetCatcher( 0 );
// if we are already connected to the local host, stay connected
if ( clc.state >= CA_CONNECTED && !Q_stricmp( clc.servername, "localhost" ) ) {
clc.state = CA_CONNECTED; // so the connect screen is drawn
Com_Memset( cls.updateInfoString, 0, sizeof( cls.updateInfoString ) );
Com_Memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) );
Com_Memset( &cl.gameState, 0, sizeof( cl.gameState ) );
clc.lastPacketSentTime = -9999;
SCR_UpdateScreen();
} else {
// clear nextmap so the cinematic shutdown doesn't execute it
Cvar_Set( "nextmap", "" );
CL_Disconnect( qtrue );
Q_strncpyz( clc.servername, "localhost", sizeof(clc.servername) );
clc.state = CA_CHALLENGING; // so the connect screen is drawn
Key_SetCatcher( 0 );
SCR_UpdateScreen();
clc.connectTime = -RETRANSMIT_TIMEOUT;
NET_StringToAdr( clc.servername, &clc.serverAddress, NA_UNSPEC);
// we don't need a challenge on the localhost
CL_CheckForResend();
}
}
/*
=====================
CL_ClearState
Called before parsing a gamestate
=====================
*/
void CL_ClearState (void) {
// S_StopAllSounds();
Com_Memset( &cl, 0, sizeof( cl ) );
}
/*
====================
CL_UpdateGUID
update cl_guid using QKEY_FILE and optional prefix
====================
*/
static void CL_UpdateGUID( const char *prefix, int prefix_len )
{
fileHandle_t f;
int len;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
if( len != QKEY_SIZE )
Cvar_Set( "cl_guid", "" );
else
Cvar_Set( "cl_guid", Com_MD5File( QKEY_FILE, QKEY_SIZE,
prefix, prefix_len ) );
}
static void CL_OldGame(void)
{
if(cl_oldGameSet)
{
// change back to previous fs_game
cl_oldGameSet = qfalse;
Cvar_Set2("fs_game", cl_oldGame, qtrue);
FS_ConditionalRestart(clc.checksumFeed, qfalse);
}
}
/*
=====================
CL_Disconnect
Called when a connection, demo, or cinematic is being terminated.
Goes from a connected state to either a menu state or a console state
Sends a disconnect message to the server
This is also called on Com_Error and Com_Quit, so it shouldn't cause any errors
=====================
*/
void CL_Disconnect( qboolean showMainMenu ) {
if ( !com_cl_running || !com_cl_running->integer ) {
return;
}
// shutting down the client so enter full screen ui mode
Cvar_Set("r_uiFullScreen", "1");
if ( clc.demorecording ) {
CL_StopRecord_f ();
}
if (clc.download) {
FS_FCloseFile( clc.download );
clc.download = 0;
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
#ifdef USE_MUMBLE
if (cl_useMumble->integer && mumble_islinked()) {
Com_Printf("Mumble: Unlinking from Mumble application\n");
mumble_unlink();
}
#endif
#ifdef USE_VOIP
if (cl_voipSend->integer) {
int tmp = cl_voipUseVAD->integer;
cl_voipUseVAD->integer = 0; // disable this for a moment.
clc.voipOutgoingDataSize = 0; // dump any pending VoIP transmission.
Cvar_Set("cl_voipSend", "0");
CL_CaptureVoip(); // clean up any state...
cl_voipUseVAD->integer = tmp;
}
if (clc.voipCodecInitialized) {
int i;
opus_encoder_destroy(clc.opusEncoder);
for (i = 0; i < MAX_CLIENTS; i++) {
opus_decoder_destroy(clc.opusDecoder[i]);
}
clc.voipCodecInitialized = qfalse;
}
Cmd_RemoveCommand ("voip");
#endif
if ( clc.demofile ) {
FS_FCloseFile( clc.demofile );
clc.demofile = 0;
}
if ( uivm && showMainMenu ) {
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NONE );
}
SCR_StopCinematic ();
S_ClearSoundBuffer();
// send a disconnect message to the server
// send it a few times in case one is dropped
if ( clc.state >= CA_CONNECTED ) {
CL_AddReliableCommand("disconnect", qtrue);
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
// Remove pure paks
FS_PureServerSetLoadedPaks("", "");
FS_PureServerSetReferencedPaks( "", "" );
CL_ClearState ();
// wipe the client connection
Com_Memset( &clc, 0, sizeof( clc ) );
clc.state = CA_DISCONNECTED;
// allow cheats locally
Cvar_Set( "sv_cheats", "1" );
// not connected to a pure server anymore
cl_connectedToPureServer = qfalse;
#ifdef USE_VOIP
// not connected to voip server anymore.
clc.voipEnabled = qfalse;
#endif
// Stop recording any video
if( CL_VideoRecording( ) ) {
// Finish rendering current frame
SCR_UpdateScreen( );
CL_CloseAVI( );
}
CL_UpdateGUID( NULL, 0 );
if(!noGameRestart)
CL_OldGame();
else
noGameRestart = qfalse;
}
/*
===================
CL_ForwardCommandToServer
adds the current command line as a clientCommand
things like godmode, noclip, etc, are commands directed to the server,
so when they are typed in at the console, they will need to be forwarded.
===================
*/
void CL_ForwardCommandToServer( const char *string ) {
char *cmd;
cmd = Cmd_Argv(0);
// ignore key up commands
if ( cmd[0] == '-' ) {
return;
}
if ( clc.demoplaying || clc.state < CA_CONNECTED || cmd[0] == '+' ) {
Com_Printf ("Unknown command \"%s" S_COLOR_WHITE "\"\n", cmd);
return;
}
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand(string, qfalse);
} else {
CL_AddReliableCommand(cmd, qfalse);
}
}
/*
===================
CL_RequestMotd
===================
*/
void CL_RequestMotd( void ) {
#ifdef UPDATE_SERVER_NAME
char info[MAX_INFO_STRING];
if ( !cl_motd->integer ) {
return;
}
Com_Printf( "Resolving %s\n", UPDATE_SERVER_NAME );
if ( !NET_StringToAdr( UPDATE_SERVER_NAME, &cls.updateServer, NA_IP ) ) {
Com_Printf( "Couldn't resolve address\n" );
return;
}
cls.updateServer.port = BigShort( PORT_UPDATE );
Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", UPDATE_SERVER_NAME,
cls.updateServer.ip[0], cls.updateServer.ip[1],
cls.updateServer.ip[2], cls.updateServer.ip[3],
BigShort( cls.updateServer.port ) );
info[0] = 0;
Com_sprintf( cls.updateChallenge, sizeof( cls.updateChallenge ), "%i", ((rand() << 16) ^ rand()) ^ Com_Milliseconds());
Info_SetValueForKey( info, "challenge", cls.updateChallenge );
Info_SetValueForKey( info, "renderer", cls.glconfig.renderer_string );
Info_SetValueForKey( info, "version", com_version->string );
NET_OutOfBandPrint( NS_CLIENT, cls.updateServer, "getmotd \"%s\"\n", info );
#endif
}
/*
===================
CL_RequestAuthorization
Authorization server protocol
-----------------------------
All commands are text in Q3 out of band packets (leading 0xff 0xff 0xff 0xff).
Whenever the client tries to get a challenge from the server it wants to
connect to, it also blindly fires off a packet to the authorize server:
getKeyAuthorize <challenge> <cdkey>
cdkey may be "demo"
#OLD The authorize server returns a:
#OLD
#OLD keyAthorize <challenge> <accept | deny>
#OLD
#OLD A client will be accepted if the cdkey is valid and it has not been used by any other IP
#OLD address in the last 15 minutes.
The server sends a:
getIpAuthorize <challenge> <ip>
The authorize server returns a:
ipAuthorize <challenge> <accept | deny | demo | unknown >
A client will be accepted if a valid cdkey was sent by that ip (only) in the last 15 minutes.
If no response is received from the authorize server after two tries, the client will be let
in anyway.
===================
*/
#ifndef STANDALONE
void CL_RequestAuthorization( void ) {
char nums[64];
int i, j, l;
cvar_t *fs;
if ( !cls.authorizeServer.port ) {
Com_Printf( "Resolving %s\n", AUTHORIZE_SERVER_NAME );
if ( !NET_StringToAdr( AUTHORIZE_SERVER_NAME, &cls.authorizeServer, NA_IP ) ) {
Com_Printf( "Couldn't resolve address\n" );
return;
}
cls.authorizeServer.port = BigShort( PORT_AUTHORIZE );
Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", AUTHORIZE_SERVER_NAME,
cls.authorizeServer.ip[0], cls.authorizeServer.ip[1],
cls.authorizeServer.ip[2], cls.authorizeServer.ip[3],
BigShort( cls.authorizeServer.port ) );
}
if ( cls.authorizeServer.type == NA_BAD ) {
return;
}
// only grab the alphanumeric values from the cdkey, to avoid any dashes or spaces
j = 0;
l = strlen( cl_cdkey );
if ( l > 32 ) {
l = 32;
}
for ( i = 0 ; i < l ; i++ ) {
if ( ( cl_cdkey[i] >= '0' && cl_cdkey[i] <= '9' )
|| ( cl_cdkey[i] >= 'a' && cl_cdkey[i] <= 'z' )
|| ( cl_cdkey[i] >= 'A' && cl_cdkey[i] <= 'Z' )
) {
nums[j] = cl_cdkey[i];
j++;
}
}
nums[j] = 0;
fs = Cvar_Get ("cl_anonymous", "0", CVAR_INIT|CVAR_SYSTEMINFO );
NET_OutOfBandPrint(NS_CLIENT, cls.authorizeServer, "getKeyAuthorize %i %s", fs->integer, nums );
}
#endif
/*
======================================================================
CONSOLE COMMANDS
======================================================================
*/
/*
==================
CL_ForwardToServer_f
==================
*/
void CL_ForwardToServer_f( void ) {
if ( clc.state != CA_ACTIVE || clc.demoplaying ) {
Com_Printf ("Not connected to a server.\n");
return;
}
// don't forward the first argument
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand(Cmd_Args(), qfalse);
}
}
/*
==================
CL_Disconnect_f
==================
*/
void CL_Disconnect_f( void ) {
SCR_StopCinematic();
Cvar_Set("ui_singlePlayerActive", "0");
if ( clc.state != CA_DISCONNECTED && clc.state != CA_CINEMATIC ) {
Com_Error (ERR_DISCONNECT, "Disconnected from server");
}
}
/*
================
CL_Reconnect_f
================
*/
void CL_Reconnect_f( void ) {
if ( !strlen( cl_reconnectArgs ) )
return;
Cvar_Set("ui_singlePlayerActive", "0");
Cbuf_AddText( va("connect %s\n", cl_reconnectArgs ) );
}
/*
================
CL_Connect_f
================
*/
void CL_Connect_f( void ) {
char *server;
const char *serverString;
int argc = Cmd_Argc();
netadrtype_t family = NA_UNSPEC;
if ( argc != 2 && argc != 3 ) {
Com_Printf( "usage: connect [-4|-6] server\n");
return;
}
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
// save arguments for reconnect
Q_strncpyz( cl_reconnectArgs, Cmd_Args(), sizeof( cl_reconnectArgs ) );
Cvar_Set("ui_singlePlayerActive", "0");
// fire a message off to the motd server
CL_RequestMotd();
// clear any previous "server full" type messages
clc.serverMessage[0] = 0;
if ( com_sv_running->integer && !strcmp( server, "localhost" ) ) {
// if running a local server, kill it
SV_Shutdown( "Server quit" );
}
// make sure a local server is killed
Cvar_Set( "sv_killserver", "1" );
SV_Frame( 0 );
noGameRestart = qtrue;
CL_Disconnect( qtrue );
Con_Close();
Q_strncpyz( clc.servername, server, sizeof(clc.servername) );
if (!NET_StringToAdr(clc.servername, &clc.serverAddress, family) ) {
Com_Printf ("Bad server address\n");
clc.state = CA_DISCONNECTED;
return;
}
if (clc.serverAddress.port == 0) {
clc.serverAddress.port = BigShort( PORT_SERVER );
}
serverString = NET_AdrToStringwPort(clc.serverAddress);
Com_Printf( "%s resolved to %s\n", clc.servername, serverString);
if( cl_guidServerUniq->integer )
CL_UpdateGUID( serverString, strlen( serverString ) );
else
CL_UpdateGUID( NULL, 0 );
// if we aren't playing on a lan, we need to authenticate
// with the cd key
if(NET_IsLocalAddress(clc.serverAddress))
clc.state = CA_CHALLENGING;
else
{
clc.state = CA_CONNECTING;
// Set a client challenge number that ideally is mirrored back by the server.
clc.challenge = ((rand() << 16) ^ rand()) ^ Com_Milliseconds();
}
Key_SetCatcher( 0 );
clc.connectTime = -99999; // CL_CheckForResend() will fire immediately
clc.connectPacketCount = 0;
// server connection string
Cvar_Set( "cl_currentServerAddress", server );
}
#define MAX_RCON_MESSAGE 1024
/*
==================
CL_CompleteRcon
==================
*/
static void CL_CompleteRcon( char *args, int argNum )
{
if( argNum == 2 )
{
// Skip "rcon "
char *p = Com_SkipTokens( args, 1, " " );
if( p > args )
Field_CompleteCommand( p, qtrue, qtrue );
}
}
/*
==================
CL_CompletePlayerName
==================
*/
static void CL_CompletePlayerName( char *args, int argNum )
{
if( argNum == 2 )
{
char names[MAX_CLIENTS][MAX_NAME_LENGTH];
const char *namesPtr[MAX_CLIENTS];
int i;
int clientCount;
int nameCount;
const char *info;
const char *name;
//configstring
info = cl.gameState.stringData + cl.gameState.stringOffsets[CS_SERVERINFO];
clientCount = atoi( Info_ValueForKey( info, "sv_maxclients" ) );
nameCount = 0;
for( i = 0; i < clientCount; i++ ) {
if( i == clc.clientNum )
continue;
info = cl.gameState.stringData + cl.gameState.stringOffsets[CS_PLAYERS+i];
name = Info_ValueForKey( info, "n" );
if( name[0] == '\0' )
continue;
Q_strncpyz( names[nameCount], name, sizeof(names[nameCount]) );
Q_CleanStr( names[nameCount] );
namesPtr[nameCount] = names[nameCount];
nameCount++;
}
qsort( (void*)namesPtr, nameCount, sizeof( namesPtr[0] ), Com_strCompare );
Field_CompletePlayerName( namesPtr, nameCount );
}
}
/*
=====================
CL_Rcon_f
Send the rest of the command line over as
an unconnected command.
=====================
*/
void CL_Rcon_f( void ) {
char message[MAX_RCON_MESSAGE];
netadr_t to;
if ( !rcon_client_password->string[0] ) {
Com_Printf ("You must set 'rconpassword' before\n"
"issuing an rcon command.\n");
return;
}
message[0] = -1;
message[1] = -1;
message[2] = -1;
message[3] = -1;
message[4] = 0;
Q_strcat (message, MAX_RCON_MESSAGE, "rcon ");
Q_strcat (message, MAX_RCON_MESSAGE, rcon_client_password->string);
Q_strcat (message, MAX_RCON_MESSAGE, " ");
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543
Q_strcat (message, MAX_RCON_MESSAGE, Cmd_Cmd()+5);
if ( clc.state >= CA_CONNECTED ) {
to = clc.netchan.remoteAddress;
} else {
if (!strlen(rconAddress->string)) {
Com_Printf ("You must either be connected,\n"
"or set the 'rconAddress' cvar\n"
"to issue rcon commands\n");
return;
}
NET_StringToAdr (rconAddress->string, &to, NA_UNSPEC);
if (to.port == 0) {
to.port = BigShort (PORT_SERVER);
}
}
NET_SendPacket (NS_CLIENT, strlen(message)+1, message, to);
}
/*
=================
CL_SendPureChecksums
=================
*/
void CL_SendPureChecksums( void ) {
char cMsg[MAX_INFO_VALUE];
// if we are pure we need to send back a command with our referenced pk3 checksums
Com_sprintf(cMsg, sizeof(cMsg), "cp %d %s", cl.serverId, FS_ReferencedPakPureChecksums());
CL_AddReliableCommand(cMsg, qfalse);
}
/*
=================
CL_ResetPureClientAtServer
=================
*/
void CL_ResetPureClientAtServer( void ) {
CL_AddReliableCommand("vdr", qfalse);
}
/*
=================
CL_Vid_Restart_f
Restart the video subsystem
we also have to reload the UI and CGame because the renderer
doesn't know what graphics to reload
=================
*/
void CL_Vid_Restart_f( void ) {
// Settings may have changed so stop recording now
if( CL_VideoRecording( ) ) {
CL_CloseAVI( );
}
if(clc.demorecording)
CL_StopRecord_f();
// don't let them loop during the restart
S_StopAllSounds();
if(!FS_ConditionalRestart(clc.checksumFeed, qtrue))
{
// if not running a server clear the whole hunk
if(com_sv_running->integer)
{
// clear all the client data on the hunk
Hunk_ClearToMark();
}
else
{
// clear the whole hunk
Hunk_Clear();
}
// shutdown the UI
CL_ShutdownUI();
// shutdown the CGame
CL_ShutdownCGame();
// shutdown the renderer and clear the renderer interface
CL_ShutdownRef();
// client is no longer pure untill new checksums are sent
CL_ResetPureClientAtServer();
// clear pak references
FS_ClearPakReferences( FS_UI_REF | FS_CGAME_REF );
// reinitialize the filesystem if the game directory or checksum has changed
cls.rendererStarted = qfalse;
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.soundRegistered = qfalse;
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set("cl_paused", "0");
// initialize the renderer interface
CL_InitRef();
// startup all the client stuff
CL_StartHunkUsers(qfalse);
// start the cgame if connected
if(clc.state > CA_CONNECTED && clc.state != CA_CINEMATIC)
{
cls.cgameStarted = qtrue;
CL_InitCGame();
// send pure checksums
CL_SendPureChecksums();
}
}
}
/*
=================
CL_Snd_Restart
Restart the sound subsystem
=================
*/
void CL_Snd_Shutdown(void)
{
S_Shutdown();
cls.soundStarted = qfalse;
}
/*
=================
CL_Snd_Restart_f
Restart the sound subsystem
The cgame and game must also be forced to restart because
handles will be invalid
=================
*/
void CL_Snd_Restart_f(void)
{
CL_Snd_Shutdown();
// sound will be reinitialized by vid_restart
CL_Vid_Restart_f();
}
/*
==================
CL_PK3List_f
==================
*/
void CL_OpenedPK3List_f( void ) {
Com_Printf("Opened PK3 Names: %s\n", FS_LoadedPakNames());
}
/*
==================
CL_PureList_f
==================
*/
void CL_ReferencedPK3List_f( void ) {
Com_Printf("Referenced PK3 Names: %s\n", FS_ReferencedPakNames());
}
/*
==================
CL_Configstrings_f
==================
*/
void CL_Configstrings_f( void ) {
int i;
int ofs;
if ( clc.state != CA_ACTIVE ) {
Com_Printf( "Not connected to a server.\n");
return;
}
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
ofs = cl.gameState.stringOffsets[ i ];
if ( !ofs ) {
continue;
}
Com_Printf( "%4i: %s\n", i, cl.gameState.stringData + ofs );
}
}
/*
==============
CL_Clientinfo_f
==============
*/
void CL_Clientinfo_f( void ) {
Com_Printf( "--------- Client Information ---------\n" );
Com_Printf( "state: %i\n", clc.state );
Com_Printf( "Server: %s\n", clc.servername );
Com_Printf ("User info settings:\n");
Info_Print( Cvar_InfoString( CVAR_USERINFO ) );
Com_Printf( "--------------------------------------\n" );
}
//====================================================================
/*
=================
CL_DownloadsComplete
Called when all downloading has been completed
=================
*/
void CL_DownloadsComplete( void ) {
#ifdef USE_CURL
// if we downloaded with cURL
if(clc.cURLUsed) {
clc.cURLUsed = qfalse;
CL_cURL_Shutdown();
if( clc.cURLDisconnected ) {
if(clc.downloadRestart) {
FS_Restart(clc.checksumFeed);
clc.downloadRestart = qfalse;
}
clc.cURLDisconnected = qfalse;
CL_Reconnect_f();
return;
}
}
#endif
// if we downloaded files we need to restart the file system
if (clc.downloadRestart) {
clc.downloadRestart = qfalse;
FS_Restart(clc.checksumFeed); // We possibly downloaded a pak, restart the file system to load it
// inform the server so we get new gamestate info
CL_AddReliableCommand("donedl", qfalse);
// by sending the donedl command we request a new gamestate
// so we don't want to load stuff yet
return;
}
// let the client game init and load data
clc.state = CA_LOADING;
// Pump the loop, this may change gamestate!
Com_EventLoop();
// if the gamestate was changed by calling Com_EventLoop
// then we loaded everything already and we don't want to do it again.
if ( clc.state != CA_LOADING ) {
return;
}
// starting to load a map so we get out of full screen ui mode
Cvar_Set("r_uiFullScreen", "0");
// flush client memory and start loading stuff
// this will also (re)load the UI
// if this is a local client then only the client part of the hunk
// will be cleared, note that this is done after the hunk mark has been set
CL_FlushMemory();
// initialize the CGame
cls.cgameStarted = qtrue;
CL_InitCGame();
// set pure checksums
CL_SendPureChecksums();
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
/*
=================
CL_BeginDownload
Requests a file to download from the server. Stores it in the current
game directory.
=================
*/
void CL_BeginDownload( const char *localName, const char *remoteName ) {
Com_DPrintf("***** CL_BeginDownload *****\n"
"Localname: %s\n"
"Remotename: %s\n"
"****************************\n", localName, remoteName);
Q_strncpyz ( clc.downloadName, localName, sizeof(clc.downloadName) );
Com_sprintf( clc.downloadTempName, sizeof(clc.downloadTempName), "%s.tmp", localName );
// Set so UI gets access to it
Cvar_Set( "cl_downloadName", remoteName );
Cvar_Set( "cl_downloadSize", "0" );
Cvar_Set( "cl_downloadCount", "0" );
Cvar_SetValue( "cl_downloadTime", cls.realtime );
clc.downloadBlock = 0; // Starting new file
clc.downloadCount = 0;
CL_AddReliableCommand(va("download %s", remoteName), qfalse);
}
/*
=================
CL_NextDownload
A download completed or failed
=================
*/
void CL_NextDownload(void)
{
char *s;
char *remoteName, *localName;
qboolean useCURL = qfalse;
// A download has finished, check whether this matches a referenced checksum
if(*clc.downloadName)
{
char *zippath = FS_BuildOSPath(Cvar_VariableString("fs_homepath"), clc.downloadName, "");
zippath[strlen(zippath)-1] = '\0';
if(!FS_CompareZipChecksum(zippath))
Com_Error(ERR_DROP, "Incorrect checksum for file: %s", clc.downloadName);
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set("cl_downloadName", "");
// We are looking to start a download here
if (*clc.downloadList) {
s = clc.downloadList;
// format is:
// @remotename@localname@remotename@localname, etc.
if (*s == '@')
s++;
remoteName = s;
if ( (s = strchr(s, '@')) == NULL ) {
CL_DownloadsComplete();
return;
}
*s++ = 0;
localName = s;
if ( (s = strchr(s, '@')) != NULL )
*s++ = 0;
else
s = localName + strlen(localName); // point at the nul byte
#ifdef USE_CURL
if(!(cl_allowDownload->integer & DLF_NO_REDIRECT)) {
if(clc.sv_allowDownload & DLF_NO_REDIRECT) {
Com_Printf("WARNING: server does not "
"allow download redirection "
"(sv_allowDownload is %d)\n",
clc.sv_allowDownload);
}
else if(!*clc.sv_dlURL) {
Com_Printf("WARNING: server allows "
"download redirection, but does not "
"have sv_dlURL set\n");
}
else if(!CL_cURL_Init()) {
Com_Printf("WARNING: could not load "
"cURL library\n");
}
else {
CL_cURL_BeginDownload(localName, va("%s/%s",
clc.sv_dlURL, remoteName));
useCURL = qtrue;
}
}
else if(!(clc.sv_allowDownload & DLF_NO_REDIRECT)) {
Com_Printf("WARNING: server allows download "
"redirection, but it disabled by client "
"configuration (cl_allowDownload is %d)\n",
cl_allowDownload->integer);
}
#endif /* USE_CURL */
if(!useCURL) {
if((cl_allowDownload->integer & DLF_NO_UDP)) {
Com_Error(ERR_DROP, "UDP Downloads are "
"disabled on your client. "
"(cl_allowDownload is %d)",
cl_allowDownload->integer);
return;
}
else {
CL_BeginDownload( localName, remoteName );
}
}
clc.downloadRestart = qtrue;
// move over the rest
memmove( clc.downloadList, s, strlen(s) + 1);
return;
}
CL_DownloadsComplete();
}
/*
=================
CL_InitDownloads
After receiving a valid game state, we valid the cgame and local zip files here
and determine if we need to download them
=================
*/
void CL_InitDownloads(void) {
char missingfiles[1024];
if ( !(cl_allowDownload->integer & DLF_ENABLE) )
{
// autodownload is disabled on the client
// but it's possible that some referenced files on the server are missing
if (FS_ComparePaks( missingfiles, sizeof( missingfiles ), qfalse ) )
{
// NOTE TTimo I would rather have that printed as a modal message box
// but at this point while joining the game we don't know wether we will successfully join or not
Com_Printf( "\nWARNING: You are missing some files referenced by the server:\n%s"
"You might not be able to join the game\n"
"Go to the setting menu to turn on autodownload, or get the file elsewhere\n\n", missingfiles );
}
}
else if ( FS_ComparePaks( clc.downloadList, sizeof( clc.downloadList ) , qtrue ) ) {
Com_Printf("Need paks: %s\n", clc.downloadList );
if ( *clc.downloadList ) {
// if autodownloading is not enabled on the server
clc.state = CA_CONNECTED;
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
CL_NextDownload();
return;
}
}
CL_DownloadsComplete();
}
/*
=================
CL_CheckForResend
Resend a connect message if the last one has timed out
=================
*/
void CL_CheckForResend( void ) {
int port;
char info[MAX_INFO_STRING];
char data[MAX_INFO_STRING + 10];
// don't send anything if playing back a demo
if ( clc.demoplaying ) {
return;
}
// resend if we haven't gotten a reply yet
if ( clc.state != CA_CONNECTING && clc.state != CA_CHALLENGING ) {
return;
}
if ( cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT ) {
return;
}
clc.connectTime = cls.realtime; // for retransmit requests
clc.connectPacketCount++;
switch ( clc.state ) {
case CA_CONNECTING:
// requesting a challenge .. IPv6 users always get in as authorize server supports no ipv6.
#ifndef STANDALONE
if (!com_standalone->integer && clc.serverAddress.type == NA_IP && !Sys_IsLANAddress( clc.serverAddress ) )
CL_RequestAuthorization();
#endif
// The challenge request shall be followed by a client challenge so no malicious server can hijack this connection.
// Add the gamename so the server knows we're running the correct game or can reject the client
// with a meaningful message
Com_sprintf(data, sizeof(data), "getchallenge %d %s", clc.challenge, com_gamename->string);
NET_OutOfBandPrint(NS_CLIENT, clc.serverAddress, "%s", data);
break;
case CA_CHALLENGING:
// sending back the challenge
port = Cvar_VariableValue ("net_qport");
Q_strncpyz( info, Cvar_InfoString( CVAR_USERINFO ), sizeof( info ) );
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer == com_protocol->integer)
clc.compat = qtrue;
if(clc.compat)
Info_SetValueForKey(info, "protocol", va("%i", com_legacyprotocol->integer));
else
#endif
Info_SetValueForKey(info, "protocol", va("%i", com_protocol->integer));
Info_SetValueForKey( info, "qport", va("%i", port ) );
Info_SetValueForKey( info, "challenge", va("%i", clc.challenge ) );
Com_sprintf( data, sizeof(data), "connect \"%s\"", info );
NET_OutOfBandData( NS_CLIENT, clc.serverAddress, (byte *) data, strlen ( data ) );
// the most current userinfo has been sent, so watch for any
// newer changes to userinfo variables
cvar_modifiedFlags &= ~CVAR_USERINFO;
break;
default:
Com_Error( ERR_FATAL, "CL_CheckForResend: bad clc.state" );
}
}
/*
===================
CL_MotdPacket
===================
*/
void CL_MotdPacket( netadr_t from ) {
#ifdef UPDATE_SERVER_NAME
char *challenge;
char *info;
// if not from our server, ignore it
if ( !NET_CompareAdr( from, cls.updateServer ) ) {
return;
}
info = Cmd_Argv(1);
// check challenge
challenge = Info_ValueForKey( info, "challenge" );
if ( strcmp( challenge, cls.updateChallenge ) ) {
return;
}
challenge = Info_ValueForKey( info, "motd" );
Q_strncpyz( cls.updateInfoString, info, sizeof( cls.updateInfoString ) );
Cvar_Set( "cl_motdString", challenge );
#endif
}
/*
===================
CL_InitServerInfo
===================
*/
void CL_InitServerInfo( serverInfo_t *server, netadr_t *address ) {
server->adr = *address;
server->clients = 0;
server->hostName[0] = '\0';
server->mapName[0] = '\0';
server->maxClients = 0;
server->maxPing = 0;
server->minPing = 0;
server->ping = -1;
server->game[0] = '\0';
server->gameType = 0;
server->netType = 0;
server->punkbuster = 0;
server->g_humanplayers = 0;
server->g_needpass = 0;
}
#define MAX_SERVERSPERPACKET 256
/*
===================
CL_ServersResponsePacket
===================
*/
void CL_ServersResponsePacket( const netadr_t* from, msg_t *msg, qboolean extended ) {
int i, j, count, total;
netadr_t addresses[MAX_SERVERSPERPACKET];
int numservers;
byte* buffptr;
byte* buffend;
Com_Printf("CL_ServersResponsePacket\n");
if (cls.numglobalservers == -1) {
// state to detect lack of servers or lack of response
cls.numglobalservers = 0;
cls.numGlobalServerAddresses = 0;
}
// parse through server response string
numservers = 0;
buffptr = msg->data;
buffend = buffptr + msg->cursize;
// advance to initial token
do
{
if(*buffptr == '\\' || (extended && *buffptr == '/'))
break;
buffptr++;
} while (buffptr < buffend);
while (buffptr + 1 < buffend)
{
// IPv4 address
if (*buffptr == '\\')
{
buffptr++;
if (buffend - buffptr < sizeof(addresses[numservers].ip) + sizeof(addresses[numservers].port) + 1)
break;
for(i = 0; i < sizeof(addresses[numservers].ip); i++)
addresses[numservers].ip[i] = *buffptr++;
addresses[numservers].type = NA_IP;
}
// IPv6 address, if it's an extended response
else if (extended && *buffptr == '/')
{
buffptr++;
if (buffend - buffptr < sizeof(addresses[numservers].ip6) + sizeof(addresses[numservers].port) + 1)
break;
for(i = 0; i < sizeof(addresses[numservers].ip6); i++)
addresses[numservers].ip6[i] = *buffptr++;
addresses[numservers].type = NA_IP6;
addresses[numservers].scope_id = from->scope_id;
}
else
// syntax error!
break;
// parse out port
addresses[numservers].port = (*buffptr++) << 8;
addresses[numservers].port += *buffptr++;
addresses[numservers].port = BigShort( addresses[numservers].port );
// syntax check
if (*buffptr != '\\' && *buffptr != '/')
break;
numservers++;
if (numservers >= MAX_SERVERSPERPACKET)
break;
}
count = cls.numglobalservers;
for (i = 0; i < numservers && count < MAX_GLOBAL_SERVERS; i++) {
// build net address
serverInfo_t *server = &cls.globalServers[count];
// Tequila: It's possible to have sent many master server requests. Then
// we may receive many times the same addresses from the master server.
// We just avoid to add a server if it is still in the global servers list.
for (j = 0; j < count; j++)
{
if (NET_CompareAdr(cls.globalServers[j].adr, addresses[i]))
break;
}
if (j < count)
continue;
CL_InitServerInfo( server, &addresses[i] );
// advance to next slot
count++;
}
// if getting the global list
if ( count >= MAX_GLOBAL_SERVERS && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS )
{
// if we couldn't store the servers in the main list anymore
for (; i < numservers && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS; i++)
{
// just store the addresses in an additional list
cls.globalServerAddresses[cls.numGlobalServerAddresses++] = addresses[i];
}
}
cls.numglobalservers = count;
total = count + cls.numGlobalServerAddresses;
Com_Printf("%d servers parsed (total %d)\n", numservers, total);
}
/*
=================
CL_ConnectionlessPacket
Responses to broadcasts, etc
=================
*/
void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) {
char *s;
char *c;
int challenge = 0;
MSG_BeginReadingOOB( msg );
MSG_ReadLong( msg ); // skip the -1
s = MSG_ReadStringLine( msg );
Cmd_TokenizeString( s );
c = Cmd_Argv(0);
Com_DPrintf ("CL packet %s: %s\n", NET_AdrToStringwPort(from), c);
// challenge from the server we are connecting to
if (!Q_stricmp(c, "challengeResponse"))
{
char *strver;
int ver;
if (clc.state != CA_CONNECTING)
{
Com_DPrintf("Unwanted challenge response received. Ignored.\n");
return;
}
c = Cmd_Argv(2);
if(*c)
challenge = atoi(c);
strver = Cmd_Argv(3);
if(*strver)
{
ver = atoi(strver);
if(ver != com_protocol->integer)
{
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer > 0)
{
// Server is ioq3 but has a different protocol than we do.
// Fall back to idq3 protocol.
clc.compat = qtrue;
Com_Printf(S_COLOR_YELLOW "Warning: Server reports protocol version %d, "
"we have %d. Trying legacy protocol %d.\n",
ver, com_protocol->integer, com_legacyprotocol->integer);
}
else
#endif
{
Com_Printf(S_COLOR_YELLOW "Warning: Server reports protocol version %d, we have %d. "
"Trying anyways.\n", ver, com_protocol->integer);
}
}
}
#ifdef LEGACY_PROTOCOL
else
clc.compat = qtrue;
if(clc.compat)
{
if(!NET_CompareAdr(from, clc.serverAddress))
{
// This challenge response is not coming from the expected address.
// Check whether we have a matching client challenge to prevent
// connection hi-jacking.
if(!*c || challenge != clc.challenge)
{
Com_DPrintf("Challenge response received from unexpected source. Ignored.\n");
return;
}
}
}
else
#endif
{
if(!*c || challenge != clc.challenge)
{
Com_Printf("Bad challenge for challengeResponse. Ignored.\n");
return;
}
}
// start sending challenge response instead of challenge request packets
clc.challenge = atoi(Cmd_Argv(1));
clc.state = CA_CHALLENGING;
clc.connectPacketCount = 0;
clc.connectTime = -99999;
// take this address as the new server address. This allows
// a server proxy to hand off connections to multiple servers
clc.serverAddress = from;
Com_DPrintf ("challengeResponse: %d\n", clc.challenge);
return;
}
// server connection
if ( !Q_stricmp(c, "connectResponse") ) {
if ( clc.state >= CA_CONNECTED ) {
Com_Printf ("Dup connect received. Ignored.\n");
return;
}
if ( clc.state != CA_CHALLENGING ) {
Com_Printf ("connectResponse packet while not connecting. Ignored.\n");
return;
}
if ( !NET_CompareAdr( from, clc.serverAddress ) ) {
Com_Printf( "connectResponse from wrong address. Ignored.\n" );
return;
}
#ifdef LEGACY_PROTOCOL
if(!clc.compat)
#endif
{
c = Cmd_Argv(1);
if(*c)
challenge = atoi(c);
else
{
Com_Printf("Bad connectResponse received. Ignored.\n");
return;
}
if(challenge != clc.challenge)
{
Com_Printf("ConnectResponse with bad challenge received. Ignored.\n");
return;
}
}
#ifdef LEGACY_PROTOCOL
Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableValue("net_qport"),
clc.challenge, clc.compat);
#else
Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableValue("net_qport"),
clc.challenge, qfalse);
#endif
clc.state = CA_CONNECTED;
clc.lastPacketSentTime = -9999; // send first packet immediately
return;
}
// server responding to an info broadcast
if ( !Q_stricmp(c, "infoResponse") ) {
CL_ServerInfoPacket( from, msg );
return;
}
// server responding to a get playerlist
if ( !Q_stricmp(c, "statusResponse") ) {
CL_ServerStatusResponse( from, msg );
return;
}
// echo request from server
if ( !Q_stricmp(c, "echo") ) {
NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv(1) );
return;
}
// cd check
if ( !Q_stricmp(c, "keyAuthorize") ) {
// we don't use these now, so dump them on the floor
return;
}
// global MOTD from id
if ( !Q_stricmp(c, "motd") ) {
CL_MotdPacket( from );
return;
}
// echo request from server
if(!Q_stricmp(c, "print")){
s = MSG_ReadString( msg );
Q_strncpyz( clc.serverMessage, s, sizeof( clc.serverMessage ) );
Com_Printf( "%s", s );
return;
}
// list of servers sent back by a master server (classic)
if ( !Q_strncmp(c, "getserversResponse", 18) ) {
CL_ServersResponsePacket( &from, msg, qfalse );
return;
}
// list of servers sent back by a master server (extended)
if ( !Q_strncmp(c, "getserversExtResponse", 21) ) {
CL_ServersResponsePacket( &from, msg, qtrue );
return;
}
Com_DPrintf ("Unknown connectionless packet command.\n");
}
/*
=================
CL_PacketEvent
A packet has arrived from the main event loop
=================
*/
void CL_PacketEvent( netadr_t from, msg_t *msg ) {
int headerBytes;
clc.lastPacketTime = cls.realtime;
if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) {
CL_ConnectionlessPacket( from, msg );
return;
}
if ( clc.state < CA_CONNECTED ) {
return; // can't be a valid sequenced packet
}
if ( msg->cursize < 4 ) {
Com_Printf ("%s: Runt packet\n", NET_AdrToStringwPort( from ));
return;
}
//
// packet from server
//
if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
Com_DPrintf ("%s:sequenced packet without connection\n"
, NET_AdrToStringwPort( from ) );
// FIXME: send a client disconnect?
return;
}
if (!CL_Netchan_Process( &clc.netchan, msg) ) {
return; // out of order, duplicated, etc
}
// the header is different lengths for reliable and unreliable messages
headerBytes = msg->readcount;
// track the last message received so it can be returned in
// client messages, allowing the server to detect a dropped
// gamestate
clc.serverMessageSequence = LittleLong( *(int *)msg->data );
clc.lastPacketTime = cls.realtime;
CL_ParseServerMessage( msg );
//
// we don't know if it is ok to save a demo message until
// after we have parsed the frame
//
if ( clc.demorecording && !clc.demowaiting ) {
CL_WriteDemoMessage( msg, headerBytes );
}
}
/*
==================
CL_CheckTimeout
==================
*/
void CL_CheckTimeout( void ) {
//
// check timeout
//
if ( ( !CL_CheckPaused() || !sv_paused->integer )
&& clc.state >= CA_CONNECTED && clc.state != CA_CINEMATIC
&& cls.realtime - clc.lastPacketTime > cl_timeout->value*1000) {
if (++cl.timeoutcount > 5) { // timeoutcount saves debugger
Com_Printf ("\nServer connection timed out.\n");
CL_Disconnect( qtrue );
return;
}
} else {
cl.timeoutcount = 0;
}
}
/*
==================
CL_CheckPaused
Check whether client has been paused.
==================
*/
qboolean CL_CheckPaused(void)
{
// if cl_paused->modified is set, the cvar has only been changed in
// this frame. Keep paused in this frame to ensure the server doesn't
// lag behind.
if(cl_paused->integer || cl_paused->modified)
return qtrue;
return qfalse;
}
//============================================================================
/*
==================
CL_CheckUserinfo
==================
*/
void CL_CheckUserinfo( void ) {
// don't add reliable commands when not yet connected
if(clc.state < CA_CONNECTED)
return;
// don't overflow the reliable command buffer when paused
if(CL_CheckPaused())
return;
// send a reliable userinfo update if needed
if(cvar_modifiedFlags & CVAR_USERINFO)
{
cvar_modifiedFlags &= ~CVAR_USERINFO;
CL_AddReliableCommand(va("userinfo \"%s\"", Cvar_InfoString( CVAR_USERINFO ) ), qfalse);
}
}
/*
==================
CL_Frame
==================
*/
void CL_Frame ( int msec ) {
if ( !com_cl_running->integer ) {
return;
}
#ifdef USE_CURL
if(clc.downloadCURLM) {
CL_cURL_PerformDownload();
// we can't process frames normally when in disconnected
// download mode since the ui vm expects clc.state to be
// CA_CONNECTED
if(clc.cURLDisconnected) {
cls.realFrametime = msec;
cls.frametime = msec;
cls.realtime += cls.frametime;
SCR_UpdateScreen();
S_Update();
Con_RunConsole();
cls.framecount++;
return;
}
}
#endif
if ( cls.cddialog ) {
// bring up the cd error dialog if needed
cls.cddialog = qfalse;
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NEED_CD );
} else if ( clc.state == CA_DISCONNECTED && !( Key_GetCatcher( ) & KEYCATCH_UI )
&& !com_sv_running->integer && uivm ) {
// if disconnected, bring up the menu
S_StopAllSounds();
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_MAIN );
}
// if recording an avi, lock to a fixed fps
if ( CL_VideoRecording( ) && cl_aviFrameRate->integer && msec) {
// save the current screen
if ( clc.state == CA_ACTIVE || cl_forceavidemo->integer) {
float fps = MIN(cl_aviFrameRate->value * com_timescale->value, 1000.0f);
float frameDuration = MAX(1000.0f / fps, 1.0f) + clc.aviVideoFrameRemainder;
CL_TakeVideoFrame( );
msec = (int)frameDuration;
clc.aviVideoFrameRemainder = frameDuration - msec;
}
}
if( cl_autoRecordDemo->integer ) {
if( clc.state == CA_ACTIVE && !clc.demorecording && !clc.demoplaying ) {
// If not recording a demo, and we should be, start one
qtime_t now;
char *nowString;
char *p;
char mapName[ MAX_QPATH ];
char serverName[ MAX_OSPATH ];
Com_RealTime( &now );
nowString = va( "%04d%02d%02d%02d%02d%02d",
1900 + now.tm_year,
1 + now.tm_mon,
now.tm_mday,
now.tm_hour,
now.tm_min,
now.tm_sec );
Q_strncpyz( serverName, clc.servername, MAX_OSPATH );
// Replace the ":" in the address as it is not a valid
// file name character
p = strstr( serverName, ":" );
if( p ) {
*p = '.';
}
Q_strncpyz( mapName, COM_SkipPath( cl.mapname ), sizeof( cl.mapname ) );
COM_StripExtension(mapName, mapName, sizeof(mapName));
Cbuf_ExecuteText( EXEC_NOW,
va( "record %s-%s-%s", nowString, serverName, mapName ) );
}
else if( clc.state != CA_ACTIVE && clc.demorecording ) {
// Recording, but not CA_ACTIVE, so stop recording
CL_StopRecord_f( );
}
}
// save the msec before checking pause
cls.realFrametime = msec;
// decide the simulation time
cls.frametime = msec;
cls.realtime += cls.frametime;
if ( cl_timegraph->integer ) {
SCR_DebugGraph ( cls.realFrametime * 0.25 );
}
// see if we need to update any userinfo
CL_CheckUserinfo();
// if we haven't gotten a packet in a long time,
// drop the connection
CL_CheckTimeout();
// send intentions now
CL_SendCmd();
// resend a connection request if necessary
CL_CheckForResend();
// decide on the serverTime to render
CL_SetCGameTime();
// update the screen
SCR_UpdateScreen();
// update audio
S_Update();
#ifdef USE_VOIP
CL_CaptureVoip();
#endif
#ifdef USE_MUMBLE
CL_UpdateMumble();
#endif
// advance local effects for next frame
SCR_RunCinematic();
Con_RunConsole();
cls.framecount++;
}
//============================================================================
/*
================
CL_RefPrintf
DLL glue
================
*/
static __attribute__ ((format (printf, 2, 3))) void QDECL CL_RefPrintf( int print_level, const char *fmt, ...) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start (argptr,fmt);
Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
va_end (argptr);
if ( print_level == PRINT_ALL ) {
Com_Printf ("%s", msg);
} else if ( print_level == PRINT_WARNING ) {
Com_Printf (S_COLOR_YELLOW "%s", msg); // yellow
} else if ( print_level == PRINT_DEVELOPER ) {
Com_DPrintf (S_COLOR_RED "%s", msg); // red
}
}
/*
============
CL_ShutdownRef
============
*/
void CL_ShutdownRef( void ) {
if ( re.Shutdown ) {
re.Shutdown( qtrue );
}
Com_Memset( &re, 0, sizeof( re ) );
#ifdef USE_RENDERER_DLOPEN
if ( rendererLib ) {
Sys_UnloadLibrary( rendererLib );
rendererLib = NULL;
}
#endif
}
/*
============
CL_InitRenderer
============
*/
void CL_InitRenderer( void ) {
// this sets up the renderer and calls R_Init
re.BeginRegistration( &cls.glconfig );
// load character sets
cls.charSetShader = re.RegisterShader( "gfx/2d/bigchars" );
cls.whiteShader = re.RegisterShader( "white" );
cls.consoleShader = re.RegisterShader( "console" );
g_console_field_width = cls.glconfig.vidWidth / SMALLCHAR_WIDTH - 2;
g_consoleField.widthInChars = g_console_field_width;
}
/*
============================
CL_StartHunkUsers
After the server has cleared the hunk, these will need to be restarted
This is the only place that any of these functions are called from
============================
*/
void CL_StartHunkUsers( qboolean rendererOnly ) {
if (!com_cl_running) {
return;
}
if ( !com_cl_running->integer ) {
return;
}
if ( !cls.rendererStarted ) {
cls.rendererStarted = qtrue;
CL_InitRenderer();
}
if ( rendererOnly ) {
return;
}
if ( !cls.soundStarted ) {
cls.soundStarted = qtrue;
S_Init();
}
if ( !cls.soundRegistered ) {
cls.soundRegistered = qtrue;
S_BeginRegistration();
}
if( com_dedicated->integer ) {
return;
}
if ( !cls.uiStarted ) {
cls.uiStarted = qtrue;
CL_InitUI();
}
}
/*
============
CL_RefMalloc
============
*/
void *CL_RefMalloc( int size ) {
return Z_TagMalloc( size, TAG_RENDERER );
}
int CL_ScaledMilliseconds(void) {
return Sys_Milliseconds()*com_timescale->value;
}
/*
============
CL_InitRef
============
*/
void CL_InitRef( void ) {
refimport_t ri;
refexport_t *ret;
#ifdef USE_RENDERER_DLOPEN
GetRefAPI_t GetRefAPI;
char dllName[MAX_OSPATH];
#endif
Com_Printf( "----- Initializing Renderer ----\n" );
#ifdef USE_RENDERER_DLOPEN
cl_renderer = Cvar_Get("cl_renderer", "opengl2", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED);
Com_sprintf(dllName, sizeof(dllName), "renderer_%s_" ARCH_STRING DLL_EXT, cl_renderer->string);
if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString))
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Cvar_ForceReset("cl_renderer");
Com_sprintf(dllName, sizeof(dllName), "renderer_opengl2_" ARCH_STRING DLL_EXT);
rendererLib = Sys_LoadDll(dllName, qfalse);
}
if(!rendererLib)
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Com_Error(ERR_FATAL, "Failed to load renderer");
}
GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI");
if(!GetRefAPI)
{
Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError());
}
#endif
ri.Cmd_AddCommand = Cmd_AddCommand;
ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
ri.Cmd_Argc = Cmd_Argc;
ri.Cmd_Argv = Cmd_Argv;
ri.Cmd_ExecuteText = Cbuf_ExecuteText;
ri.Printf = CL_RefPrintf;
ri.Error = Com_Error;
ri.Milliseconds = CL_ScaledMilliseconds;
ri.Malloc = CL_RefMalloc;
ri.Free = Z_Free;
#ifdef HUNK_DEBUG
ri.Hunk_AllocDebug = Hunk_AllocDebug;
#else
ri.Hunk_Alloc = Hunk_Alloc;
#endif
ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
ri.CM_ClusterPVS = CM_ClusterPVS;
ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
ri.FS_ReadFile = FS_ReadFile;
ri.FS_FreeFile = FS_FreeFile;
ri.FS_WriteFile = FS_WriteFile;
ri.FS_FreeFileList = FS_FreeFileList;
ri.FS_ListFiles = FS_ListFiles;
ri.FS_FileIsInPAK = FS_FileIsInPAK;
ri.FS_FileExists = FS_FileExists;
ri.Cvar_Get = Cvar_Get;
ri.Cvar_Set = Cvar_Set;
ri.Cvar_SetValue = Cvar_SetValue;
ri.Cvar_CheckRange = Cvar_CheckRange;
ri.Cvar_SetDescription = Cvar_SetDescription;
ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
// cinematic stuff
ri.CIN_UploadCinematic = CIN_UploadCinematic;
ri.CIN_PlayCinematic = CIN_PlayCinematic;
ri.CIN_RunCinematic = CIN_RunCinematic;
ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;
ri.IN_Init = IN_Init;
ri.IN_Shutdown = IN_Shutdown;
ri.IN_Restart = IN_Restart;
ri.ftol = Q_ftol;
ri.Sys_SetEnv = Sys_SetEnv;
ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit;
ri.Sys_GLimpInit = Sys_GLimpInit;
ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;
ret = GetRefAPI( REF_API_VERSION, &ri );
#if defined __USEA3D && defined __A3D_GEOM
hA3Dg_ExportRenderGeom (ret);
#endif
Com_Printf( "-------------------------------\n");
if ( !ret ) {
Com_Error (ERR_FATAL, "Couldn't initialize refresh" );
}
re = *ret;
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
}
//===========================================================================================
void CL_SetModel_f( void ) {
char *arg;
char name[256];
arg = Cmd_Argv( 1 );
if (arg[0]) {
Cvar_Set( "model", arg );
Cvar_Set( "headmodel", arg );
} else {
Cvar_VariableStringBuffer( "model", name, sizeof(name) );
Com_Printf("model is set to %s\n", name);
}
}
//===========================================================================================
/*
===============
CL_Video_f
video
video [filename]
===============
*/
void CL_Video_f( void )
{
char filename[ MAX_OSPATH ];
int i, last;
if( !clc.demoplaying )
{
Com_Printf( "The video command can only be used when playing back demos\n" );
return;
}
if( Cmd_Argc( ) == 2 )
{
// explicit filename
Com_sprintf( filename, MAX_OSPATH, "videos/%s.avi", Cmd_Argv( 1 ) );
}
else
{
// scan for a free filename
for( i = 0; i <= 9999; i++ )
{
int a, b, c, d;
last = i;
a = last / 1000;
last -= a * 1000;
b = last / 100;
last -= b * 100;
c = last / 10;
last -= c * 10;
d = last;
Com_sprintf( filename, MAX_OSPATH, "videos/video%d%d%d%d.avi",
a, b, c, d );
if( !FS_FileExists( filename ) )
break; // file doesn't exist
}
if( i > 9999 )
{
Com_Printf( S_COLOR_RED "ERROR: no free file names to create video\n" );
return;
}
}
CL_OpenAVIForWriting( filename );
}
/*
===============
CL_StopVideo_f
===============
*/
void CL_StopVideo_f( void )
{
CL_CloseAVI( );
}
/*
===============
CL_GenerateQKey
test to see if a valid QKEY_FILE exists. If one does not, try to generate
it by filling it with 2048 bytes of random data.
===============
*/
static void CL_GenerateQKey(void)
{
int len = 0;
unsigned char buff[ QKEY_SIZE ];
fileHandle_t f;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
if( len == QKEY_SIZE ) {
Com_Printf( "QKEY found.\n" );
return;
}
else {
if( len > 0 ) {
Com_Printf( "QKEY file size != %d, regenerating\n",
QKEY_SIZE );
}
Com_Printf( "QKEY building random string\n" );
Com_RandomBytes( buff, sizeof(buff) );
f = FS_SV_FOpenFileWrite( QKEY_FILE );
if( !f ) {
Com_Printf( "QKEY could not open %s for write\n",
QKEY_FILE );
return;
}
FS_Write( buff, sizeof(buff), f );
FS_FCloseFile( f );
Com_Printf( "QKEY generated\n" );
}
}
void CL_Sayto_f( void ) {
char *rawname;
char name[MAX_NAME_LENGTH];
char cleanName[MAX_NAME_LENGTH];
const char *info;
int count;
int i;
int clientNum;
char *p;
if ( Cmd_Argc() < 3 ) {
Com_Printf ("sayto <player name> <text>\n");
return;
}
rawname = Cmd_Argv(1);
Com_FieldStringToPlayerName( name, MAX_NAME_LENGTH, rawname );
info = cl.gameState.stringData + cl.gameState.stringOffsets[CS_SERVERINFO];
count = atoi( Info_ValueForKey( info, "sv_maxclients" ) );
clientNum = -1;
for( i = 0; i < count; i++ ) {
info = cl.gameState.stringData + cl.gameState.stringOffsets[CS_PLAYERS+i];
Q_strncpyz( cleanName, Info_ValueForKey( info, "n" ), sizeof(cleanName) );
Q_CleanStr( cleanName );
if ( !Q_stricmp( cleanName, name ) ) {
clientNum = i;
break;
}
}
if( clientNum <= -1 )
{
Com_Printf ("No such player name: %s.\n", name);
return;
}
p = Cmd_ArgsFrom(2);
if ( *p == '"' ) {
p++;
p[strlen(p)-1] = 0;
}
CL_AddReliableCommand(va("tell %i \"%s\"", clientNum, p ), qfalse);
}
/*
====================
CL_Init
====================
*/
void CL_Init( void ) {
Com_Printf( "----- Client Initialization -----\n" );
Con_Init ();
if(!com_fullyInitialized)
{
CL_ClearState();
clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
cl_oldGameSet = qfalse;
}
cls.realtime = 0;
CL_InitInput ();
//
// register our variables
//
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
#ifdef UPDATE_SERVER_NAME
cl_motd = Cvar_Get ("cl_motd", "1", 0);
#endif
cl_timeout = Cvar_Get ("cl_timeout", "200", 0);
cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP );
cl_showSend = Cvar_Get ("cl_showSend", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP );
cl_freezeDemo = Cvar_Get ("cl_freezeDemo", "0", CVAR_TEMP );
rcon_client_password = Cvar_Get ("rconPassword", "", CVAR_TEMP );
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_timedemo = Cvar_Get ("timedemo", "0", 0);
cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE);
cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE);
cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE);
cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE);
cl_forceavidemo = Cvar_Get ("cl_forceavidemo", "0", 0);
rconAddress = Cvar_Get ("rconAddress", "", 0);
cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE);
cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE);
cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", 0);
cl_maxpackets = Cvar_Get ("cl_maxpackets", "30", CVAR_ARCHIVE );
cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE );
cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE);
cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE);
cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE);
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE );
// 0: legacy mouse acceleration
// 1: new implementation
cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE );
// offset for the power function (for style 1, ignored otherwise)
// this should be set to the max rate value
cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE );
Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse);
cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0);
cl_allowDownload = Cvar_Get ("cl_allowDownload", "0", CVAR_ARCHIVE);
#ifdef USE_CURL_DLOPEN
cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE | CVAR_PROTECTED);
#endif
cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0);
#ifdef __APPLE__
// In game video is REALLY slow in Mac OS X right now due to driver slowness
cl_inGameVideo = Cvar_Get ("r_inGameVideo", "0", CVAR_ARCHIVE);
#else
cl_inGameVideo = Cvar_Get ("r_inGameVideo", "1", CVAR_ARCHIVE);
#endif
cl_serverStatusResendTime = Cvar_Get ("cl_serverStatusResendTime", "750", 0);
// init autoswitch so the ui will have it correctly even
// if the cgame hasn't been started
Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE);
m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE);
m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE);
m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE);
m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE);
#ifdef __APPLE__
// Input is jittery on OS X w/o this
m_filter = Cvar_Get ("m_filter", "1", CVAR_ARCHIVE);
#else
m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE);
#endif
j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE);
j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE);
j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE);
j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE);
j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE);
j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE);
j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE);
j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE);
j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE);
j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE);
Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM );
Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE );
cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE);
cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE);
// ~ and `, as keys and characters
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE);
// userinfo
Cvar_Get ("name", "UnnamedPlayer", CVAR_USERINFO | CVAR_ARCHIVE );
cl_rate = Cvar_Get ("rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("model", "sarge", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("headmodel", "sarge", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("team_model", "james", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("team_headmodel", "*james", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("g_redTeam", "Stroggs", CVAR_SERVERINFO | CVAR_ARCHIVE);
Cvar_Get ("g_blueTeam", "Pagans", CVAR_SERVERINFO | CVAR_ARCHIVE);
Cvar_Get ("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("color2", "5", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("teamtask", "0", CVAR_USERINFO );
Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("password", "", CVAR_USERINFO);
Cvar_Get ("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE );
#ifdef USE_MUMBLE
cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH);
cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE);
#endif
#ifdef USE_VOIP
cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0);
cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0);
cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE);
cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE);
cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE);
cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE);
cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE);
cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE);
Cvar_CheckRange( cl_voip, 0, 1, qtrue );
cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM);
#endif
// cgame might not be initialized before menu is used
Cvar_Get ("cg_viewsize", "100", CVAR_ARCHIVE );
// Make sure cg_stereoSeparation is zero as that variable is deprecated and should not be used anymore.
Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM);
//
// register our commands
//
Cmd_AddCommand ("cmd", CL_ForwardToServer_f);
Cmd_AddCommand ("configstrings", CL_Configstrings_f);
Cmd_AddCommand ("clientinfo", CL_Clientinfo_f);
Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f);
Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f);
Cmd_AddCommand ("disconnect", CL_Disconnect_f);
Cmd_AddCommand ("record", CL_Record_f);
Cmd_AddCommand ("demo", CL_PlayDemo_f);
Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName );
Cmd_AddCommand ("cinematic", CL_PlayCinematic_f);
Cmd_AddCommand ("stoprecord", CL_StopRecord_f);
Cmd_AddCommand ("connect", CL_Connect_f);
Cmd_AddCommand ("reconnect", CL_Reconnect_f);
Cmd_AddCommand ("localservers", CL_LocalServers_f);
Cmd_AddCommand ("globalservers", CL_GlobalServers_f);
Cmd_AddCommand ("rcon", CL_Rcon_f);
Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon );
Cmd_AddCommand ("ping", CL_Ping_f );
Cmd_AddCommand ("serverstatus", CL_ServerStatus_f );
Cmd_AddCommand ("showip", CL_ShowIP_f );
Cmd_AddCommand ("fs_openedList", CL_OpenedPK3List_f );
Cmd_AddCommand ("fs_referencedList", CL_ReferencedPK3List_f );
Cmd_AddCommand ("model", CL_SetModel_f );
Cmd_AddCommand ("video", CL_Video_f );
Cmd_AddCommand ("stopvideo", CL_StopVideo_f );
if( !com_dedicated->integer ) {
Cmd_AddCommand ("sayto", CL_Sayto_f );
Cmd_SetCommandCompletionFunc( "sayto", CL_CompletePlayerName );
}
CL_InitRef();
SCR_Init ();
// Cbuf_Execute ();
Cvar_Set( "cl_running", "1" );
CL_GenerateQKey();
Cvar_Get( "cl_guid", "", CVAR_USERINFO | CVAR_ROM );
CL_UpdateGUID( NULL, 0 );
Com_Printf( "----- Client Initialization Complete -----\n" );
}
/*
===============
CL_Shutdown
===============
*/
void CL_Shutdown(char *finalmsg, qboolean disconnect, qboolean quit)
{
static qboolean recursive = qfalse;
// check whether the client is running at all.
if(!(com_cl_running && com_cl_running->integer))
return;
Com_Printf( "----- Client Shutdown (%s) -----\n", finalmsg );
if ( recursive ) {
Com_Printf( "WARNING: Recursive shutdown\n" );
return;
}
recursive = qtrue;
noGameRestart = quit;
if(disconnect)
CL_Disconnect(qtrue);
CL_ClearMemory(qtrue);
CL_Snd_Shutdown();
Cmd_RemoveCommand ("cmd");
Cmd_RemoveCommand ("configstrings");
Cmd_RemoveCommand ("clientinfo");
Cmd_RemoveCommand ("snd_restart");
Cmd_RemoveCommand ("vid_restart");
Cmd_RemoveCommand ("disconnect");
Cmd_RemoveCommand ("record");
Cmd_RemoveCommand ("demo");
Cmd_RemoveCommand ("cinematic");
Cmd_RemoveCommand ("stoprecord");
Cmd_RemoveCommand ("connect");
Cmd_RemoveCommand ("reconnect");
Cmd_RemoveCommand ("localservers");
Cmd_RemoveCommand ("globalservers");
Cmd_RemoveCommand ("rcon");
Cmd_RemoveCommand ("ping");
Cmd_RemoveCommand ("serverstatus");
Cmd_RemoveCommand ("showip");
Cmd_RemoveCommand ("fs_openedList");
Cmd_RemoveCommand ("fs_referencedList");
Cmd_RemoveCommand ("model");
Cmd_RemoveCommand ("video");
Cmd_RemoveCommand ("stopvideo");
CL_ShutdownInput();
Con_Shutdown();
Cvar_Set( "cl_running", "0" );
recursive = qfalse;
Com_Memset( &cls, 0, sizeof( cls ) );
Key_SetCatcher( 0 );
Com_Printf( "-----------------------\n" );
}
static void CL_SetServerInfo(serverInfo_t *server, const char *info, int ping) {
if (server) {
if (info) {
server->clients = atoi(Info_ValueForKey(info, "clients"));
Q_strncpyz(server->hostName,Info_ValueForKey(info, "hostname"), MAX_NAME_LENGTH);
Q_strncpyz(server->mapName, Info_ValueForKey(info, "mapname"), MAX_NAME_LENGTH);
server->maxClients = atoi(Info_ValueForKey(info, "sv_maxclients"));
Q_strncpyz(server->game,Info_ValueForKey(info, "game"), MAX_NAME_LENGTH);
server->gameType = atoi(Info_ValueForKey(info, "gametype"));
server->netType = atoi(Info_ValueForKey(info, "nettype"));
server->minPing = atoi(Info_ValueForKey(info, "minping"));
server->maxPing = atoi(Info_ValueForKey(info, "maxping"));
server->punkbuster = atoi(Info_ValueForKey(info, "punkbuster"));
server->g_humanplayers = atoi(Info_ValueForKey(info, "g_humanplayers"));
server->g_needpass = atoi(Info_ValueForKey(info, "g_needpass"));
}
server->ping = ping;
}
}
static void CL_SetServerInfoByAddress(netadr_t from, const char *info, int ping) {
int i;
for (i = 0; i < MAX_OTHER_SERVERS; i++) {
if (NET_CompareAdr(from, cls.localServers[i].adr)) {
CL_SetServerInfo(&cls.localServers[i], info, ping);
}
}
for (i = 0; i < MAX_GLOBAL_SERVERS; i++) {
if (NET_CompareAdr(from, cls.globalServers[i].adr)) {
CL_SetServerInfo(&cls.globalServers[i], info, ping);
}
}
for (i = 0; i < MAX_OTHER_SERVERS; i++) {
if (NET_CompareAdr(from, cls.favoriteServers[i].adr)) {
CL_SetServerInfo(&cls.favoriteServers[i], info, ping);
}
}
}
/*
===================
CL_ServerInfoPacket
===================
*/
void CL_ServerInfoPacket( netadr_t from, msg_t *msg ) {
int i, type;
char info[MAX_INFO_STRING];
char *infoString;
int prot;
char *gamename;
qboolean gameMismatch;
infoString = MSG_ReadString( msg );
// if this isn't the correct gamename, ignore it
gamename = Info_ValueForKey( infoString, "gamename" );
#ifdef LEGACY_PROTOCOL
// gamename is optional for legacy protocol
if (com_legacyprotocol->integer && !*gamename)
gameMismatch = qfalse;
else
#endif
gameMismatch = !*gamename || strcmp(gamename, com_gamename->string) != 0;
if (gameMismatch)
{
Com_DPrintf( "Game mismatch in info packet: %s\n", infoString );
return;
}
// if this isn't the correct protocol version, ignore it
prot = atoi( Info_ValueForKey( infoString, "protocol" ) );
if(prot != com_protocol->integer
#ifdef LEGACY_PROTOCOL
&& prot != com_legacyprotocol->integer
#endif
)
{
Com_DPrintf( "Different protocol info packet: %s\n", infoString );
return;
}
// iterate servers waiting for ping response
for (i=0; i<MAX_PINGREQUESTS; i++)
{
if ( cl_pinglist[i].adr.port && !cl_pinglist[i].time && NET_CompareAdr( from, cl_pinglist[i].adr ) )
{
// calc ping time
cl_pinglist[i].time = Sys_Milliseconds() - cl_pinglist[i].start;
Com_DPrintf( "ping time %dms from %s\n", cl_pinglist[i].time, NET_AdrToString( from ) );
// save of info
Q_strncpyz( cl_pinglist[i].info, infoString, sizeof( cl_pinglist[i].info ) );
// tack on the net type
// NOTE: make sure these types are in sync with the netnames strings in the UI
switch (from.type)
{
case NA_BROADCAST:
case NA_IP:
type = 1;
break;
case NA_IP6:
type = 2;
break;
default:
type = 0;
break;
}
Info_SetValueForKey( cl_pinglist[i].info, "nettype", va("%d", type) );
CL_SetServerInfoByAddress(from, infoString, cl_pinglist[i].time);
return;
}
}
// if not just sent a local broadcast or pinging local servers
if (cls.pingUpdateSource != AS_LOCAL) {
return;
}
for ( i = 0 ; i < MAX_OTHER_SERVERS ; i++ ) {
// empty slot
if ( cls.localServers[i].adr.port == 0 ) {
break;
}
// avoid duplicate
if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) {
return;
}
}
if ( i == MAX_OTHER_SERVERS ) {
Com_DPrintf( "MAX_OTHER_SERVERS hit, dropping infoResponse\n" );
return;
}
// add this to the list
cls.numlocalservers = i+1;
CL_InitServerInfo( &cls.localServers[i], &from );
Q_strncpyz( info, MSG_ReadString( msg ), MAX_INFO_STRING );
if (strlen(info)) {
if (info[strlen(info)-1] != '\n') {
Q_strcat(info, sizeof(info), "\n");
}
Com_Printf( "%s: %s", NET_AdrToStringwPort( from ), info );
}
}
/*
===================
CL_GetServerStatus
===================
*/
serverStatus_t *CL_GetServerStatus( netadr_t from ) {
int i, oldest, oldestTime;
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
return &cl_serverStatusList[i];
}
}
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
if ( cl_serverStatusList[i].retrieved ) {
return &cl_serverStatusList[i];
}
}
oldest = -1;
oldestTime = 0;
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
if (oldest == -1 || cl_serverStatusList[i].startTime < oldestTime) {
oldest = i;
oldestTime = cl_serverStatusList[i].startTime;
}
}
return &cl_serverStatusList[oldest];
}
/*
===================
CL_ServerStatus
===================
*/
int CL_ServerStatus( char *serverAddress, char *serverStatusString, int maxLen ) {
int i;
netadr_t to;
serverStatus_t *serverStatus;
// if no server address then reset all server status requests
if ( !serverAddress ) {
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
cl_serverStatusList[i].address.port = 0;
cl_serverStatusList[i].retrieved = qtrue;
}
return qfalse;
}
// get the address
if ( !NET_StringToAdr( serverAddress, &to, NA_UNSPEC) ) {
return qfalse;
}
serverStatus = CL_GetServerStatus( to );
// if no server status string then reset the server status request for this address
if ( !serverStatusString ) {
serverStatus->retrieved = qtrue;
return qfalse;
}
// if this server status request has the same address
if ( NET_CompareAdr( to, serverStatus->address) ) {
// if we received a response for this server status request
if (!serverStatus->pending) {
Q_strncpyz(serverStatusString, serverStatus->string, maxLen);
serverStatus->retrieved = qtrue;
serverStatus->startTime = 0;
return qtrue;
}
// resend the request regularly
else if ( serverStatus->startTime < Com_Milliseconds() - cl_serverStatusResendTime->integer ) {
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->time = 0;
serverStatus->startTime = Com_Milliseconds();
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
}
// if retrieved
else if ( serverStatus->retrieved ) {
serverStatus->address = to;
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->startTime = Com_Milliseconds();
serverStatus->time = 0;
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
return qfalse;
}
/*
===================
CL_ServerStatusResponse
===================
*/
void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) {
char *s;
char info[MAX_INFO_STRING];
int i, l, score, ping;
int len;
serverStatus_t *serverStatus;
serverStatus = NULL;
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
serverStatus = &cl_serverStatusList[i];
break;
}
}
// if we didn't request this server status
if (!serverStatus) {
return;
}
s = MSG_ReadStringLine( msg );
len = 0;
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "%s", s);
if (serverStatus->print) {
Com_Printf("Server settings:\n");
// print cvars
while (*s) {
for (i = 0; i < 2 && *s; i++) {
if (*s == '\\')
s++;
l = 0;
while (*s) {
info[l++] = *s;
if (l >= MAX_INFO_STRING-1)
break;
s++;
if (*s == '\\') {
break;
}
}
info[l] = '\0';
if (i) {
Com_Printf("%s\n", info);
}
else {
Com_Printf("%-24s", info);
}
}
}
}
len = strlen(serverStatus->string);
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\");
if (serverStatus->print) {
Com_Printf("\nPlayers:\n");
Com_Printf("num: score: ping: name:\n");
}
for (i = 0, s = MSG_ReadStringLine( msg ); *s; s = MSG_ReadStringLine( msg ), i++) {
len = strlen(serverStatus->string);
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\%s", s);
if (serverStatus->print) {
score = ping = 0;
sscanf(s, "%d %d", &score, &ping);
s = strchr(s, ' ');
if (s)
s = strchr(s+1, ' ');
if (s)
s++;
else
s = "unknown";
Com_Printf("%-2d %-3d %-3d %s\n", i, score, ping, s );
}
}
len = strlen(serverStatus->string);
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\");
serverStatus->time = Com_Milliseconds();
serverStatus->address = from;
serverStatus->pending = qfalse;
if (serverStatus->print) {
serverStatus->retrieved = qtrue;
}
}
/*
==================
CL_LocalServers_f
==================
*/
void CL_LocalServers_f( void ) {
char *message;
int i, j;
netadr_t to;
Com_Printf( "Scanning for servers on the local network...\n");
// reset the list, waiting for response
cls.numlocalservers = 0;
cls.pingUpdateSource = AS_LOCAL;
for (i = 0; i < MAX_OTHER_SERVERS; i++) {
qboolean b = cls.localServers[i].visible;
Com_Memset(&cls.localServers[i], 0, sizeof(cls.localServers[i]));
cls.localServers[i].visible = b;
}
Com_Memset( &to, 0, sizeof( to ) );
// The 'xxx' in the message is a challenge that will be echoed back
// by the server. We don't care about that here, but master servers
// can use that to prevent spoofed server responses from invalid ip
message = "\377\377\377\377getinfo xxx";
// send each message twice in case one is dropped
for ( i = 0 ; i < 2 ; i++ ) {
// send a broadcast packet on each server port
// we support multiple server ports so a single machine
// can nicely run multiple servers
for ( j = 0 ; j < NUM_SERVER_PORTS ; j++ ) {
to.port = BigShort( (short)(PORT_SERVER + j) );
to.type = NA_BROADCAST;
NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
to.type = NA_MULTICAST6;
NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
}
}
}
/*
==================
CL_GlobalServers_f
==================
*/
void CL_GlobalServers_f( void ) {
netadr_t to;
int count, i, masterNum;
char command[1024], *masteraddress;
if ((count = Cmd_Argc()) < 3 || (masterNum = atoi(Cmd_Argv(1))) < 0 || masterNum > MAX_MASTER_SERVERS - 1)
{
Com_Printf("usage: globalservers <master# 0-%d> <protocol> [keywords]\n", MAX_MASTER_SERVERS - 1);
return;
}
sprintf(command, "sv_master%d", masterNum + 1);
masteraddress = Cvar_VariableString(command);
if(!*masteraddress)
{
Com_Printf( "CL_GlobalServers_f: Error: No master server address given.\n");
return;
}
// reset the list, waiting for response
// -1 is used to distinguish a "no response"
i = NET_StringToAdr(masteraddress, &to, NA_UNSPEC);
if(!i)
{
Com_Printf( "CL_GlobalServers_f: Error: could not resolve address of master %s\n", masteraddress);
return;
}
else if(i == 2)
to.port = BigShort(PORT_MASTER);
Com_Printf("Requesting servers from master %s...\n", masteraddress);
cls.numglobalservers = -1;
cls.pingUpdateSource = AS_GLOBAL;
// Use the extended query for IPv6 masters
if (to.type == NA_IP6 || to.type == NA_MULTICAST6)
{
int v4enabled = Cvar_VariableIntegerValue("net_enabled") & NET_ENABLEV4;
if(v4enabled)
{
Com_sprintf(command, sizeof(command), "getserversExt %s %s",
com_gamename->string, Cmd_Argv(2));
}
else
{
Com_sprintf(command, sizeof(command), "getserversExt %s %s ipv6",
com_gamename->string, Cmd_Argv(2));
}
}
else if ( !Q_stricmp( com_gamename->string, LEGACY_MASTER_GAMENAME ) )
Com_sprintf(command, sizeof(command), "getservers %s",
Cmd_Argv(2));
else
Com_sprintf(command, sizeof(command), "getservers %s %s",
com_gamename->string, Cmd_Argv(2));
for (i=3; i < count; i++)
{
Q_strcat(command, sizeof(command), " ");
Q_strcat(command, sizeof(command), Cmd_Argv(i));
}
NET_OutOfBandPrint( NS_SERVER, to, "%s", command );
}
/*
==================
CL_GetPing
==================
*/
void CL_GetPing( int n, char *buf, int buflen, int *pingtime )
{
const char *str;
int time;
int maxPing;
if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port)
{
// empty or invalid slot
buf[0] = '\0';
*pingtime = 0;
return;
}
str = NET_AdrToStringwPort( cl_pinglist[n].adr );
Q_strncpyz( buf, str, buflen );
time = cl_pinglist[n].time;
if (!time)
{
// check for timeout
time = Sys_Milliseconds() - cl_pinglist[n].start;
maxPing = Cvar_VariableIntegerValue( "cl_maxPing" );
if( maxPing < 100 ) {
maxPing = 100;
}
if (time < maxPing)
{
// not timed out yet
time = 0;
}
}
CL_SetServerInfoByAddress(cl_pinglist[n].adr, cl_pinglist[n].info, cl_pinglist[n].time);
*pingtime = time;
}
/*
==================
CL_GetPingInfo
==================
*/
void CL_GetPingInfo( int n, char *buf, int buflen )
{
if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port)
{
// empty or invalid slot
if (buflen)
buf[0] = '\0';
return;
}
Q_strncpyz( buf, cl_pinglist[n].info, buflen );
}
/*
==================
CL_ClearPing
==================
*/
void CL_ClearPing( int n )
{
if (n < 0 || n >= MAX_PINGREQUESTS)
return;
cl_pinglist[n].adr.port = 0;
}
/*
==================
CL_GetPingQueueCount
==================
*/
int CL_GetPingQueueCount( void )
{
int i;
int count;
ping_t* pingptr;
count = 0;
pingptr = cl_pinglist;
for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ ) {
if (pingptr->adr.port) {
count++;
}
}
return (count);
}
/*
==================
CL_GetFreePing
==================
*/
ping_t* CL_GetFreePing( void )
{
ping_t* pingptr;
ping_t* best;
int oldest;
int i;
int time;
pingptr = cl_pinglist;
for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ )
{
// find free ping slot
if (pingptr->adr.port)
{
if (!pingptr->time)
{
if (Sys_Milliseconds() - pingptr->start < 500)
{
// still waiting for response
continue;
}
}
else if (pingptr->time < 500)
{
// results have not been queried
continue;
}
}
// clear it
pingptr->adr.port = 0;
return (pingptr);
}
// use oldest entry
pingptr = cl_pinglist;
best = cl_pinglist;
oldest = INT_MIN;
for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ )
{
// scan for oldest
time = Sys_Milliseconds() - pingptr->start;
if (time > oldest)
{
oldest = time;
best = pingptr;
}
}
return (best);
}
/*
==================
CL_Ping_f
==================
*/
void CL_Ping_f( void ) {
netadr_t to;
ping_t* pingptr;
char* server;
int argc;
netadrtype_t family = NA_UNSPEC;
argc = Cmd_Argc();
if ( argc != 2 && argc != 3 ) {
Com_Printf( "usage: ping [-4|-6] server\n");
return;
}
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
Com_Memset( &to, 0, sizeof(netadr_t) );
if ( !NET_StringToAdr( server, &to, family ) ) {
return;
}
pingptr = CL_GetFreePing();
memcpy( &pingptr->adr, &to, sizeof (netadr_t) );
pingptr->start = Sys_Milliseconds();
pingptr->time = 0;
CL_SetServerInfoByAddress(pingptr->adr, NULL, 0);
NET_OutOfBandPrint( NS_CLIENT, to, "getinfo xxx" );
}
/*
==================
CL_UpdateVisiblePings_f
==================
*/
qboolean CL_UpdateVisiblePings_f(int source) {
int slots, i;
char buff[MAX_STRING_CHARS];
int pingTime;
int max;
qboolean status = qfalse;
if (source < 0 || source > AS_FAVORITES) {
return qfalse;
}
cls.pingUpdateSource = source;
slots = CL_GetPingQueueCount();
if (slots < MAX_PINGREQUESTS) {
serverInfo_t *server = NULL;
switch (source) {
case AS_LOCAL :
server = &cls.localServers[0];
max = cls.numlocalservers;
break;
case AS_GLOBAL :
server = &cls.globalServers[0];
max = cls.numglobalservers;
break;
case AS_FAVORITES :
server = &cls.favoriteServers[0];
max = cls.numfavoriteservers;
break;
default:
return qfalse;
}
for (i = 0; i < max; i++) {
if (server[i].visible) {
if (server[i].ping == -1) {
int j;
if (slots >= MAX_PINGREQUESTS) {
break;
}
for (j = 0; j < MAX_PINGREQUESTS; j++) {
if (!cl_pinglist[j].adr.port) {
continue;
}
if (NET_CompareAdr( cl_pinglist[j].adr, server[i].adr)) {
// already on the list
break;
}
}
if (j >= MAX_PINGREQUESTS) {
status = qtrue;
for (j = 0; j < MAX_PINGREQUESTS; j++) {
if (!cl_pinglist[j].adr.port) {
break;
}
}
memcpy(&cl_pinglist[j].adr, &server[i].adr, sizeof(netadr_t));
cl_pinglist[j].start = Sys_Milliseconds();
cl_pinglist[j].time = 0;
NET_OutOfBandPrint( NS_CLIENT, cl_pinglist[j].adr, "getinfo xxx" );
slots++;
}
}
// if the server has a ping higher than cl_maxPing or
// the ping packet got lost
else if (server[i].ping == 0) {
// if we are updating global servers
if (source == AS_GLOBAL) {
//
if ( cls.numGlobalServerAddresses > 0 ) {
// overwrite this server with one from the additional global servers
cls.numGlobalServerAddresses--;
CL_InitServerInfo(&server[i], &cls.globalServerAddresses[cls.numGlobalServerAddresses]);
// NOTE: the server[i].visible flag stays untouched
}
}
}
}
}
}
if (slots) {
status = qtrue;
}
for (i = 0; i < MAX_PINGREQUESTS; i++) {
if (!cl_pinglist[i].adr.port) {
continue;
}
CL_GetPing( i, buff, MAX_STRING_CHARS, &pingTime );
if (pingTime != 0) {
CL_ClearPing(i);
status = qtrue;
}
}
return status;
}
/*
==================
CL_ServerStatus_f
==================
*/
void CL_ServerStatus_f(void) {
netadr_t to, *toptr = NULL;
char *server;
serverStatus_t *serverStatus;
int argc;
netadrtype_t family = NA_UNSPEC;
argc = Cmd_Argc();
if ( argc != 2 && argc != 3 )
{
if (clc.state != CA_ACTIVE || clc.demoplaying)
{
Com_Printf ("Not connected to a server.\n");
Com_Printf( "usage: serverstatus [-4|-6] server\n");
return;
}
toptr = &clc.serverAddress;
}
if(!toptr)
{
Com_Memset( &to, 0, sizeof(netadr_t) );
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
toptr = &to;
if ( !NET_StringToAdr( server, toptr, family ) )
return;
}
NET_OutOfBandPrint( NS_CLIENT, *toptr, "getstatus" );
serverStatus = CL_GetServerStatus( *toptr );
serverStatus->address = *toptr;
serverStatus->print = qtrue;
serverStatus->pending = qtrue;
}
/*
==================
CL_ShowIP_f
==================
*/
void CL_ShowIP_f(void) {
Sys_ShowIP();
}
/*
=================
CL_CDKeyValidate
=================
*/
qboolean CL_CDKeyValidate( const char *key, const char *checksum ) {
#ifdef STANDALONE
return qtrue;
#else
char ch;
byte sum;
char chs[3];
int i, len;
len = strlen(key);
if( len != CDKEY_LEN ) {
return qfalse;
}
if( checksum && strlen( checksum ) != CDCHKSUM_LEN ) {
return qfalse;
}
sum = 0;
// for loop gets rid of conditional assignment warning
for (i = 0; i < len; i++) {
ch = *key++;
if (ch>='a' && ch<='z') {
ch -= 32;
}
switch( ch ) {
case '2':
case '3':
case '7':
case 'A':
case 'B':
case 'C':
case 'D':
case 'G':
case 'H':
case 'J':
case 'L':
case 'P':
case 'R':
case 'S':
case 'T':
case 'W':
sum += ch;
continue;
default:
return qfalse;
}
}
sprintf(chs, "%02x", sum);
if (checksum && !Q_stricmp(chs, checksum)) {
return qtrue;
}
if (!checksum) {
return qtrue;
}
return qfalse;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3228_0 |
crossvul-cpp_data_good_3233_4 | /*
===========================================================================
Return to Castle Wolfenstein single player GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein single player GPL Source Code (RTCW SP Source Code).
RTCW SP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW SP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
/*****************************************************************************
* name: files.c
*
* desc: handle based filesystem for Quake III Arena
*
*
*****************************************************************************/
#include "q_shared.h"
#include "qcommon.h"
#include "../zlib-1.2.8/unzip.h"
/*
=============================================================================
QUAKE3 FILESYSTEM
All of Quake's data access is through a hierarchical file system, but the contents of
the file system can be transparently merged from several sources.
A "qpath" is a reference to game file data. MAX_ZPATH is 256 characters, which must include
a terminating zero. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any
references outside the quake directory system.
The "base path" is the path to the directory holding all the game directories and usually
the executable. It defaults to ".", but can be overridden with a "+set fs_basepath c:\quake3"
command line to allow code debugging in a different directory. Basepath cannot
be modified at all after startup. Any files that are created (demos, screenshots,
etc) will be created relative to the base path, so base path should usually be writable.
The "home path" is the path used for all write access. On win32 systems we have "base path"
== "home path", but on *nix systems the base installation is usually readonly, and
"home path" points to ~/.q3a or similar
The user can also install custom mods and content in "home path", so it should be searched
along with "home path" and "cd path" for game content.
The "base game" is the directory under the paths where data comes from by default, and
can be either "baseq3" or "demoq3".
The "current game" may be the same as the base game, or it may be the name of another
directory under the paths that should be searched for files before looking in the base game.
This is the basis for addons.
Clients automatically set the game directory after receiving a gamestate from a server,
so only servers need to worry about +set fs_game.
No other directories outside of the base game and current game will ever be referenced by
filesystem functions.
To save disk space and speed loading, directory trees can be collapsed into zip files.
The files use a ".pk3" extension to prevent users from unzipping them accidentally, but
otherwise the are simply normal uncompressed zip files. A game directory can have multiple
zip files of the form "pak0.pk3", "pak1.pk3", etc. Zip files are searched in decending order
from the highest number to the lowest, and will always take precedence over the filesystem.
This allows a pk3 distributed as a patch to override all existing data.
Because we will have updated executables freely available online, there is no point to
trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
should be exactly the same executables as release versions, but with different data that
automatically restricts where game media can come from to prevent add-ons from working.
Additionaly, we search in several subdirectories:
current game is the current mode
base game is a variable to allow mods based on other mods
(such as baseq3 + missionpack content combination in a mod for instance)
BASEGAME is the hardcoded base game ("baseq3")
e.g. the qpath "sound/newstuff/test.wav" would be searched for in the following places:
home path + current game's zip files
home path + current game's directory
base path + current game's zip files
base path + current game's directory
cd path + current game's zip files
cd path + current game's directory
home path + base game's zip file
home path + base game's directory
base path + base game's zip file
base path + base game's directory
cd path + base game's zip file
cd path + base game's directory
home path + BASEGAME's zip file
home path + BASEGAME's directory
base path + BASEGAME's zip file
base path + BASEGAME's directory
cd path + BASEGAME's zip file
cd path + BASEGAME's directory
server download, to be written to home path + current game's directory
The filesystem can be safely shutdown and reinitialized with different
basedir / cddir / game combinations, but all other subsystems that rely on it
(sound, video) must also be forced to restart.
Because the same files are loaded by both the clip model (CM_) and renderer (TR_)
subsystems, a simple single-file caching scheme is used. The CM_ subsystems will
load the file with a request to cache. Only one file will be kept cached at a time,
so any models that are going to be referenced by both subsystems should alternate
between the CM_ load function and the ref load function.
TODO: A qpath that starts with a leading slash will always refer to the base game, even if another
game is currently active. This allows character models, skins, and sounds to be downloaded
to a common directory no matter which game is active.
How to prevent downloading zip files?
Pass pk3 file names in systeminfo, and download before FS_Restart()?
Aborting a download disconnects the client from the server.
How to mark files as downloadable? Commercial add-ons won't be downloadable.
Non-commercial downloads will want to download the entire zip file.
the game would have to be reset to actually read the zip in
Auto-update information
Path separators
Casing
separate server gamedir and client gamedir, so if the user starts
a local game after having connected to a network game, it won't stick
with the network game.
allow menu options for game selection?
Read / write config to floppy option.
Different version coexistance?
When building a pak file, make sure a wolfconfig.cfg isn't present in it,
or configs will never get loaded from disk!
todo:
downloading (outside fs?)
game directory passing and restarting
=============================================================================
*/
// every time a new demo pk3 file is built, this checksum must be updated.
// the easiest way to get it is to just run the game and see what it spits out
#define DEMO_PAK0_CHECKSUM 2985661941u
static const unsigned int pak_checksums[] = {
1886207346u
};
static const unsigned int en_sppak_checksums[] = {
2837138611u,
3033901371u,
483593179u,
// sp_pak4.pk3 from GOTY edition
4131017020u
};
static const unsigned int fr_sppak_checksums[] = {
2183777857u,
3033901371u,
839012592u,
// sp_pak4.pk3 from GOTY edition
4131017020u
};
static const unsigned int gm_sppak_checksums[] = {
3078133571u,
285968110u,
2694180987u,
// sp_pak4.pk3 from GOTY edition
4131017020u
};
static const unsigned int it_sppak_checksums[] = {
3826630960u,
3033901371u,
652965486u,
// sp_pak4.pk3 from GOTY edition
4131017020u
};
static const unsigned int sp_sppak_checksums[] = {
652879493u,
3033901371u,
1162920123u,
// sp_pak4.pk3 from GOTY edition
4131017020u
};
// if this is defined, the executable positively won't work with any paks other
// than the demo pak, even if productid is present. This is only used for our
// last demo release to prevent the mac and linux users from using the demo
// executable with the production windows pak before the mac/linux products
// hit the shelves a little later
// NOW defined in build files
//#define PRE_RELEASE_TADEMO
#define MAX_ZPATH 256
#define MAX_SEARCH_PATHS 4096
#define MAX_FILEHASH_SIZE 1024
typedef struct fileInPack_s {
char *name; // name of the file
unsigned long pos; // file info position in zip
unsigned long len; // uncompress file size
struct fileInPack_s* next; // next file in the hash
} fileInPack_t;
typedef struct {
char pakPathname[MAX_OSPATH]; // c:\quake3\baseq3
char pakFilename[MAX_OSPATH]; // c:\quake3\baseq3\pak0.pk3
char pakBasename[MAX_OSPATH]; // pak0
char pakGamename[MAX_OSPATH]; // baseq3
unzFile handle; // handle to zip file
int checksum; // regular checksum
int pure_checksum; // checksum for pure
int numfiles; // number of files in pk3
int referenced; // referenced file flags
int hashSize; // hash table size (power of 2)
fileInPack_t* *hashTable; // hash table
fileInPack_t* buildBuffer; // buffer with the filenames etc.
} pack_t;
typedef struct {
char path[MAX_OSPATH]; // c:\quake3
char fullpath[MAX_OSPATH]; // c:\quake3\baseq3
char gamedir[MAX_OSPATH]; // baseq3
} directory_t;
typedef struct searchpath_s {
struct searchpath_s *next;
pack_t *pack; // only one of pack / dir will be non NULL
directory_t *dir;
} searchpath_t;
static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators
static cvar_t *fs_debug;
static cvar_t *fs_homepath;
#ifdef __APPLE__
// Also search the .app bundle for .pk3 files
static cvar_t *fs_apppath;
#endif
#ifndef STANDALONE
static cvar_t *fs_steampath;
#endif
static cvar_t *fs_basepath;
static cvar_t *fs_basegame;
static cvar_t *fs_gamedirvar;
static searchpath_t *fs_searchpaths;
static int fs_readCount; // total bytes read
static int fs_loadCount; // total files read
static int fs_loadStack; // total files in memory
static int fs_packFiles = 0; // total number of files in packs
static int fs_checksumFeed;
typedef union qfile_gus {
FILE* o;
unzFile z;
} qfile_gut;
typedef struct qfile_us {
qfile_gut file;
qboolean unique;
} qfile_ut;
typedef struct {
qfile_ut handleFiles;
qboolean handleSync;
int fileSize;
int zipFilePos;
int zipFileLen;
qboolean zipFile;
qboolean streamed;
char name[MAX_ZPATH];
} fileHandleData_t;
static fileHandleData_t fsh[MAX_FILE_HANDLES];
// TTimo - https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
// wether we did a reorder on the current search path when joining the server
static qboolean fs_reordered;
// never load anything from pk3 files that are not present at the server when pure
static int fs_numServerPaks = 0;
static int fs_serverPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverPakNames[MAX_SEARCH_PATHS]; // pk3 names
// only used for autodownload, to make sure the client has at least
// all the pk3 files that are referenced at the server side
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS]; // pk3 names
// last valid game folder used
char lastValidBase[MAX_OSPATH];
char lastValidComBaseGame[MAX_OSPATH];
char lastValidFsBaseGame[MAX_OSPATH];
char lastValidGame[MAX_OSPATH];
#ifdef FS_MISSING
FILE* missingFiles = NULL;
#endif
/* C99 defines __func__ */
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2 || _MSC_VER >= 1300
# define __func__ __FUNCTION__
# else
# define __func__ "(unknown)"
# endif
#endif
/*
==============
FS_Initialized
==============
*/
qboolean FS_Initialized( void ) {
return ( fs_searchpaths != NULL );
}
/*
=================
FS_PakIsPure
=================
*/
qboolean FS_PakIsPure( pack_t *pack ) {
int i;
if ( fs_numServerPaks ) {
// NOTE TTimo we are matching checksums without checking the pak names
// this means you can have the same pk3 as the server under a different name, you will still get through sv_pure validation
// (what happens when two pk3's have the same checkums? is it a likely situation?)
// also, if there's a wrong checksumed pk3 and autodownload is enabled, the checksum will be appended to the downloaded pk3 name
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
// FIXME: also use hashed file names
if ( pack->checksum == fs_serverPaks[i] ) {
return qtrue; // on the aproved list
}
}
return qfalse; // not on the pure server pak list
}
return qtrue;
}
/*
=================
FS_LoadStack
return load stack
=================
*/
int FS_LoadStack( void ) {
return fs_loadStack;
}
/*
================
return a hash value for the filename
================
*/
static long FS_HashFileName( const char *fname, int hashSize ) {
int i;
long hash;
char letter;
hash = 0;
i = 0;
while ( fname[i] != '\0' ) {
letter = tolower( fname[i] );
if ( letter == '.' ) {
break; // don't include extension
}
if ( letter == '\\' ) {
letter = '/'; // damn path names
}
if ( letter == PATH_SEP ) {
letter = '/'; // damn path names
}
hash += (long)( letter ) * ( i + 119 );
i++;
}
hash = ( hash ^ ( hash >> 10 ) ^ ( hash >> 20 ) );
hash &= ( hashSize - 1 );
return hash;
}
static fileHandle_t FS_HandleForFile( void ) {
int i;
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o == NULL ) {
return i;
}
}
Com_Error( ERR_DROP, "FS_HandleForFile: none free" );
return 0;
}
static FILE *FS_FileForHandle( fileHandle_t f ) {
if ( f < 1 || f >= MAX_FILE_HANDLES ) {
Com_Error( ERR_DROP, "FS_FileForHandle: out of range" );
}
if ( fsh[f].zipFile == qtrue ) {
Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" );
}
if ( !fsh[f].handleFiles.file.o ) {
Com_Error( ERR_DROP, "FS_FileForHandle: NULL" );
}
return fsh[f].handleFiles.file.o;
}
void FS_ForceFlush( fileHandle_t f ) {
FILE *file;
file = FS_FileForHandle( f );
setvbuf( file, NULL, _IONBF, 0 );
}
/*
================
FS_fplength
================
*/
long FS_fplength(FILE *h)
{
long pos;
long end;
pos = ftell(h);
fseek(h, 0, SEEK_END);
end = ftell(h);
fseek(h, pos, SEEK_SET);
return end;
}
/*
================
FS_filelength
If this is called on a non-unique FILE (from a pak file),
it will return the size of the pak file, not the expected
size of the file.
================
*/
long FS_filelength(fileHandle_t f)
{
FILE *h;
h = FS_FileForHandle( f );
if(h == NULL)
return -1;
else
return FS_fplength(h);
}
/*
====================
FS_ReplaceSeparators
Fix things up differently for win/unix/mac
====================
*/
static void FS_ReplaceSeparators( char *path ) {
char *s;
qboolean lastCharWasSep = qfalse;
for ( s = path ; *s ; s++ ) {
if ( *s == '/' || *s == '\\' ) {
if ( !lastCharWasSep ) {
*s = PATH_SEP;
lastCharWasSep = qtrue;
} else {
memmove (s, s + 1, strlen (s));
}
} else {
lastCharWasSep = qfalse;
}
}
}
/*
===================
FS_BuildOSPath
Qpath may have either forward or backwards slashes
===================
*/
char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) {
char temp[MAX_OSPATH];
static char ospath[2][MAX_OSPATH];
static int toggle;
toggle ^= 1; // flip-flop to allow two returns without clash
if ( !game || !game[0] ) {
game = fs_gamedir;
}
Com_sprintf( temp, sizeof( temp ), "/%s/%s", game, qpath );
FS_ReplaceSeparators( temp );
Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp );
return ospath[toggle];
}
/*
============
FS_CreatePath
Creates any directories needed to store the given filename
============
*/
qboolean FS_CreatePath (char *OSPath) {
char *ofs;
char path[MAX_OSPATH];
// make absolutely sure that it can't back up the path
// FIXME: is c: allowed???
if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) {
Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath );
return qtrue;
}
Q_strncpyz( path, OSPath, sizeof( path ) );
FS_ReplaceSeparators( path );
// Skip creation of the root directory as it will always be there
ofs = strchr( path, PATH_SEP );
if ( ofs != NULL ) {
ofs++;
}
for (; ofs != NULL && *ofs ; ofs++) {
if (*ofs == PATH_SEP) {
// create the directory
*ofs = 0;
if (!Sys_Mkdir (path)) {
Com_Error( ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"",
path );
}
*ofs = PATH_SEP;
}
}
return qfalse;
}
/*
=================
FS_CopyFile
Copy a fully specified file from one place to another
=================
*/
static void FS_CopyFile( char *fromOSPath, char *toOSPath ) {
FILE *f;
int len;
byte *buf;
//Com_Printf( "copy %s to %s\n", fromOSPath, toOSPath );
if ( strstr( fromOSPath, "journal.dat" ) || strstr( fromOSPath, "journaldata.dat" ) ) {
Com_Printf( "Ignoring journal files\n" );
return;
}
f = Sys_FOpen( fromOSPath, "rb" );
if ( !f ) {
return;
}
fseek( f, 0, SEEK_END );
len = ftell( f );
fseek( f, 0, SEEK_SET );
// we are using direct malloc instead of Z_Malloc here, so it
// probably won't work on a mac... Its only for developers anyway...
buf = malloc( len );
if ( fread( buf, 1, len, f ) != len ) {
Com_Error( ERR_FATAL, "Short read in FS_Copyfiles()\n" );
}
fclose( f );
if ( FS_CreatePath( toOSPath ) ) {
free( buf );
return;
}
f = Sys_FOpen( toOSPath, "wb" );
if ( !f ) {
free( buf );
return;
}
if ( fwrite( buf, 1, len, f ) != len ) {
Com_Error( ERR_FATAL, "Short write in FS_Copyfiles()\n" );
}
fclose( f );
free( buf );
}
void FS_CopyFileOS( char *from, char *to ) {
FILE *f;
int len;
byte *buf;
char *fromOSPath, *toOSPath;
fromOSPath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from );
toOSPath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to );
//Com_Printf( "copy %s to %s\n", fromOSPath, toOSPath );
if ( strstr( fromOSPath, "journal.dat" ) || strstr( fromOSPath, "journaldata.dat" ) ) {
Com_Printf( "Ignoring journal files\n" );
return;
}
f = Sys_FOpen( fromOSPath, "rb" );
if ( !f ) {
return;
}
fseek( f, 0, SEEK_END );
len = ftell( f );
fseek( f, 0, SEEK_SET );
// we are using direct malloc instead of Z_Malloc here, so it
// probably won't work on a mac... Its only for developers anyway...
buf = malloc( len );
if ( fread( buf, 1, len, f ) != len ) {
Com_Error( ERR_FATAL, "Short read in FS_Copyfiles()\n" );
}
fclose( f );
if ( FS_CreatePath( toOSPath ) ) {
free( buf );
return;
}
f = Sys_FOpen( toOSPath, "wb" );
if ( !f ) {
free( buf );
return;
}
if ( fwrite( buf, 1, len, f ) != len ) {
Com_Error( ERR_FATAL, "Short write in FS_Copyfiles()\n" );
}
fclose( f );
free( buf );
}
/*
=================
FS_CheckFilenameIsMutable
ERR_FATAL if trying to maniuplate a file with the platform library, QVM, or pk3 extension
=================
*/
static void FS_CheckFilenameIsMutable( const char *filename,
const char *function )
{
// Check if the filename ends with the library, QVM, or pk3 extension
if(COM_CompareExtension( filename, DLL_EXT )
|| COM_CompareExtension( filename, ".qvm" )
|| COM_CompareExtension( filename, ".pk3" ) )
{
Com_Error( ERR_FATAL, "%s: Not allowed to manipulate '%s' due "
"to %s extension", function, filename, COM_GetExtension( filename ) );
}
}
/*
===========
FS_Remove
===========
*/
void FS_Remove( const char *osPath ) {
FS_CheckFilenameIsMutable( osPath, __func__ );
remove( osPath );
}
/*
===========
FS_HomeRemove
===========
*/
void FS_HomeRemove( const char *homePath ) {
FS_CheckFilenameIsMutable( homePath, __func__ );
remove( FS_BuildOSPath( fs_homepath->string,
fs_gamedir, homePath ) );
}
/*
================
FS_FileInPathExists
Tests if path and file exists
================
*/
qboolean FS_FileInPathExists(const char *testpath)
{
FILE *filep;
filep = Sys_FOpen(testpath, "rb");
if(filep)
{
fclose(filep);
return qtrue;
}
return qfalse;
}
/*
================
FS_FileExists
Tests if the file exists in the current gamedir, this DOES NOT
search the paths. This is to determine if opening a file to write
(which always goes into the current gamedir) will cause any overwrites.
NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards
================
*/
qboolean FS_FileExists(const char *file)
{
return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file));
}
/*
================
FS_SV_FileExists
Tests if the file exists
================
*/
qboolean FS_SV_FileExists( const char *file )
{
char *testpath;
testpath = FS_BuildOSPath( fs_homepath->string, file, "");
testpath[strlen(testpath)-1] = '\0';
return FS_FileInPathExists(testpath);
}
/*
===========
FS_SV_FOpenFileWrite
===========
*/
fileHandle_t FS_SV_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileWrite: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_SV_FOpenFileRead
Search for a file somewhere below the home path then base path
in that order
===========
*/
long FS_SV_FOpenFileRead(const char *filename, fileHandle_t *fp)
{
char *ospath;
fileHandle_t f = 0;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
// S_ClearSoundBuffer();
// search homepath
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
// remove trailing slash
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o)
{
// If fs_homepath == fs_basepath, don't bother
if (Q_stricmp(fs_homepath->string,fs_basepath->string))
{
// search basepath
ospath = FS_BuildOSPath( fs_basepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
#ifndef STANDALONE
// Check fs_steampath too
if (!fsh[f].handleFiles.file.o && fs_steampath->string[0])
{
ospath = FS_BuildOSPath( fs_steampath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_steampath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
#endif
if ( !fsh[f].handleFiles.file.o )
{
f = 0;
}
}
*fp = f;
if (f) {
return FS_filelength(f);
}
return -1;
}
/*
===========
FS_SV_Rename
===========
*/
void FS_SV_Rename( const char *from, const char *to, qboolean safe ) {
char *from_ospath, *to_ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
// don't let sound stutter
// S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, from, "" );
to_ospath = FS_BuildOSPath( fs_homepath->string, to, "" );
from_ospath[strlen( from_ospath ) - 1] = '\0';
to_ospath[strlen( to_ospath ) - 1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath );
}
if ( safe ) {
FS_CheckFilenameIsMutable( to_ospath, __func__ );
}
if ( rename( from_ospath, to_ospath ) ) {
// Failed, try copying it and deleting the original
FS_CopyFile( from_ospath, to_ospath );
FS_Remove( from_ospath );
}
}
/*
===========
FS_Rename
===========
*/
void FS_Rename( const char *from, const char *to ) {
char *from_ospath, *to_ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
// don't let sound stutter
// S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from );
to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to );
if ( fs_debug->integer ) {
Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath );
}
FS_CheckFilenameIsMutable( to_ospath, __func__ );
if ( rename( from_ospath, to_ospath ) ) {
// Failed first attempt, try deleting destination, and renaming again
FS_Remove( to_ospath );
if ( rename( from_ospath, to_ospath ) ) {
// Failed, try copying it and deleting the original
FS_CopyFile( from_ospath, to_ospath );
FS_Remove( from_ospath );
}
}
}
/*
==============
FS_FCloseFile
If the FILE pointer is an open pak file, leave it open.
For some reason, other dll's can't just cal fclose()
on files returned by FS_FOpenFile...
==============
*/
void FS_FCloseFile( fileHandle_t f ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( fsh[f].zipFile == qtrue ) {
unzCloseCurrentFile( fsh[f].handleFiles.file.z );
if ( fsh[f].handleFiles.unique ) {
unzClose( fsh[f].handleFiles.file.z );
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
return;
}
// we didn't find it as a pak, so close it as a unique file
if ( fsh[f].handleFiles.file.o ) {
fclose( fsh[f].handleFiles.file.o );
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
}
/*
===========
FS_FOpenFileWrite
===========
*/
fileHandle_t FS_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileWrite: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if ( FS_CreatePath( ospath ) ) {
return 0;
}
// enabling the following line causes a recursive function call loop
// when running with +set logfile 1 +set developer 1
//Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if ( !fsh[f].handleFiles.file.o ) {
f = 0;
}
return f;
}
/*
===========
FS_FOpenFileAppend
===========
*/
fileHandle_t FS_FOpenFileAppend( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
// S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileAppend: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if ( FS_CreatePath( ospath ) ) {
return 0;
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "ab" );
fsh[f].handleSync = qfalse;
if ( !fsh[f].handleFiles.file.o ) {
f = 0;
}
return f;
}
/*
===========
FS_FCreateOpenPipeFile
===========
*/
fileHandle_t FS_FCreateOpenPipeFile( const char *filename ) {
char *ospath;
FILE *fifo;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
// S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FCreateOpenPipeFile: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
fifo = Sys_Mkfifo( ospath );
if( fifo ) {
fsh[f].handleFiles.file.o = fifo;
fsh[f].handleSync = qfalse;
}
else
{
Com_Printf( S_COLOR_YELLOW "WARNING: Could not create new com_pipefile at %s. "
"com_pipefile will not be used.\n", ospath );
f = 0;
}
return f;
}
/*
===========
FS_FilenameCompare
Ignore case and seprator char distinctions
===========
*/
qboolean FS_FilenameCompare( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if ( Q_islower( c1 ) ) {
c1 -= ( 'a' - 'A' );
}
if ( Q_islower( c2 ) ) {
c2 -= ( 'a' - 'A' );
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if ( c1 != c2 ) {
return qtrue; // strings not equal
}
} while ( c1 );
return qfalse; // strings are equal
}
/*
===========
FS_FileCompare
Do a binary check of the two files, return qfalse if they are different, otherwise qtrue
===========
*/
qboolean FS_FileCompare( const char *s1, const char *s2 ) {
FILE *f1, *f2;
int len1, len2, pos;
byte *b1, *b2, *p1, *p2;
f1 = fopen( s1, "rb" );
if ( !f1 ) {
Com_Error( ERR_FATAL, "FS_FileCompare: %s does not exist\n", s1 );
}
f2 = fopen( s2, "rb" );
if ( !f2 ) { // this file is allowed to not be there, since it might not exist in the previous build
fclose( f1 );
return qfalse;
//Com_Error( ERR_FATAL, "FS_FileCompare: %s does not exist\n", s2 );
}
// first do a length test
pos = ftell( f1 );
fseek( f1, 0, SEEK_END );
len1 = ftell( f1 );
fseek( f1, pos, SEEK_SET );
pos = ftell( f2 );
fseek( f2, 0, SEEK_END );
len2 = ftell( f2 );
fseek( f2, pos, SEEK_SET );
if ( len1 != len2 ) {
fclose( f1 );
fclose( f2 );
return qfalse;
}
// now do a binary compare
b1 = malloc( len1 );
if ( fread( b1, 1, len1, f1 ) != len1 ) {
Com_Error( ERR_FATAL, "Short read in FS_FileCompare()\n" );
}
fclose( f1 );
b2 = malloc( len2 );
if ( fread( b2, 1, len2, f2 ) != len2 ) {
Com_Error( ERR_FATAL, "Short read in FS_FileCompare()\n" );
}
fclose( f2 );
//if (!memcmp(b1, b2, (int)min(len1,len2) )) {
p1 = b1;
p2 = b2;
for ( pos = 0; pos < len1; pos++, p1++, p2++ )
{
if ( *p1 != *p2 ) {
free( b1 );
free( b2 );
return qfalse;
}
}
//}
// they are identical
free( b1 );
free( b2 );
return qtrue;
}
/*
===========
FS_IsExt
Return qtrue if ext matches file extension filename
===========
*/
qboolean FS_IsExt(const char *filename, const char *ext, int namelen)
{
int extlen;
extlen = strlen(ext);
if(extlen > namelen)
return qfalse;
filename += namelen - extlen;
return !Q_stricmp(filename, ext);
}
/*
===========
FS_IsDemoExt
Return qtrue if filename has a demo extension
===========
*/
qboolean FS_IsDemoExt(const char *filename, int namelen)
{
char *ext_test;
int index, protocol;
ext_test = strrchr(filename, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMOEXT, ARRAY_LEN(DEMOEXT) - 1))
{
protocol = atoi(ext_test + ARRAY_LEN(DEMOEXT));
if(protocol == com_protocol->integer)
return qtrue;
#ifdef LEGACY_PROTOCOL
if(protocol == com_legacyprotocol->integer)
return qtrue;
#endif
for(index = 0; demo_protocols[index]; index++)
{
if(demo_protocols[index] == protocol)
return qtrue;
}
}
return qfalse;
}
/*
===========
FS_FOpenFileReadDir
Tries opening file "filename" in searchpath "search"
Returns filesize and an open FILE pointer.
===========
*/
extern qboolean com_fullyInitialized;
long FS_FOpenFileReadDir(const char *filename, searchpath_t *search, fileHandle_t *file, qboolean uniqueFILE, qboolean unpure)
{
long hash;
pack_t *pak;
fileInPack_t *pakFile;
directory_t *dir;
char *netpath;
FILE *filep;
int len;
if(filename == NULL)
Com_Error(ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed");
// qpaths are not supposed to have a leading slash
if(filename[0] == '/' || filename[0] == '\\')
filename++;
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if(strstr(filename, ".." ) || strstr(filename, "::"))
{
if(file == NULL)
return qfalse;
*file = 0;
return -1;
}
// make sure the rtcwkey file is only readable by the iortcw.exe at initialization
// any other time the key should only be accessed in memory using the provided functions
if(com_fullyInitialized && strstr(filename, "rtcwkey"))
{
if(file == NULL)
return qfalse;
*file = 0;
return -1;
}
if(file == NULL)
{
// just wants to see if file is there
// is the element a pak file?
if(search->pack)
{
hash = FS_HashFileName(filename, search->pack->hashSize);
if(search->pack->hashTable[hash])
{
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do
{
// case and separator insensitive comparisons
if(!FS_FilenameCompare(pakFile->name, filename))
{
// found it!
if(pakFile->len)
return pakFile->len;
else
{
// It's not nice, but legacy code depends
// on positive value if file exists no matter
// what size
return 1;
}
}
pakFile = pakFile->next;
} while ( pakFile != NULL );
}
}
else if(search->dir)
{
dir = search->dir;
netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
filep = Sys_FOpen(netpath, "rb");
if(filep)
{
len = FS_fplength(filep);
fclose(filep);
if(len)
return len;
else
return 1;
}
}
return 0;
}
*file = FS_HandleForFile();
fsh[*file].handleFiles.unique = uniqueFILE;
// is the element a pak file?
if(search->pack)
{
hash = FS_HashFileName(filename, search->pack->hashSize);
if(search->pack->hashTable[hash])
{
// disregard if it doesn't match one of the allowed pure pak files
if(!unpure && !FS_PakIsPure(search->pack))
{
*file = 0;
return -1;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do
{
// case and separator insensitive comparisons
if(!FS_FilenameCompare(pakFile->name, filename))
{
// found it!
// mark the pak as having been referenced and mark specifics on cgame and ui
// shaders, txt, arena files by themselves do not count as a reference as
// these are loaded from all pk3s
// from every pk3 file..
len = strlen(filename);
if (!(pak->referenced & FS_GENERAL_REF))
{
if(!FS_IsExt(filename, ".shader", len) &&
!FS_IsExt(filename, ".txt", len) &&
!FS_IsExt(filename, ".cfg", len) &&
!FS_IsExt(filename, ".config", len) &&
!FS_IsExt(filename, ".bot", len) &&
!FS_IsExt(filename, ".arena", len) &&
!FS_IsExt(filename, ".menu", len) &&
!strstr(filename, "levelshots"))
{
pak->referenced |= FS_GENERAL_REF;
}
}
if(strstr(filename, Sys_GetDLLName( "cgame" )))
pak->referenced |= FS_CGAME_REF;
if(strstr(filename, Sys_GetDLLName( "ui" )))
pak->referenced |= FS_UI_REF;
if(strstr(filename, "cgame.sp.qvm"))
pak->referenced |= FS_CGAME_REF;
if(strstr(filename, "ui.sp.qvm"))
pak->referenced |= FS_UI_REF;
if(uniqueFILE)
{
// open a new file on the pakfile
fsh[*file].handleFiles.file.z = unzOpen(pak->pakFilename);
if(fsh[*file].handleFiles.file.z == NULL)
Com_Error(ERR_FATAL, "Couldn't open %s", pak->pakFilename);
}
else
fsh[*file].handleFiles.file.z = pak->handle;
Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
fsh[*file].zipFile = qtrue;
// set the file position in the zip file (also sets the current file info)
unzSetOffset(fsh[*file].handleFiles.file.z, pakFile->pos);
// open the file in the zip
unzOpenCurrentFile(fsh[*file].handleFiles.file.z);
fsh[*file].zipFilePos = pakFile->pos;
fsh[*file].zipFileLen = pakFile->len;
if(fs_debug->integer)
{
Com_Printf("FS_FOpenFileRead: %s (found in '%s')\n",
filename, pak->pakFilename);
}
return pakFile->len;
}
pakFile = pakFile->next;
} while ( pakFile != NULL );
}
}
else if(search->dir)
{
// check a file in the directory tree
// if we are running restricted, the only files we
// will allow to come from the directory are .cfg files
len = strlen(filename);
// FIXME TTimo I'm not sure about the fs_numServerPaks test
// if you are using FS_ReadFile to find out if a file exists,
// this test can make the search fail although the file is in the directory
// I had the problem on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8
// turned out I used FS_FileExists instead
if(!unpure && fs_numServerPaks)
{
if(!FS_IsExt(filename, ".cfg", len) && // for config files
// !FS_IsExt(filename, ".menu", len) && // menu files
!FS_IsExt(filename, ".svg", len) && // savegames
!FS_IsExt(filename, ".game", len) && // menu files
!FS_IsExt(filename, ".dat", len) && // for journal files
!FS_IsDemoExt(filename, len)) // demos
{
*file = 0;
return -1;
}
}
dir = search->dir;
netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
filep = Sys_FOpen(netpath, "rb");
if (filep == NULL)
{
*file = 0;
return -1;
}
Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
fsh[*file].zipFile = qfalse;
if(fs_debug->integer)
{
Com_Printf("FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename,
dir->path, PATH_SEP, dir->gamedir);
}
fsh[*file].handleFiles.file.o = filep;
return FS_fplength(filep);
}
*file = 0;
return -1;
}
/*
===========
FS_FOpenFileRead
Finds the file in the search path.
Returns filesize and an open FILE pointer.
Used for streaming data out of either a
separate file or a ZIP file.
===========
*/
long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE)
{
searchpath_t *search;
long len;
qboolean isLocalConfig;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
isLocalConfig = !strcmp(filename, "autoexec.cfg") || !strcmp(filename, Q3CONFIG_CFG);
for(search = fs_searchpaths; search; search = search->next)
{
// autoexec.cfg and wolfconfig.cfg can only be loaded outside of pk3 files.
if (isLocalConfig && search->pack)
continue;
len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse);
if(file == NULL)
{
if(len > 0)
return len;
}
else
{
if(len >= 0 && *file)
return len;
}
}
#ifdef FS_MISSING
if(missingFiles)
fprintf(missingFiles, "%s\n", filename);
#endif
if(file)
{
*file = 0;
return -1;
}
else
{
// When file is NULL, we're querying the existance of the file
// If we've got here, it doesn't exist
return 0;
}
}
/*
=================
FS_FindVM
Find a suitable VM file in search path order.
In each searchpath try:
- open DLL file if DLL loading enabled
- open QVM file
Enable search for DLL by setting enableDll to FSVM_ENABLEDLL
write found DLL or QVM to "found" and return VMI_NATIVE if DLL, VMI_COMPILED if QVM
Return the searchpath in "startSearch".
=================
*/
int FS_FindVM(void **startSearch, char *found, int foundlen, const char *name, int enableDll)
{
searchpath_t *search, *lastSearch;
directory_t *dir;
pack_t *pack;
char dllName[MAX_OSPATH], qvmName[MAX_OSPATH];
char *netpath;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
if(enableDll)
Q_strncpyz(dllName, Sys_GetDLLName(name), sizeof(dllName));
Com_sprintf(qvmName, sizeof(qvmName), "vm/%s.sp.qvm", name);
lastSearch = *startSearch;
if(*startSearch == NULL)
search = fs_searchpaths;
else
search = lastSearch->next;
while(search)
{
if(search->dir && !fs_numServerPaks)
{
dir = search->dir;
if(enableDll)
{
netpath = FS_BuildOSPath(dir->path, dir->gamedir, dllName);
if(FS_FileInPathExists(netpath))
{
Q_strncpyz(found, netpath, foundlen);
*startSearch = search;
return VMI_NATIVE;
}
}
if(FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, qfalse) > 0)
{
*startSearch = search;
return VMI_COMPILED;
}
}
else if(search->pack)
{
pack = search->pack;
if(lastSearch && lastSearch->pack)
{
// make sure we only try loading one VM file per game dir
// i.e. if VM from pak7.pk3 fails we won't try one from pak6.pk3
if(!FS_FilenameCompare(lastSearch->pack->pakPathname, pack->pakPathname))
{
search = search->next;
continue;
}
}
if(FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, qfalse) > 0)
{
*startSearch = search;
return VMI_COMPILED;
}
}
search = search->next;
}
return -1;
}
/*
==============
FS_Delete
TTimo - this was not in the 1.30 filesystem code
using fs_homepath for the file to remove
==============
*/
int FS_Delete( char *filename ) {
char *ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !filename || filename[0] == 0 ) {
return 0;
}
// for safety, only allow deletion from the save directory
if ( Q_strncmp( filename, "save/", 5 ) != 0 ) {
return 0;
}
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( remove( ospath ) != -1 ) { // success
return 1;
}
return 0;
}
/*
=================
FS_Read2
Properly handles partial reads
=================
*/
int FS_Read2( void *buffer, int len, fileHandle_t f ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !f ) {
return 0;
}
if ( fsh[f].streamed ) {
int r;
fsh[f].streamed = qfalse;
r = FS_Read( buffer, len, f );
fsh[f].streamed = qtrue;
return r;
} else {
return FS_Read( buffer, len, f );
}
}
int FS_Read( void *buffer, int len, fileHandle_t f ) {
int block, remaining;
int read;
byte *buf;
int tries;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !f ) {
return 0;
}
buf = (byte *)buffer;
fs_readCount += len;
if ( fsh[f].zipFile == qfalse ) {
remaining = len;
tries = 0;
while ( remaining ) {
block = remaining;
read = fread( buf, 1, block, fsh[f].handleFiles.file.o );
if ( read == 0 ) {
// we might have been trying to read from a CD, which
// sometimes returns a 0 read on windows
if ( !tries ) {
tries = 1;
} else {
return len - remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read");
}
}
if ( read == -1 ) {
Com_Error( ERR_FATAL, "FS_Read: -1 bytes read" );
}
remaining -= read;
buf += read;
}
return len;
} else {
return unzReadCurrentFile( fsh[f].handleFiles.file.z, buffer, len );
}
}
/*
=================
FS_Write
Properly handles partial writes
=================
*/
int FS_Write( const void *buffer, int len, fileHandle_t h ) {
int block, remaining;
int written;
byte *buf;
int tries;
FILE *f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !h ) {
return 0;
}
f = FS_FileForHandle( h );
buf = (byte *)buffer;
remaining = len;
tries = 0;
while ( remaining ) {
block = remaining;
written = fwrite( buf, 1, block, f );
if ( written == 0 ) {
if ( !tries ) {
tries = 1;
} else {
Com_Printf( "FS_Write: 0 bytes written\n" );
return 0;
}
}
if ( written == -1 ) {
Com_Printf( "FS_Write: -1 bytes written\n" );
return 0;
}
remaining -= written;
buf += written;
}
if ( fsh[h].handleSync ) {
fflush( f );
}
return len;
}
#define MAXPRINTMSG 4096
void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof( msg ), fmt, argptr );
va_end( argptr );
FS_Write( msg, strlen( msg ), h );
}
#define PK3_SEEK_BUFFER_SIZE 65536
/*
=================
FS_Seek
=================
*/
int FS_Seek( fileHandle_t f, long offset, int origin ) {
int _origin;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
return -1;
}
if ( fsh[f].streamed ) {
int r;
fsh[f].streamed = qfalse;
r = FS_Seek( f, offset, origin );
fsh[f].streamed = qtrue;
return r;
}
if ( fsh[f].zipFile == qtrue ) {
//FIXME: this is really, really crappy
//(but better than what was here before)
byte buffer[PK3_SEEK_BUFFER_SIZE];
int remainder;
int currentPosition = FS_FTell( f );
// change negative offsets into FS_SEEK_SET
if ( offset < 0 ) {
switch( origin ) {
case FS_SEEK_END:
remainder = fsh[f].zipFileLen + offset;
break;
case FS_SEEK_CUR:
remainder = currentPosition + offset;
break;
case FS_SEEK_SET:
default:
remainder = 0;
break;
}
if ( remainder < 0 ) {
remainder = 0;
}
origin = FS_SEEK_SET;
} else {
if ( origin == FS_SEEK_END ) {
remainder = fsh[f].zipFileLen - currentPosition + offset;
} else {
remainder = offset;
}
}
switch( origin ) {
case FS_SEEK_SET:
if ( remainder == currentPosition ) {
return offset;
}
unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
unzOpenCurrentFile(fsh[f].handleFiles.file.z);
//fallthrough
case FS_SEEK_END:
case FS_SEEK_CUR:
while( remainder > PK3_SEEK_BUFFER_SIZE ) {
FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f );
remainder -= PK3_SEEK_BUFFER_SIZE;
}
FS_Read( buffer, remainder, f );
return offset;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
return -1;
}
} else {
FILE *file;
file = FS_FileForHandle( f );
switch ( origin ) {
case FS_SEEK_CUR:
_origin = SEEK_CUR;
break;
case FS_SEEK_END:
_origin = SEEK_END;
break;
case FS_SEEK_SET:
_origin = SEEK_SET;
break;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
break;
}
return fseek( file, offset, _origin );
}
}
/*
======================================================================================
CONVENIENCE FUNCTIONS FOR ENTIRE FILES
======================================================================================
*/
int FS_FileIsInPAK( const char *filename, int *pChecksum ) {
searchpath_t *search;
pack_t *pak;
fileInPack_t *pakFile;
long hash = 0;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !filename ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed" );
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
return -1;
}
//
// search through the path, one element at a time
//
for ( search = fs_searchpaths ; search ; search = search->next ) {
//
if ( search->pack ) {
hash = FS_HashFileName( filename, search->pack->hashSize );
}
// is the element a pak file?
if ( search->pack && search->pack->hashTable[hash] ) {
// disregard if it doesn't match one of the allowed pure pak files
if ( !FS_PakIsPure( search->pack ) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
if ( pChecksum ) {
*pChecksum = pak->pure_checksum;
}
return 1;
}
pakFile = pakFile->next;
} while ( pakFile != NULL );
}
}
return -1;
}
/*
============
FS_ReadFileDir
Filename are relative to the quake search path
a null buffer will just return the file length without loading
If searchPath is non-NULL search only in that specific search path
============
*/
long FS_ReadFileDir(const char *qpath, void *searchPath, qboolean unpure, void **buffer)
{
fileHandle_t h;
searchpath_t *search;
byte* buf;
qboolean isConfig;
long len;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !qpath || !qpath[0] ) {
Com_Error( ERR_FATAL, "FS_ReadFile with empty name" );
}
buf = NULL; // quiet compiler warning
// if this is a .cfg file and we are playing back a journal, read
// it from the journal file
if ( strstr( qpath, ".cfg" ) ) {
isConfig = qtrue;
if ( com_journal && com_journal->integer == 2 ) {
int r;
Com_DPrintf( "Loading %s from journal file.\n", qpath );
r = FS_Read( &len, sizeof( len ), com_journalDataFile );
if ( r != sizeof( len ) ) {
if ( buffer != NULL ) {
*buffer = NULL;
}
return -1;
}
// if the file didn't exist when the journal was created
if ( !len ) {
if ( buffer == NULL ) {
return 1; // hack for old journal files
}
*buffer = NULL;
return -1;
}
if ( buffer == NULL ) {
return len;
}
buf = Hunk_AllocateTempMemory( len + 1 );
*buffer = buf;
r = FS_Read( buf, len, com_journalDataFile );
if ( r != len ) {
Com_Error( ERR_FATAL, "Read from journalDataFile failed" );
}
fs_loadCount++;
fs_loadStack++;
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
return len;
}
} else {
isConfig = qfalse;
}
search = searchPath;
if(search == NULL)
{
// look for it in the filesystem or pack files
len = FS_FOpenFileRead(qpath, &h, qfalse);
}
else
{
// look for it in a specific search path only
len = FS_FOpenFileReadDir(qpath, search, &h, qfalse, unpure);
}
if ( h == 0 ) {
if ( buffer ) {
*buffer = NULL;
}
// if we are journalling and it is a config file, write a zero to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing zero for %s to journal file.\n", qpath );
len = 0;
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return -1;
}
if ( !buffer ) {
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing len for %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
FS_FCloseFile( h );
return len;
}
fs_loadCount++;
fs_loadStack++;
buf = Hunk_AllocateTempMemory( len + 1 );
*buffer = buf;
FS_Read( buf, len, h );
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
FS_FCloseFile( h );
// if we are journalling and it is a config file, write it to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Write( buf, len, com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return len;
}
/*
============
FS_ReadFile
Filename are relative to the quake search path
a null buffer will just return the file length without loading
============
*/
long FS_ReadFile(const char *qpath, void **buffer)
{
return FS_ReadFileDir(qpath, NULL, qfalse, buffer);
}
/*
=============
FS_FreeFile
=============
*/
void FS_FreeFile( void *buffer ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !buffer ) {
Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" );
}
fs_loadStack--;
Hunk_FreeTempMemory( buffer );
// if all of our temp files are free, clear all of our space
if ( fs_loadStack == 0 ) {
Hunk_ClearTempMemory();
}
}
/*
============
FS_WriteFile
Filename are relative to the quake search path
============
*/
void FS_WriteFile( const char *qpath, const void *buffer, int size ) {
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !qpath || !buffer ) {
Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" );
}
f = FS_FOpenFileWrite( qpath );
if ( !f ) {
Com_Printf( "Failed to open %s\n", qpath );
return;
}
FS_Write( buffer, size, f );
FS_FCloseFile( f );
}
/*
==========================================================================
ZIP FILE LOADING
==========================================================================
*/
/*
=================
FS_LoadZipFile
Creates a new pak_t in the search chain for the contents
of a zip file.
=================
*/
static pack_t *FS_LoadZipFile(const char *zipfile, const char *basename)
{
fileInPack_t *buildBuffer;
pack_t *pack;
unzFile uf;
int err;
unz_global_info gi;
char filename_inzip[MAX_ZPATH];
unz_file_info file_info;
int i, len;
long hash;
int fs_numHeaderLongs;
int *fs_headerLongs;
char *namePtr;
fs_numHeaderLongs = 0;
uf = unzOpen( zipfile );
err = unzGetGlobalInfo( uf,&gi );
if ( err != UNZ_OK ) {
return NULL;
}
fs_packFiles += gi.number_entry;
len = 0;
unzGoToFirstFile( uf );
for ( i = 0; i < gi.number_entry; i++ )
{
err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 );
if ( err != UNZ_OK ) {
break;
}
len += strlen( filename_inzip ) + 1;
unzGoToNextFile( uf );
}
buildBuffer = Z_Malloc( ( gi.number_entry * sizeof( fileInPack_t ) ) + len );
namePtr = ( (char *) buildBuffer ) + gi.number_entry * sizeof( fileInPack_t );
fs_headerLongs = Z_Malloc( ( gi.number_entry + 1 ) * sizeof(int) );
fs_headerLongs[ fs_numHeaderLongs++ ] = LittleLong( fs_checksumFeed );
// get the hash table size from the number of files in the zip
// because lots of custom pk3 files have less than 32 or 64 files
for ( i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1 ) {
if ( i > gi.number_entry ) {
break;
}
}
pack = Z_Malloc( sizeof( pack_t ) + i * sizeof( fileInPack_t * ) );
pack->hashSize = i;
pack->hashTable = ( fileInPack_t ** )( ( (char *) pack ) + sizeof( pack_t ) );
for ( i = 0; i < pack->hashSize; i++ ) {
pack->hashTable[i] = NULL;
}
Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) );
Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) );
// strip .pk3 if needed
if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) {
pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0;
}
pack->handle = uf;
pack->numfiles = gi.number_entry;
unzGoToFirstFile( uf );
for ( i = 0; i < gi.number_entry; i++ )
{
err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 );
if ( err != UNZ_OK ) {
break;
}
if ( file_info.uncompressed_size > 0 ) {
fs_headerLongs[fs_numHeaderLongs++] = LittleLong( file_info.crc );
}
Q_strlwr( filename_inzip );
hash = FS_HashFileName( filename_inzip, pack->hashSize );
buildBuffer[i].name = namePtr;
strcpy( buildBuffer[i].name, filename_inzip );
namePtr += strlen( filename_inzip ) + 1;
// store the file position in the zip
buildBuffer[i].pos = unzGetOffset(uf);
buildBuffer[i].len = file_info.uncompressed_size;
buildBuffer[i].next = pack->hashTable[hash];
pack->hashTable[hash] = &buildBuffer[i];
unzGoToNextFile( uf );
}
pack->checksum = Com_BlockChecksum( &fs_headerLongs[ 1 ], sizeof(*fs_headerLongs) * ( fs_numHeaderLongs - 1 ) );
pack->pure_checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs );
pack->checksum = LittleLong( pack->checksum );
pack->pure_checksum = LittleLong( pack->pure_checksum );
Z_Free( fs_headerLongs );
pack->buildBuffer = buildBuffer;
return pack;
}
/*
=================
FS_FreePak
Frees a pak structure and releases all associated resources
=================
*/
static void FS_FreePak(pack_t *thepak)
{
unzClose(thepak->handle);
Z_Free(thepak->buildBuffer);
Z_Free(thepak);
}
/*
=================
FS_GetZipChecksum
Compares whether the given pak file matches a referenced checksum
=================
*/
qboolean FS_CompareZipChecksum(const char *zipfile)
{
pack_t *thepak;
int index, checksum;
thepak = FS_LoadZipFile(zipfile, "");
if(!thepak)
return qfalse;
checksum = thepak->checksum;
FS_FreePak(thepak);
for(index = 0; index < fs_numServerReferencedPaks; index++)
{
if(checksum == fs_serverReferencedPaks[index])
return qtrue;
}
return qfalse;
}
/*
=================================================================================
DIRECTORY SCANNING FUNCTIONS
=================================================================================
*/
#define MAX_FOUND_FILES 0x1000
static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) {
int len, at, newdep;
newdep = 0;
zpath[0] = 0;
len = 0;
at = 0;
while ( zname[at] != 0 )
{
if ( zname[at] == '/' || zname[at] == '\\' ) {
len = at;
newdep++;
}
at++;
}
strcpy( zpath, zname );
zpath[len] = 0;
*depth = newdep;
return len;
}
/*
==================
FS_AddFileToList
==================
*/
static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) {
int i;
if ( nfiles == MAX_FOUND_FILES - 1 ) {
return nfiles;
}
for ( i = 0 ; i < nfiles ; i++ ) {
if ( !Q_stricmp( name, list[i] ) ) {
return nfiles; // allready in list
}
}
list[nfiles] = CopyString( name );
nfiles++;
return nfiles;
}
/*
===============
FS_ListFilteredFiles
Returns a uniqued list of files that match the given criteria
from all search paths
===============
*/
char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles, qboolean allowNonPureFilesOnDisk ) {
int nfiles;
char **listCopy;
char *list[MAX_FOUND_FILES];
searchpath_t *search;
int i;
int pathLength;
int extensionLength;
int length, pathDepth, temp;
pack_t *pak;
fileInPack_t *buildBuffer;
char zpath[MAX_ZPATH];
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !path ) {
*numfiles = 0;
return NULL;
}
if ( !extension ) {
extension = "";
}
pathLength = strlen( path );
if ( path[pathLength - 1] == '\\' || path[pathLength - 1] == '/' ) {
pathLength--;
}
extensionLength = strlen( extension );
nfiles = 0;
FS_ReturnPath( path, zpath, &pathDepth );
//
// search through the path, one element at a time, adding to list
//
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
//ZOID: If we are pure, don't search for files on paks that
// aren't on the pure list
if ( !FS_PakIsPure( search->pack ) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
buildBuffer = pak->buildBuffer;
for ( i = 0; i < pak->numfiles; i++ ) {
char *name;
int zpathLen, depth;
// check for directory match
name = buildBuffer[i].name;
//
if ( filter ) {
// case insensitive
if ( !Com_FilterPath( filter, name, qfalse ) ) {
continue;
}
// unique the match
nfiles = FS_AddFileToList( name, list, nfiles );
} else {
zpathLen = FS_ReturnPath( name, zpath, &depth );
if ( ( depth - pathDepth ) > 2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) {
continue;
}
// check for extension match
length = strlen( name );
if ( length < extensionLength ) {
continue;
}
if ( Q_stricmp( name + length - extensionLength, extension ) ) {
continue;
}
// unique the match
temp = pathLength;
if ( pathLength ) {
temp++; // include the '/'
}
nfiles = FS_AddFileToList( name + temp, list, nfiles );
}
}
} else if ( search->dir ) { // scan for files in the filesystem
char *netpath;
int numSysFiles;
char **sysFiles;
char *name;
// don't scan directories for files if we are pure or restricted
// allow listing of savegames for the demo menus
if ( fs_numServerPaks && !allowNonPureFilesOnDisk && Q_stricmp( extension, "svg" ) ) {
continue;
} else {
netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path );
sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse );
for ( i = 0 ; i < numSysFiles ; i++ ) {
// unique the match
name = sysFiles[i];
nfiles = FS_AddFileToList( name, list, nfiles );
}
Sys_FreeFileList( sysFiles );
}
}
}
// return a copy of the list
*numfiles = nfiles;
if ( !nfiles ) {
return NULL;
}
listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
for ( i = 0 ; i < nfiles ; i++ ) {
listCopy[i] = list[i];
}
listCopy[i] = NULL;
return listCopy;
}
/*
=================
FS_ListFiles
=================
*/
char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) {
return FS_ListFilteredFiles( path, extension, NULL, numfiles, qfalse );
}
/*
=================
FS_FreeFileList
=================
*/
void FS_FreeFileList( char **list ) {
int i;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !list ) {
return;
}
for ( i = 0 ; list[i] ; i++ ) {
Z_Free( list[i] );
}
Z_Free( list );
}
/*
================
FS_GetFileList
================
*/
int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
int nFiles, i, nTotal, nLen;
char **pFiles = NULL;
*listbuf = 0;
nFiles = 0;
nTotal = 0;
if ( Q_stricmp( path, "$modlist" ) == 0 ) {
return FS_GetModList( listbuf, bufsize );
}
pFiles = FS_ListFiles( path, extension, &nFiles );
for ( i = 0; i < nFiles; i++ ) {
nLen = strlen( pFiles[i] ) + 1;
if ( nTotal + nLen + 1 < bufsize ) {
strcpy( listbuf, pFiles[i] );
listbuf += nLen;
nTotal += nLen;
} else {
nFiles = i;
break;
}
}
FS_FreeFileList( pFiles );
return nFiles;
}
/*
=======================
Sys_ConcatenateFileLists
mkv: Naive implementation. Concatenates three lists into a
new list, and frees the old lists from the heap.
bk001129 - from cvs1.17 (mkv)
FIXME TTimo those two should move to common.c next to Sys_ListFiles
=======================
*/
static unsigned int Sys_CountFileList( char **list ) {
int i = 0;
if (list)
{
while (*list)
{
list++;
i++;
}
}
return i;
}
static char** Sys_ConcatenateFileLists( char **list0, char **list1 )
{
int totalLength = 0;
char** cat = NULL, **dst, **src;
totalLength += Sys_CountFileList(list0);
totalLength += Sys_CountFileList(list1);
/* Create new list. */
dst = cat = Z_Malloc( ( totalLength + 1 ) * sizeof( char* ) );
/* Copy over lists. */
if (list0)
{
for (src = list0; *src; src++, dst++)
*dst = *src;
}
if (list1)
{
for (src = list1; *src; src++, dst++)
*dst = *src;
}
// Terminate the list
*dst = NULL;
// Free our old lists.
// NOTE: not freeing their content, it's been merged in dst and still being used
if (list0) Z_Free( list0 );
if (list1) Z_Free( list1 );
return cat;
}
/*
================
FS_GetModDescription
================
*/
void FS_GetModDescription( const char *modDir, char *description, int descriptionLen ) {
fileHandle_t descHandle;
char descPath[MAX_QPATH];
int nDescLen;
FILE *file;
Com_sprintf( descPath, sizeof ( descPath ), "%s/description.txt", modDir );
nDescLen = FS_SV_FOpenFileRead( descPath, &descHandle );
if ( nDescLen > 0 && descHandle ) {
file = FS_FileForHandle(descHandle);
Com_Memset( description, 0, descriptionLen );
nDescLen = fread(description, 1, descriptionLen, file);
if (nDescLen >= 0) {
description[nDescLen] = '\0';
}
FS_FCloseFile(descHandle);
} else {
Q_strncpyz( description, modDir, descriptionLen );
}
}
/*
================
FS_GetModList
Returns a list of mod directory names
A mod directory is a peer to baseq3 with a pk3 in it
The directories are searched in base path, cd path and home path
================
*/
int FS_GetModList( char *listbuf, int bufsize ) {
int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen;
char **pFiles = NULL;
char **pPaks = NULL;
char *name, *path;
char description[MAX_OSPATH];
int dummy;
char **pFiles0 = NULL;
char **pFiles1 = NULL;
#ifndef STANDALONE
char **pFiles2 = NULL;
char **pFiles3 = NULL;
#endif
qboolean bDrop = qfalse;
*listbuf = 0;
nMods = nTotal = 0;
pFiles0 = Sys_ListFiles( fs_homepath->string, NULL, NULL, &dummy, qtrue );
pFiles1 = Sys_ListFiles( fs_basepath->string, NULL, NULL, &dummy, qtrue );
#ifndef STANDALONE
pFiles2 = Sys_ListFiles( fs_steampath->string, NULL, NULL, &dummy, qtrue );
#endif
// we searched for mods in the three paths
// it is likely that we have duplicate names now, which we will cleanup below
#ifndef STANDALONE
pFiles3 = Sys_ConcatenateFileLists( pFiles0, pFiles1 );
pFiles = Sys_ConcatenateFileLists( pFiles2, pFiles3 );
#else
pFiles = Sys_ConcatenateFileLists( pFiles0, pFiles1 );
#endif
nPotential = Sys_CountFileList(pFiles);
for ( i = 0 ; i < nPotential ; i++ ) {
name = pFiles[i];
// NOTE: cleaner would involve more changes
// ignore duplicate mod directories
if (i!=0) {
bDrop = qfalse;
for(j=0; j<i; j++)
{
if (Q_stricmp(pFiles[j],name)==0) {
// this one can be dropped
bDrop = qtrue;
break;
}
}
}
if (bDrop) {
continue;
}
// we drop "baseq3" "." and ".."
if (Q_stricmp(name, com_basegame->string) && Q_stricmpn(name, ".", 1)) {
// now we need to find some .pk3 files to validate the mod
// NOTE TTimo: (actually I'm not sure why .. what if it's a mod under developement with no .pk3?)
// we didn't keep the information when we merged the directory names, as to what OS Path it was found under
// so it could be in base path, cd path or home path
// we will try each three of them here (yes, it's a bit messy)
path = FS_BuildOSPath( fs_basepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse);
Sys_FreeFileList( pPaks ); // we only use Sys_ListFiles to check wether .pk3 files are present
/* try on home path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_homepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
#ifndef STANDALONE
/* try on steam path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_steampath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
#endif
if (nPaks > 0) {
nLen = strlen(name) + 1;
// nLen is the length of the mod path
// we need to see if there is a description available
FS_GetModDescription( name, description, sizeof( description ) );
nDescLen = strlen(description) + 1;
if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) {
strcpy(listbuf, name);
listbuf += nLen;
strcpy(listbuf, description);
listbuf += nDescLen;
nTotal += nLen + nDescLen;
nMods++;
}
else {
break;
}
}
}
}
Sys_FreeFileList( pFiles );
return nMods;
}
//============================================================================
/*
================
FS_Dir_f
================
*/
void FS_Dir_f( void ) {
char *path;
char *extension;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) {
Com_Printf( "usage: dir <directory> [extension]\n" );
return;
}
if ( Cmd_Argc() == 2 ) {
path = Cmd_Argv( 1 );
extension = "";
} else {
path = Cmd_Argv( 1 );
extension = Cmd_Argv( 2 );
}
Com_Printf( "Directory of %s %s\n", path, extension );
Com_Printf( "---------------\n" );
dirnames = FS_ListFiles( path, extension, &ndirs );
for ( i = 0; i < ndirs; i++ ) {
Com_Printf( "%s\n", dirnames[i] );
}
FS_FreeFileList( dirnames );
}
/*
===========
FS_ConvertPath
===========
*/
void FS_ConvertPath( char *s ) {
while ( *s ) {
if ( *s == '\\' || *s == ':' ) {
*s = '/';
}
s++;
}
}
/*
===========
FS_PathCmp
Ignore case and seprator char distinctions
===========
*/
int FS_PathCmp( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if ( Q_islower( c1 ) ) {
c1 -= ( 'a' - 'A' );
}
if ( Q_islower( c2 ) ) {
c2 -= ( 'a' - 'A' );
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if ( c1 < c2 ) {
return -1; // strings not equal
}
if ( c1 > c2 ) {
return 1;
}
} while ( c1 );
return 0; // strings are equal
}
/*
================
FS_SortFileList
================
*/
void FS_SortFileList( char **filelist, int numfiles ) {
int i, j, k, numsortedfiles;
char **sortedlist;
sortedlist = Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ) );
sortedlist[0] = NULL;
numsortedfiles = 0;
for ( i = 0; i < numfiles; i++ ) {
for ( j = 0; j < numsortedfiles; j++ ) {
if ( FS_PathCmp( filelist[i], sortedlist[j] ) < 0 ) {
break;
}
}
for ( k = numsortedfiles; k > j; k-- ) {
sortedlist[k] = sortedlist[k - 1];
}
sortedlist[j] = filelist[i];
numsortedfiles++;
}
Com_Memcpy( filelist, sortedlist, numfiles * sizeof( *filelist ) );
Z_Free( sortedlist );
}
/*
================
FS_NewDir_f
================
*/
void FS_NewDir_f( void ) {
char *filter;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 ) {
Com_Printf( "usage: fdir <filter>\n" );
Com_Printf( "example: fdir *q3dm*.bsp\n" );
return;
}
filter = Cmd_Argv( 1 );
Com_Printf( "---------------\n" );
dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs, qfalse );
FS_SortFileList( dirnames, ndirs );
for ( i = 0; i < ndirs; i++ ) {
FS_ConvertPath( dirnames[i] );
Com_Printf( "%s\n", dirnames[i] );
}
Com_Printf( "%d files listed\n", ndirs );
FS_FreeFileList( dirnames );
}
/*
============
FS_Path_f
============
*/
void FS_Path_f( void ) {
searchpath_t *s;
int i;
Com_Printf( "Current search path:\n" );
for ( s = fs_searchpaths; s; s = s->next ) {
if ( s->pack ) {
Com_Printf( "%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles );
if ( fs_numServerPaks ) {
if ( !FS_PakIsPure( s->pack ) ) {
Com_Printf( " not on the pure list\n" );
} else {
Com_Printf( " on the pure list\n" );
}
}
} else {
Com_Printf ("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir );
}
}
Com_Printf( "\n" );
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o ) {
Com_Printf( "handle %i: %s\n", i, fsh[i].name );
}
}
}
/*
============
FS_TouchFile_f
============
*/
void FS_TouchFile_f( void ) {
fileHandle_t f;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: touchFile <file>\n" );
return;
}
FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse );
if ( f ) {
FS_FCloseFile( f );
}
}
/*
============
FS_Which
============
*/
qboolean FS_Which(const char *filename, void *searchPath)
{
searchpath_t *search = searchPath;
if(FS_FOpenFileReadDir(filename, search, NULL, qfalse, qfalse) > 0)
{
if(search->pack)
{
Com_Printf("File \"%s\" found in \"%s\"\n", filename, search->pack->pakFilename);
return qtrue;
}
else if(search->dir)
{
Com_Printf( "File \"%s\" found at \"%s\"\n", filename, search->dir->fullpath);
return qtrue;
}
}
return qfalse;
}
/*
============
FS_Which_f
============
*/
void FS_Which_f( void ) {
searchpath_t *search;
char *filename;
filename = Cmd_Argv(1);
if ( !filename[0] ) {
Com_Printf( "Usage: which <file>\n" );
return;
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// just wants to see if file is there
for(search = fs_searchpaths; search; search = search->next)
{
if(FS_Which(filename, search))
return;
}
Com_Printf("File not found: \"%s\"\n", filename);
}
//===========================================================================
static int QDECL paksort( const void *a, const void *b ) {
char *aa, *bb;
aa = *(char **)a;
bb = *(char **)b;
return FS_PathCmp( aa, bb );
}
/*
================
FS_AddGameDirectory
Sets fs_gamedir, adds the directory to the head of the path,
then loads the zip headers
================
*/
#define MAX_PAKFILES 1024
void FS_AddGameDirectory( const char *path, const char *dir ) {
searchpath_t *sp;
int i;
searchpath_t *search;
pack_t *pak;
char *pakfile;
int numfiles;
char **pakfiles;
char *sorted[MAX_PAKFILES];
// this fixes the case where fs_basepath is the same as fs_cdpath
// which happens on full installs
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->dir && !Q_stricmp( sp->dir->path, path ) && !Q_stricmp( sp->dir->gamedir, dir ) ) {
return; // we've already got this one
}
}
Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) );
//
// add the directory to the search path
//
search = Z_Malloc( sizeof( searchpath_t ) );
search->dir = Z_Malloc( sizeof( *search->dir ) );
Q_strncpyz( search->dir->path, path, sizeof( search->dir->path ) );
Q_strncpyz( search->dir->gamedir, dir, sizeof( search->dir->gamedir ) );
search->next = fs_searchpaths;
fs_searchpaths = search;
// find all pak files in this directory
pakfile = FS_BuildOSPath( path, dir, "" );
pakfile[ strlen( pakfile ) - 1 ] = 0; // strip the trailing slash
pakfiles = Sys_ListFiles( pakfile, ".pk3", NULL, &numfiles, qfalse );
// sort them so that later alphabetic matches override
// earlier ones. This makes pak1.pk3 override pak0.pk3
if ( numfiles > MAX_PAKFILES ) {
numfiles = MAX_PAKFILES;
}
for ( i = 0 ; i < numfiles ; i++ ) {
sorted[i] = pakfiles[i];
// JPW NERVE sp_* to _p_* so "sp_pak*" gets alphabetically sorted before "pak*"
//----(SA) SP mod
// (SA) sort order to be further clarified later (10/8/01)
if ( !Q_strncmp( sorted[i],"sp_",3 ) ) { // sort sp first
memcpy( sorted[i],"zz",2 );
}
}
qsort( sorted, numfiles, sizeof(char *), paksort );
for ( i = 0 ; i < numfiles ; i++ ) {
if ( Q_strncmp( sorted[i],"mp_",3 ) ) { // (SA) SP mod -- exclude mp_*
// JPW NERVE KLUDGE: fix filenames broken in mp/sp/pak sort above
//----(SA) mod for SP
if ( !Q_strncmp( sorted[i],"zz_",3 ) ) {
memcpy( sorted[i],"sp",2 );
}
// jpw
pakfile = FS_BuildOSPath( path, dir, sorted[i] );
if ( ( pak = FS_LoadZipFile( pakfile, sorted[i] ) ) == 0 ) {
continue;
}
// store the game name for downloading
strcpy( pak->pakGamename, dir );
search = Z_Malloc( sizeof( searchpath_t ) );
search->pack = pak;
search->next = fs_searchpaths;
fs_searchpaths = search;
}
}
// done
Sys_FreeFileList( pakfiles );
}
/*
================
FS_idPak
================
*/
qboolean FS_idPak(char *pak, char *base, int numPaks)
{
int i;
for ( i = 0; i < NUM_ID_PAKS; i++ ) {
if ( !FS_FilenameCompare( pak, va( "%s/pak%d", base, i ) ) ) {
break;
}
// JPW NERVE -- this fn prevents external sources from downloading/overwriting official files, so exclude both SP and MP files from this list as well
if ( !FS_FilenameCompare( pak, va( "%s/mp_pak%d",base,i ) ) ) {
break;
}
if ( !FS_FilenameCompare( pak, va( "%s/sp_pak%d",base,i + 1) ) ) {
break;
}
// jpw
}
if ( i < numPaks ) {
return qtrue;
}
return qfalse;
}
/*
================
FS_CheckDirTraversal
Check whether the string contains stuff like "../" to prevent directory traversal bugs
and return qtrue if it does.
================
*/
qboolean FS_CheckDirTraversal(const char *checkdir)
{
if(strstr(checkdir, "../") || strstr(checkdir, "..\\"))
return qtrue;
return qfalse;
}
/*
================
FS_ComparePaks
----------------
dlstring == qtrue
Returns a list of pak files that we should download from the server. They all get stored
in the current gamedir and an FS_Restart will be fired up after we download them all.
The string is the format:
@remotename@localname [repeat]
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS];
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS];
----------------
dlstring == qfalse
we are not interested in a download string format, we want something human-readable
(this is used for diagnostics while connecting to a pure server)
================
*/
qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring ) {
searchpath_t *sp;
qboolean havepak;
char *origpos = neededpaks;
int i;
if ( !fs_numServerReferencedPaks )
return qfalse; // Server didn't send any pack information along
*neededpaks = 0;
for ( i = 0 ; i < fs_numServerReferencedPaks ; i++ )
{
// Ok, see if we have this pak file
havepak = qfalse;
// never autodownload any of the id paks
if(FS_idPak(fs_serverReferencedPakNames[i], BASEGAME, NUM_ID_PAKS))
{
continue;
}
// Make sure the server cannot make us write to non-quake3 directories.
if(FS_CheckDirTraversal(fs_serverReferencedPakNames[i]))
{
Com_Printf("WARNING: Invalid download name %s\n", fs_serverReferencedPakNames[i]);
continue;
}
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i] ) {
havepak = qtrue; // This is it!
break;
}
}
if ( !havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i] ) {
// Don't got it
if (dlstring)
{
// We need this to make sure we won't hit the end of the buffer or the server could
// overwrite non-pk3 files on clients by writing so much crap into neededpaks that
// Q_strcat cuts off the .pk3 extension.
origpos += strlen(origpos);
// Remote name
Q_strcat( neededpaks, len, "@");
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Local name
Q_strcat( neededpaks, len, "@");
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
{
char st[MAX_ZPATH];
// We already have one called this, we need to download it to another name
// Make something up with the checksum in it
Com_sprintf( st, sizeof( st ), "%s.%08x.pk3", fs_serverReferencedPakNames[i], fs_serverReferencedPaks[i] );
Q_strcat( neededpaks, len, st );
}
else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
}
// Find out whether it might have overflowed the buffer and don't add this file to the
// list if that is the case.
if(strlen(origpos) + (origpos - neededpaks) >= len - 1)
{
*origpos = '\0';
break;
}
}
else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
{
Q_strcat( neededpaks, len, " (local file exists with wrong checksum)");
}
Q_strcat( neededpaks, len, "\n");
}
}
}
if ( *neededpaks ) {
Com_Printf( "Need paks: %s\n", neededpaks );
return qtrue;
}
return qfalse; // We have them all
}
/*
================
FS_Shutdown
Frees all resources.
================
*/
void FS_Shutdown( qboolean closemfp ) {
searchpath_t *p, *next;
int i;
for ( i = 0; i < MAX_FILE_HANDLES; i++ ) {
if ( fsh[i].fileSize ) {
FS_FCloseFile( i );
}
}
// free everything
for(p = fs_searchpaths; p; p = next)
{
next = p->next;
if(p->pack)
FS_FreePak(p->pack);
if (p->dir)
Z_Free(p->dir);
Z_Free(p);
}
// any FS_ calls will now be an error until reinitialized
fs_searchpaths = NULL;
Cmd_RemoveCommand( "path" );
Cmd_RemoveCommand( "dir" );
Cmd_RemoveCommand( "fdir" );
Cmd_RemoveCommand( "touchFile" );
Cmd_RemoveCommand( "which" );
#ifdef FS_MISSING
if ( closemfp ) {
fclose( missingFiles );
}
#endif
}
#ifndef STANDALONE
void Com_AppendCDKey( const char *filename );
void Com_ReadCDKey( const char *filename );
#endif
/*
================
FS_ReorderPurePaks
NOTE TTimo: the reordering that happens here is not reflected in the cvars (\cvarlist *pak*)
this can lead to misleading situations, see https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
================
*/
static void FS_ReorderPurePaks( void )
{
searchpath_t *s;
int i;
searchpath_t **p_insert_index, // for linked list reordering
**p_previous; // when doing the scan
fs_reordered = qfalse;
// only relevant when connected to pure server
if ( !fs_numServerPaks )
return;
p_insert_index = &fs_searchpaths; // we insert in order at the beginning of the list
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
p_previous = p_insert_index; // track the pointer-to-current-item
for (s = *p_insert_index; s; s = s->next) {
// the part of the list before p_insert_index has been sorted already
if (s->pack && fs_serverPaks[i] == s->pack->checksum) {
fs_reordered = qtrue;
// move this element to the insert list
*p_previous = s->next;
s->next = *p_insert_index;
*p_insert_index = s;
// increment insert list
p_insert_index = &s->next;
break; // iterate to next server pack
}
p_previous = &s->next;
}
}
}
/*
================
FS_Startup
================
*/
static void FS_Startup( const char *gameName )
{
const char *homePath;
Com_Printf( "----- FS_Startup -----\n" );
fs_packFiles = 0;
fs_debug = Cvar_Get( "fs_debug", "0", 0 );
fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT|CVAR_PROTECTED );
fs_basegame = Cvar_Get( "fs_basegame", "", CVAR_INIT );
homePath = Sys_DefaultHomePath();
if (!homePath || !homePath[0]) {
homePath = fs_basepath->string;
}
fs_homepath = Cvar_Get ("fs_homepath", homePath, CVAR_INIT|CVAR_PROTECTED );
fs_gamedirvar = Cvar_Get( "fs_game", "", CVAR_INIT | CVAR_SYSTEMINFO );
// add search path elements in reverse priority order
#ifndef STANDALONE
fs_steampath = Cvar_Get ("fs_steampath", Sys_SteamPath(), CVAR_INIT|CVAR_PROTECTED );
if (fs_steampath->string[0]) {
FS_AddGameDirectory( fs_steampath->string, gameName );
}
#endif
if ( fs_basepath->string[0] ) {
FS_AddGameDirectory( fs_basepath->string, gameName );
}
#ifdef __APPLE__
fs_apppath = Cvar_Get ("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT|CVAR_PROTECTED );
// Make MacOSX also include the base path included with the .app bundle
if (fs_apppath->string[0])
FS_AddGameDirectory(fs_apppath->string, gameName);
#endif
// NOTE: same filtering below for mods and basegame
if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string)) {
FS_CreatePath ( fs_homepath->string );
FS_AddGameDirectory( fs_homepath->string, gameName );
}
// check for additional base game so mods can be based upon other mods
if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) ) {
#ifndef STANDALONE
if ( fs_steampath->string[0] ) {
FS_AddGameDirectory( fs_steampath->string, fs_basegame->string );
}
#endif
if ( fs_basepath->string[0] ) {
FS_AddGameDirectory( fs_basepath->string, fs_basegame->string );
}
if ( fs_homepath->string[0] && Q_stricmp( fs_homepath->string,fs_basepath->string ) ) {
FS_AddGameDirectory( fs_homepath->string, fs_basegame->string );
}
}
// check for additional game folder for mods
if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) ) {
#ifndef STANDALONE
if ( fs_steampath->string[0] ) {
FS_AddGameDirectory( fs_steampath->string, fs_gamedirvar->string );
}
#endif
if ( fs_basepath->string[0] ) {
FS_AddGameDirectory( fs_basepath->string, fs_gamedirvar->string );
}
if ( fs_homepath->string[0] && Q_stricmp( fs_homepath->string,fs_basepath->string ) ) {
FS_AddGameDirectory( fs_homepath->string, fs_gamedirvar->string );
}
}
#ifndef STANDALONE
if(!com_standalone->integer)
{
cvar_t *fs;
Com_ReadCDKey(BASEGAME);
fs = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
if (fs && fs->string[0] != 0) {
Com_AppendCDKey( fs->string );
}
}
#endif
// add our commands
Cmd_AddCommand( "path", FS_Path_f );
Cmd_AddCommand( "dir", FS_Dir_f );
Cmd_AddCommand( "fdir", FS_NewDir_f );
Cmd_AddCommand( "touchFile", FS_TouchFile_f );
Cmd_AddCommand ("which", FS_Which_f );
// print the current search paths
FS_Path_f();
fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified
Com_Printf( "----------------------\n" );
#ifdef FS_MISSING
if ( missingFiles == NULL ) {
missingFiles = Sys_FOpen( "\\missing.txt", "ab" );
}
#endif
Com_Printf( "%d files in pk3 files\n", fs_packFiles );
}
#ifndef STANDALONE
/*
===================
FS_CheckSPPaks
Check whether any of the original id pak files is present,
and start up in standalone mode, if there are none and a
different com_basegame was set.
Note: If you're building a game that doesn't depend on the
Q3 media pak0.pk3, you'll want to remove this by defining
STANDALONE in q_shared.h
===================
*/
static void FS_CheckSPPaks( void )
{
searchpath_t *path;
pack_t *curpack;
unsigned int foundPak = 0;
for( path = fs_searchpaths; path; path = path->next )
{
const char* pakBasename = path->pack->pakBasename;
if(!path->pack)
continue;
curpack = path->pack;
if(!Q_stricmpn( curpack->pakGamename, BASEGAME, MAX_OSPATH )
&& strlen(pakBasename) == 7 && !Q_stricmpn( pakBasename, "sp_pak", 6 )
&& pakBasename[6] >= '1' && pakBasename[6] <= '1' + NUM_SP_PAKS - 1)
{
if( curpack->checksum != en_sppak_checksums[pakBasename[6]-'1'] &&
curpack->checksum != fr_sppak_checksums[pakBasename[6]-'1'] &&
curpack->checksum != gm_sppak_checksums[pakBasename[6]-'1'] &&
curpack->checksum != it_sppak_checksums[pakBasename[6]-'1'] &&
curpack->checksum != sp_sppak_checksums[pakBasename[6]-'1'] )
{
if(pakBasename[6] == '1')
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/sp_pak1.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-copy sp_pak1.pk3 from your\n"
"legitimate RTCW CDROM.\n"
"**************************************************\n\n\n",
curpack->checksum );
}
else
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/sp_pak%d.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-install the point release\n"
"**************************************************\n\n\n",
pakBasename[6]-'0', curpack->checksum );
}
}
foundPak |= 1<<(pakBasename[6]-'1');
}
else
{
int index;
// Finally check whether this pak's checksum is listed because the user tried
// to trick us by renaming the file, and set foundPak's highest bit to indicate this case.
for(index = 0; index < ARRAY_LEN( en_sppak_checksums ); index++)
{
if( curpack->checksum == en_sppak_checksums[index] ||
curpack->checksum == fr_sppak_checksums[index] ||
curpack->checksum == gm_sppak_checksums[index] ||
curpack->checksum == it_sppak_checksums[index] ||
curpack->checksum == sp_sppak_checksums[index] )
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: %s is renamed pak file %s%csp_pak%d.pk3\n"
"Running in standalone mode won't work\n"
"Please rename, or remove this file\n"
"**************************************************\n\n\n",
curpack->pakFilename, BASEGAME, PATH_SEP, index + 1 );
foundPak |= 0x80000000;
}
}
}
}
if(!foundPak && Q_stricmp(com_basegame->string, BASEGAME))
{
Cvar_Set("com_standalone", "1");
}
else
Cvar_Set("com_standalone", "0");
if(!com_standalone->integer && (foundPak & 0xf) != 0xf)
{
char errorText[MAX_STRING_CHARS] = "";
char missingPaks[MAX_STRING_CHARS] = "";
int i = 0;
if((foundPak & 0xf) != 0xf)
{
for( i = 0; i < NUM_SP_PAKS; i++ ) {
if ( !( foundPak & ( 1 << i ) ) ) {
Q_strcat( missingPaks, sizeof( missingPaks ), va( "sp_pak%d.pk3 ", i + 1 ) );
}
}
Q_strcat( errorText, sizeof( errorText ),
va( "\n\nPoint Release files are missing: %s \n"
"Please re-install the 1.41 point release.\n\n", missingPaks ) );
}
Com_Error(ERR_FATAL, "%s", errorText);
}
}
/*
===================
FS_CheckPak0
Check whether any of the original id pak files is present,
and start up in standalone mode, if there are none and a
different com_basegame was set.
Note: If you're building a game that doesn't depend on the
RTCW media pak0.pk3, you'll want to remove this by defining
STANDALONE in q_shared.h
===================
*/
static void FS_CheckPak0( void )
{
searchpath_t *path;
pack_t *curpack;
qboolean founddemo = qfalse;
unsigned int foundPak = 0;
for( path = fs_searchpaths; path; path = path->next )
{
const char* pakBasename = path->pack->pakBasename;
if(!path->pack)
continue;
curpack = path->pack;
if(!Q_stricmpn( curpack->pakGamename, "demomain", MAX_OSPATH )
&& !Q_stricmpn( pakBasename, "pak0", MAX_OSPATH ))
{
if(curpack->checksum == DEMO_PAK0_CHECKSUM)
founddemo = qtrue;
}
else if(!Q_stricmpn( curpack->pakGamename, BASEGAME, MAX_OSPATH )
&& strlen(pakBasename) == 4 && !Q_stricmpn( pakBasename, "pak", 3 )
&& pakBasename[3] >= '0' && pakBasename[3] <= '0' + NUM_ID_PAKS - 1)
{
if( curpack->checksum != pak_checksums[pakBasename[3]-'0'] )
{
if(pakBasename[3] == '0')
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/pak0.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-copy pak0.pk3 from your\n"
"legitimate RTCW CDROM.\n"
"**************************************************\n\n\n",
curpack->checksum );
Com_Error(ERR_FATAL, NULL);
}
/*
else
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/pak%d.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-install the point release\n"
"**************************************************\n\n\n",
pakBasename[3]-'0', curpack->checksum );
}
*/
}
foundPak |= 1<<(pakBasename[3]-'0');
}
else
{
int index;
// Finally check whether this pak's checksum is listed because the user tried
// to trick us by renaming the file, and set foundPak's highest bit to indicate this case.
for(index = 0; index < ARRAY_LEN(pak_checksums); index++)
{
if(curpack->checksum == pak_checksums[index])
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: %s is renamed pak file %s%cpak%d.pk3\n"
"Running in standalone mode won't work\n"
"Please rename, or remove this file\n"
"**************************************************\n\n\n",
curpack->pakFilename, BASEGAME, PATH_SEP, index);
foundPak |= 0x80000000;
}
}
}
}
if(!foundPak && Q_stricmp(com_basegame->string, BASEGAME))
{
Cvar_Set("com_standalone", "1");
}
else
Cvar_Set("com_standalone", "0");
if(!com_standalone->integer)
{
if(!(foundPak & 0x01))
{
if(founddemo)
{
Com_Printf( "\n\n"
"**************************************************\n"
"WARNING: It looks like you're using pak0.pk3\n"
"from the demo. This may work fine, but it is not\n"
"guaranteed or supported.\n"
"**************************************************\n\n\n" );
foundPak |= 0x01;
}
}
}
if(!com_standalone->integer && (foundPak & 0x01) != 0x01)
{
char errorText[MAX_STRING_CHARS] = "";
if((foundPak & 0x01) != 0x01)
{
Q_strcat(errorText, sizeof(errorText),
"\n\n\"pak0.pk3\" is missing. Please copy it\n"
"from your legitimate RTCW CDROM.\n\n");
}
Q_strcat(errorText, sizeof(errorText),
va("Also check that your iortcw executable is in\n"
"the correct place and that every file\n"
"in the \"%s\" directory is present and readable.\n\n", BASEGAME));
Com_Error(ERR_FATAL, "%s", errorText);
}
if(!founddemo)
FS_CheckSPPaks();
}
#endif
/*
=====================
FS_LoadedPakChecksums
Returns a space separated string containing the checksums of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->checksum ) );
}
return info;
}
/*
=====================
FS_LoadedPakNames
Returns a space separated string containing the names of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
if ( *info ) {
Q_strcat( info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
return info;
}
/*
=====================
FS_LoadedPakPureChecksums
Returns a space separated string containing the pure checksums of all loaded pk3 files.
Servers with sv_pure use these checksums to compare with the checksums the clients send
back to the server.
=====================
*/
const char *FS_LoadedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->pure_checksum ) );
}
return info;
}
/*
=====================
FS_ReferencedPakChecksums
Returns a space separated string containing the checksums of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) {
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->checksum ) );
}
}
}
return info;
}
/*
=====================
FS_ReferencedPakPureChecksums
Returns a space separated string containing the pure checksums of all referenced pk3 files.
Servers with sv_pure set will get this string back from clients for pure validation
The string has a specific order, "cgame ui @ ref1 ref2 ref3 ..."
NOTE TTimo: this code is taken from Wolf MP source
pure checksums code is not relevant to SP binary anyway
=====================
*/
const char *FS_ReferencedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
int nFlags, numPaks, checksum;
info[0] = 0;
checksum = fs_checksumFeed;
numPaks = 0;
for ( nFlags = FS_GENERAL_REF; nFlags; nFlags = nFlags >> 1 ) {
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file and has it been referenced based on flag?
if ( search->pack && ( search->pack->referenced & nFlags ) ) {
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->pure_checksum ) );
checksum ^= search->pack->pure_checksum;
numPaks++;
}
}
}
// last checksum is the encoded number of referenced pk3s
checksum ^= numPaks;
Q_strcat( info, sizeof( info ), va( "%i ", checksum ) );
return info;
}
/*
=====================
FS_ReferencedPakNames
Returns a space separated string containing the names of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
// we want to return ALL pk3's from the fs_game path
// and referenced one's from baseq3
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) {
if (*info) {
Q_strcat(info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakGamename );
Q_strcat( info, sizeof( info ), "/" );
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
}
}
return info;
}
/*
=====================
FS_ClearPakReferences
=====================
*/
void FS_ClearPakReferences( int flags ) {
searchpath_t *search;
if ( !flags ) {
flags = -1;
}
for ( search = fs_searchpaths; search; search = search->next ) {
// is the element a pak file and has it been referenced?
if ( search->pack ) {
search->pack->referenced &= ~flags;
}
}
}
/*
=====================
FS_PureServerSetLoadedPaks
If the string is empty, all data sources will be allowed.
If not empty, only pk3 files that match one of the space
separated checksums will be checked for files, with the
exception of .cfg and .dat files.
=====================
*/
void FS_PureServerSetLoadedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
fs_numServerPaks = c;
for ( i = 0 ; i < c ; i++ ) {
fs_serverPaks[i] = atoi( Cmd_Argv( i ) );
}
if ( fs_numServerPaks ) {
Com_DPrintf( "Connected to a pure server.\n" );
}
for ( i = 0 ; i < c ; i++ ) {
if ( fs_serverPakNames[i] ) {
Z_Free( fs_serverPakNames[i] );
}
fs_serverPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if ( d > MAX_SEARCH_PATHS ) {
d = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < d ; i++ ) {
fs_serverPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
}
/*
=====================
FS_PureServerSetReferencedPaks
The checksums and names of the pk3 files referenced at the server
are sent to the client and stored here. The client will use these
checksums to see if any pk3 files need to be auto-downloaded.
=====================
*/
void FS_PureServerSetReferencedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d = 0;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < c ; i++ ) {
fs_serverReferencedPaks[i] = atoi( Cmd_Argv( i ) );
}
for (i = 0 ; i < ARRAY_LEN(fs_serverReferencedPakNames); i++)
{
if(fs_serverReferencedPakNames[i])
Z_Free( fs_serverReferencedPakNames[i] );
fs_serverReferencedPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if(d > c)
d = c;
for ( i = 0 ; i < d ; i++ ) {
fs_serverReferencedPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
// ensure that there are as many checksums as there are pak names.
if(d < c)
c = d;
fs_numServerReferencedPaks = c;
}
/*
================
FS_InitFilesystem
Called only at inital startup, not when the filesystem
is resetting due to a game change
================
*/
void FS_InitFilesystem( void ) {
// allow command line parms to override our defaults
// we have to specially handle this, because normal command
// line variable sets don't happen until after the filesystem
// has already been initialized
Com_StartupVariable("fs_basepath");
Com_StartupVariable("fs_homepath");
Com_StartupVariable("fs_game");
if(!FS_FilenameCompare(Cvar_VariableString("fs_game"), com_basegame->string))
Cvar_Set("fs_game", "");
// try to start up normally
FS_Startup(com_basegame->string);
#ifndef STANDALONE
FS_CheckPak0( );
#endif
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
}
Q_strncpyz( lastValidBase, fs_basepath->string, sizeof( lastValidBase ) );
Q_strncpyz( lastValidComBaseGame, com_basegame->string, sizeof( lastValidComBaseGame ) );
Q_strncpyz( lastValidFsBaseGame, fs_basegame->string, sizeof( lastValidFsBaseGame ) );
Q_strncpyz( lastValidGame, fs_gamedirvar->string, sizeof( lastValidGame ) );
}
/*
================
FS_Restart
================
*/
void FS_Restart( int checksumFeed ) {
const char *lastGameDir;
// free anything we currently have loaded
FS_Shutdown( qfalse );
// set the checksum feed
fs_checksumFeed = checksumFeed;
// clear pak references
FS_ClearPakReferences( 0 );
// try to start up normally
FS_Startup(com_basegame->string);
#ifndef STANDALONE
FS_CheckPak0( );
#endif
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
// this might happen when connecting to a pure server not using BASEGAME/pak0.pk3
// (for instance a TA demo server)
if ( lastValidBase[0] ) {
FS_PureServerSetLoadedPaks( "", "" );
Cvar_Set( "fs_basepath", lastValidBase );
Cvar_Set( "com_basegame", lastValidComBaseGame );
Cvar_Set( "fs_basegame", lastValidFsBaseGame );
Cvar_Set( "fs_game", lastValidGame );
lastValidBase[0] = '\0';
lastValidComBaseGame[0] = '\0';
lastValidFsBaseGame[0] = '\0';
lastValidGame[0] = '\0';
FS_Restart( checksumFeed );
Com_Error( ERR_DROP, "Invalid game folder" );
return;
}
Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
}
lastGameDir = ( lastValidGame[0] ) ? lastValidGame : lastValidComBaseGame;
if ( Q_stricmp( FS_GetCurrentGameDir(), lastGameDir ) ) {
Sys_RemovePIDFile( lastGameDir );
Sys_InitPIDFile( FS_GetCurrentGameDir() );
// skip the wolfconfig.cfg if "safe" is on the command line
if ( !Com_SafeMode() ) {
Cbuf_AddText ("exec " Q3CONFIG_CFG "\n");
}
}
Q_strncpyz( lastValidBase, fs_basepath->string, sizeof( lastValidBase ) );
Q_strncpyz( lastValidComBaseGame, com_basegame->string, sizeof( lastValidComBaseGame ) );
Q_strncpyz( lastValidFsBaseGame, fs_basegame->string, sizeof( lastValidFsBaseGame ) );
Q_strncpyz( lastValidGame, fs_gamedirvar->string, sizeof( lastValidGame ) );
}
/*
=================
FS_ConditionalRestart
Restart if necessary
Return qtrue if restarting due to game directory changed, qfalse otherwise
=================
*/
qboolean FS_ConditionalRestart(int checksumFeed, qboolean disconnect)
{
if(fs_gamedirvar->modified)
{
if(FS_FilenameCompare(lastValidGame, fs_gamedirvar->string) &&
(*lastValidGame || FS_FilenameCompare(fs_gamedirvar->string, com_basegame->string)) &&
(*fs_gamedirvar->string || FS_FilenameCompare(lastValidGame, com_basegame->string)))
{
Com_GameRestart(checksumFeed, disconnect);
return qtrue;
}
else
fs_gamedirvar->modified = qfalse;
}
if(checksumFeed != fs_checksumFeed)
FS_Restart(checksumFeed);
else if(fs_numServerPaks && !fs_reordered)
FS_ReorderPurePaks();
return qfalse;
}
/*
========================================================================================
Handle based file calls for virtual machines
========================================================================================
*/
int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
int r;
qboolean sync;
sync = qfalse;
switch ( mode ) {
case FS_READ:
r = FS_FOpenFileRead( qpath, f, qtrue );
break;
case FS_WRITE:
*f = FS_FOpenFileWrite( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
case FS_APPEND_SYNC:
sync = qtrue;
case FS_APPEND:
*f = FS_FOpenFileAppend( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
default:
Com_Error( ERR_FATAL, "FS_FOpenFileByMode: bad mode" );
return -1;
}
if ( !f ) {
return r;
}
if ( *f ) {
fsh[*f].fileSize = r;
fsh[*f].streamed = qfalse;
if (mode == FS_READ) {
fsh[*f].streamed = qtrue;
}
}
fsh[*f].handleSync = sync;
return r;
}
int FS_FTell( fileHandle_t f ) {
int pos;
if ( fsh[f].zipFile == qtrue ) {
pos = unztell( fsh[f].handleFiles.file.z );
} else {
pos = ftell( fsh[f].handleFiles.file.o );
}
return pos;
}
void FS_Flush( fileHandle_t f ) {
fflush( fsh[f].handleFiles.file.o );
}
void FS_FilenameCompletion( const char *dir, const char *ext,
qboolean stripExt, void(*callback)(const char *s), qboolean allowNonPureFilesOnDisk ) {
char **filenames;
int nfiles;
int i;
char filename[ MAX_STRING_CHARS ];
filenames = FS_ListFilteredFiles( dir, ext, NULL, &nfiles, allowNonPureFilesOnDisk );
FS_SortFileList( filenames, nfiles );
for( i = 0; i < nfiles; i++ ) {
FS_ConvertPath( filenames[ i ] );
Q_strncpyz( filename, filenames[ i ], MAX_STRING_CHARS );
if( stripExt ) {
COM_StripExtension(filename, filename, sizeof(filename));
}
callback( filename );
}
FS_FreeFileList( filenames );
}
const char *FS_GetCurrentGameDir(void)
{
if(fs_gamedirvar->string[0])
return fs_gamedirvar->string;
return com_basegame->string;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3233_4 |
crossvul-cpp_data_bad_5626_0 | /*
* Virtio Support
*
* Copyright IBM, Corp. 2007
*
* Authors:
* Anthony Liguori <aliguori@us.ibm.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
*/
#include <inttypes.h>
#include "trace.h"
#include "qemu/error-report.h"
#include "hw/virtio/virtio.h"
#include "qemu/atomic.h"
#include "hw/virtio/virtio-bus.h"
/* The alignment to use between consumer and producer parts of vring.
* x86 pagesize again. */
#define VIRTIO_PCI_VRING_ALIGN 4096
typedef struct VRingDesc
{
uint64_t addr;
uint32_t len;
uint16_t flags;
uint16_t next;
} VRingDesc;
typedef struct VRingAvail
{
uint16_t flags;
uint16_t idx;
uint16_t ring[0];
} VRingAvail;
typedef struct VRingUsedElem
{
uint32_t id;
uint32_t len;
} VRingUsedElem;
typedef struct VRingUsed
{
uint16_t flags;
uint16_t idx;
VRingUsedElem ring[0];
} VRingUsed;
typedef struct VRing
{
unsigned int num;
hwaddr desc;
hwaddr avail;
hwaddr used;
} VRing;
struct VirtQueue
{
VRing vring;
hwaddr pa;
uint16_t last_avail_idx;
/* Last used index value we have signalled on */
uint16_t signalled_used;
/* Last used index value we have signalled on */
bool signalled_used_valid;
/* Notification enabled? */
bool notification;
uint16_t queue_index;
int inuse;
uint16_t vector;
void (*handle_output)(VirtIODevice *vdev, VirtQueue *vq);
VirtIODevice *vdev;
EventNotifier guest_notifier;
EventNotifier host_notifier;
};
/* virt queue functions */
static void virtqueue_init(VirtQueue *vq)
{
hwaddr pa = vq->pa;
vq->vring.desc = pa;
vq->vring.avail = pa + vq->vring.num * sizeof(VRingDesc);
vq->vring.used = vring_align(vq->vring.avail +
offsetof(VRingAvail, ring[vq->vring.num]),
VIRTIO_PCI_VRING_ALIGN);
}
static inline uint64_t vring_desc_addr(hwaddr desc_pa, int i)
{
hwaddr pa;
pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, addr);
return ldq_phys(pa);
}
static inline uint32_t vring_desc_len(hwaddr desc_pa, int i)
{
hwaddr pa;
pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, len);
return ldl_phys(pa);
}
static inline uint16_t vring_desc_flags(hwaddr desc_pa, int i)
{
hwaddr pa;
pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, flags);
return lduw_phys(pa);
}
static inline uint16_t vring_desc_next(hwaddr desc_pa, int i)
{
hwaddr pa;
pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, next);
return lduw_phys(pa);
}
static inline uint16_t vring_avail_flags(VirtQueue *vq)
{
hwaddr pa;
pa = vq->vring.avail + offsetof(VRingAvail, flags);
return lduw_phys(pa);
}
static inline uint16_t vring_avail_idx(VirtQueue *vq)
{
hwaddr pa;
pa = vq->vring.avail + offsetof(VRingAvail, idx);
return lduw_phys(pa);
}
static inline uint16_t vring_avail_ring(VirtQueue *vq, int i)
{
hwaddr pa;
pa = vq->vring.avail + offsetof(VRingAvail, ring[i]);
return lduw_phys(pa);
}
static inline uint16_t vring_used_event(VirtQueue *vq)
{
return vring_avail_ring(vq, vq->vring.num);
}
static inline void vring_used_ring_id(VirtQueue *vq, int i, uint32_t val)
{
hwaddr pa;
pa = vq->vring.used + offsetof(VRingUsed, ring[i].id);
stl_phys(pa, val);
}
static inline void vring_used_ring_len(VirtQueue *vq, int i, uint32_t val)
{
hwaddr pa;
pa = vq->vring.used + offsetof(VRingUsed, ring[i].len);
stl_phys(pa, val);
}
static uint16_t vring_used_idx(VirtQueue *vq)
{
hwaddr pa;
pa = vq->vring.used + offsetof(VRingUsed, idx);
return lduw_phys(pa);
}
static inline void vring_used_idx_set(VirtQueue *vq, uint16_t val)
{
hwaddr pa;
pa = vq->vring.used + offsetof(VRingUsed, idx);
stw_phys(pa, val);
}
static inline void vring_used_flags_set_bit(VirtQueue *vq, int mask)
{
hwaddr pa;
pa = vq->vring.used + offsetof(VRingUsed, flags);
stw_phys(pa, lduw_phys(pa) | mask);
}
static inline void vring_used_flags_unset_bit(VirtQueue *vq, int mask)
{
hwaddr pa;
pa = vq->vring.used + offsetof(VRingUsed, flags);
stw_phys(pa, lduw_phys(pa) & ~mask);
}
static inline void vring_avail_event(VirtQueue *vq, uint16_t val)
{
hwaddr pa;
if (!vq->notification) {
return;
}
pa = vq->vring.used + offsetof(VRingUsed, ring[vq->vring.num]);
stw_phys(pa, val);
}
void virtio_queue_set_notification(VirtQueue *vq, int enable)
{
vq->notification = enable;
if (vq->vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) {
vring_avail_event(vq, vring_avail_idx(vq));
} else if (enable) {
vring_used_flags_unset_bit(vq, VRING_USED_F_NO_NOTIFY);
} else {
vring_used_flags_set_bit(vq, VRING_USED_F_NO_NOTIFY);
}
if (enable) {
/* Expose avail event/used flags before caller checks the avail idx. */
smp_mb();
}
}
int virtio_queue_ready(VirtQueue *vq)
{
return vq->vring.avail != 0;
}
int virtio_queue_empty(VirtQueue *vq)
{
return vring_avail_idx(vq) == vq->last_avail_idx;
}
void virtqueue_fill(VirtQueue *vq, const VirtQueueElement *elem,
unsigned int len, unsigned int idx)
{
unsigned int offset;
int i;
trace_virtqueue_fill(vq, elem, len, idx);
offset = 0;
for (i = 0; i < elem->in_num; i++) {
size_t size = MIN(len - offset, elem->in_sg[i].iov_len);
cpu_physical_memory_unmap(elem->in_sg[i].iov_base,
elem->in_sg[i].iov_len,
1, size);
offset += size;
}
for (i = 0; i < elem->out_num; i++)
cpu_physical_memory_unmap(elem->out_sg[i].iov_base,
elem->out_sg[i].iov_len,
0, elem->out_sg[i].iov_len);
idx = (idx + vring_used_idx(vq)) % vq->vring.num;
/* Get a pointer to the next entry in the used ring. */
vring_used_ring_id(vq, idx, elem->index);
vring_used_ring_len(vq, idx, len);
}
void virtqueue_flush(VirtQueue *vq, unsigned int count)
{
uint16_t old, new;
/* Make sure buffer is written before we update index. */
smp_wmb();
trace_virtqueue_flush(vq, count);
old = vring_used_idx(vq);
new = old + count;
vring_used_idx_set(vq, new);
vq->inuse -= count;
if (unlikely((int16_t)(new - vq->signalled_used) < (uint16_t)(new - old)))
vq->signalled_used_valid = false;
}
void virtqueue_push(VirtQueue *vq, const VirtQueueElement *elem,
unsigned int len)
{
virtqueue_fill(vq, elem, len, 0);
virtqueue_flush(vq, 1);
}
static int virtqueue_num_heads(VirtQueue *vq, unsigned int idx)
{
uint16_t num_heads = vring_avail_idx(vq) - idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (num_heads > vq->vring.num) {
error_report("Guest moved used index from %u to %u",
idx, vring_avail_idx(vq));
exit(1);
}
/* On success, callers read a descriptor at vq->last_avail_idx.
* Make sure descriptor read does not bypass avail index read. */
if (num_heads) {
smp_rmb();
}
return num_heads;
}
static unsigned int virtqueue_get_head(VirtQueue *vq, unsigned int idx)
{
unsigned int head;
/* Grab the next descriptor number they're advertising, and increment
* the index we've seen. */
head = vring_avail_ring(vq, idx % vq->vring.num);
/* If their number is silly, that's a fatal mistake. */
if (head >= vq->vring.num) {
error_report("Guest says index %u is available", head);
exit(1);
}
return head;
}
static unsigned virtqueue_next_desc(hwaddr desc_pa,
unsigned int i, unsigned int max)
{
unsigned int next;
/* If this descriptor says it doesn't chain, we're done. */
if (!(vring_desc_flags(desc_pa, i) & VRING_DESC_F_NEXT))
return max;
/* Check they're not leading us off end of descriptors. */
next = vring_desc_next(desc_pa, i);
/* Make sure compiler knows to grab that: we don't want it changing! */
smp_wmb();
if (next >= max) {
error_report("Desc next is %u", next);
exit(1);
}
return next;
}
void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes,
unsigned int *out_bytes,
unsigned max_in_bytes, unsigned max_out_bytes)
{
unsigned int idx;
unsigned int total_bufs, in_total, out_total;
idx = vq->last_avail_idx;
total_bufs = in_total = out_total = 0;
while (virtqueue_num_heads(vq, idx)) {
unsigned int max, num_bufs, indirect = 0;
hwaddr desc_pa;
int i;
max = vq->vring.num;
num_bufs = total_bufs;
i = virtqueue_get_head(vq, idx++);
desc_pa = vq->vring.desc;
if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_INDIRECT) {
if (vring_desc_len(desc_pa, i) % sizeof(VRingDesc)) {
error_report("Invalid size for indirect buffer table");
exit(1);
}
/* If we've got too many, that implies a descriptor loop. */
if (num_bufs >= max) {
error_report("Looped descriptor");
exit(1);
}
/* loop over the indirect descriptor table */
indirect = 1;
max = vring_desc_len(desc_pa, i) / sizeof(VRingDesc);
num_bufs = i = 0;
desc_pa = vring_desc_addr(desc_pa, i);
}
do {
/* If we've got too many, that implies a descriptor loop. */
if (++num_bufs > max) {
error_report("Looped descriptor");
exit(1);
}
if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_WRITE) {
in_total += vring_desc_len(desc_pa, i);
} else {
out_total += vring_desc_len(desc_pa, i);
}
if (in_total >= max_in_bytes && out_total >= max_out_bytes) {
goto done;
}
} while ((i = virtqueue_next_desc(desc_pa, i, max)) != max);
if (!indirect)
total_bufs = num_bufs;
else
total_bufs++;
}
done:
if (in_bytes) {
*in_bytes = in_total;
}
if (out_bytes) {
*out_bytes = out_total;
}
}
int virtqueue_avail_bytes(VirtQueue *vq, unsigned int in_bytes,
unsigned int out_bytes)
{
unsigned int in_total, out_total;
virtqueue_get_avail_bytes(vq, &in_total, &out_total, in_bytes, out_bytes);
return in_bytes <= in_total && out_bytes <= out_total;
}
void virtqueue_map_sg(struct iovec *sg, hwaddr *addr,
size_t num_sg, int is_write)
{
unsigned int i;
hwaddr len;
for (i = 0; i < num_sg; i++) {
len = sg[i].iov_len;
sg[i].iov_base = cpu_physical_memory_map(addr[i], &len, is_write);
if (sg[i].iov_base == NULL || len != sg[i].iov_len) {
error_report("virtio: trying to map MMIO memory");
exit(1);
}
}
}
int virtqueue_pop(VirtQueue *vq, VirtQueueElement *elem)
{
unsigned int i, head, max;
hwaddr desc_pa = vq->vring.desc;
if (!virtqueue_num_heads(vq, vq->last_avail_idx))
return 0;
/* When we start there are none of either input nor output. */
elem->out_num = elem->in_num = 0;
max = vq->vring.num;
i = head = virtqueue_get_head(vq, vq->last_avail_idx++);
if (vq->vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) {
vring_avail_event(vq, vring_avail_idx(vq));
}
if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_INDIRECT) {
if (vring_desc_len(desc_pa, i) % sizeof(VRingDesc)) {
error_report("Invalid size for indirect buffer table");
exit(1);
}
/* loop over the indirect descriptor table */
max = vring_desc_len(desc_pa, i) / sizeof(VRingDesc);
desc_pa = vring_desc_addr(desc_pa, i);
i = 0;
}
/* Collect all the descriptors */
do {
struct iovec *sg;
if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_WRITE) {
if (elem->in_num >= ARRAY_SIZE(elem->in_sg)) {
error_report("Too many write descriptors in indirect table");
exit(1);
}
elem->in_addr[elem->in_num] = vring_desc_addr(desc_pa, i);
sg = &elem->in_sg[elem->in_num++];
} else {
if (elem->out_num >= ARRAY_SIZE(elem->out_sg)) {
error_report("Too many read descriptors in indirect table");
exit(1);
}
elem->out_addr[elem->out_num] = vring_desc_addr(desc_pa, i);
sg = &elem->out_sg[elem->out_num++];
}
sg->iov_len = vring_desc_len(desc_pa, i);
/* If we've got too many, that implies a descriptor loop. */
if ((elem->in_num + elem->out_num) > max) {
error_report("Looped descriptor");
exit(1);
}
} while ((i = virtqueue_next_desc(desc_pa, i, max)) != max);
/* Now map what we have collected */
virtqueue_map_sg(elem->in_sg, elem->in_addr, elem->in_num, 1);
virtqueue_map_sg(elem->out_sg, elem->out_addr, elem->out_num, 0);
elem->index = head;
vq->inuse++;
trace_virtqueue_pop(vq, elem, elem->in_num, elem->out_num);
return elem->in_num + elem->out_num;
}
/* virtio device */
static void virtio_notify_vector(VirtIODevice *vdev, uint16_t vector)
{
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->notify) {
k->notify(qbus->parent, vector);
}
}
void virtio_update_irq(VirtIODevice *vdev)
{
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
}
void virtio_set_status(VirtIODevice *vdev, uint8_t val)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
trace_virtio_set_status(vdev, val);
if (k->set_status) {
k->set_status(vdev, val);
}
vdev->status = val;
}
void virtio_reset(void *opaque)
{
VirtIODevice *vdev = opaque;
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
int i;
virtio_set_status(vdev, 0);
if (k->reset) {
k->reset(vdev);
}
vdev->guest_features = 0;
vdev->queue_sel = 0;
vdev->status = 0;
vdev->isr = 0;
vdev->config_vector = VIRTIO_NO_VECTOR;
virtio_notify_vector(vdev, vdev->config_vector);
for(i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
vdev->vq[i].vring.desc = 0;
vdev->vq[i].vring.avail = 0;
vdev->vq[i].vring.used = 0;
vdev->vq[i].last_avail_idx = 0;
vdev->vq[i].pa = 0;
vdev->vq[i].vector = VIRTIO_NO_VECTOR;
vdev->vq[i].signalled_used = 0;
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
}
}
uint32_t virtio_config_readb(VirtIODevice *vdev, uint32_t addr)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint8_t val;
k->get_config(vdev, vdev->config);
if (addr > (vdev->config_len - sizeof(val)))
return (uint32_t)-1;
val = ldub_p(vdev->config + addr);
return val;
}
uint32_t virtio_config_readw(VirtIODevice *vdev, uint32_t addr)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint16_t val;
k->get_config(vdev, vdev->config);
if (addr > (vdev->config_len - sizeof(val)))
return (uint32_t)-1;
val = lduw_p(vdev->config + addr);
return val;
}
uint32_t virtio_config_readl(VirtIODevice *vdev, uint32_t addr)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint32_t val;
k->get_config(vdev, vdev->config);
if (addr > (vdev->config_len - sizeof(val)))
return (uint32_t)-1;
val = ldl_p(vdev->config + addr);
return val;
}
void virtio_config_writeb(VirtIODevice *vdev, uint32_t addr, uint32_t data)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint8_t val = data;
if (addr > (vdev->config_len - sizeof(val)))
return;
stb_p(vdev->config + addr, val);
if (k->set_config) {
k->set_config(vdev, vdev->config);
}
}
void virtio_config_writew(VirtIODevice *vdev, uint32_t addr, uint32_t data)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint16_t val = data;
if (addr > (vdev->config_len - sizeof(val)))
return;
stw_p(vdev->config + addr, val);
if (k->set_config) {
k->set_config(vdev, vdev->config);
}
}
void virtio_config_writel(VirtIODevice *vdev, uint32_t addr, uint32_t data)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint32_t val = data;
if (addr > (vdev->config_len - sizeof(val)))
return;
stl_p(vdev->config + addr, val);
if (k->set_config) {
k->set_config(vdev, vdev->config);
}
}
void virtio_queue_set_addr(VirtIODevice *vdev, int n, hwaddr addr)
{
vdev->vq[n].pa = addr;
virtqueue_init(&vdev->vq[n]);
}
hwaddr virtio_queue_get_addr(VirtIODevice *vdev, int n)
{
return vdev->vq[n].pa;
}
int virtio_queue_get_num(VirtIODevice *vdev, int n)
{
return vdev->vq[n].vring.num;
}
int virtio_queue_get_id(VirtQueue *vq)
{
VirtIODevice *vdev = vq->vdev;
assert(vq >= &vdev->vq[0] && vq < &vdev->vq[VIRTIO_PCI_QUEUE_MAX]);
return vq - &vdev->vq[0];
}
void virtio_queue_notify_vq(VirtQueue *vq)
{
if (vq->vring.desc) {
VirtIODevice *vdev = vq->vdev;
trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
vq->handle_output(vdev, vq);
}
}
void virtio_queue_notify(VirtIODevice *vdev, int n)
{
virtio_queue_notify_vq(&vdev->vq[n]);
}
uint16_t virtio_queue_vector(VirtIODevice *vdev, int n)
{
return n < VIRTIO_PCI_QUEUE_MAX ? vdev->vq[n].vector :
VIRTIO_NO_VECTOR;
}
void virtio_queue_set_vector(VirtIODevice *vdev, int n, uint16_t vector)
{
if (n < VIRTIO_PCI_QUEUE_MAX)
vdev->vq[n].vector = vector;
}
VirtQueue *virtio_add_queue(VirtIODevice *vdev, int queue_size,
void (*handle_output)(VirtIODevice *, VirtQueue *))
{
int i;
for (i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
if (vdev->vq[i].vring.num == 0)
break;
}
if (i == VIRTIO_PCI_QUEUE_MAX || queue_size > VIRTQUEUE_MAX_SIZE)
abort();
vdev->vq[i].vring.num = queue_size;
vdev->vq[i].handle_output = handle_output;
return &vdev->vq[i];
}
void virtio_del_queue(VirtIODevice *vdev, int n)
{
if (n < 0 || n >= VIRTIO_PCI_QUEUE_MAX) {
abort();
}
vdev->vq[n].vring.num = 0;
}
void virtio_irq(VirtQueue *vq)
{
trace_virtio_irq(vq);
vq->vdev->isr |= 0x01;
virtio_notify_vector(vq->vdev, vq->vector);
}
/* Assuming a given event_idx value from the other size, if
* we have just incremented index from old to new_idx,
* should we trigger an event? */
static inline int vring_need_event(uint16_t event, uint16_t new, uint16_t old)
{
/* Note: Xen has similar logic for notification hold-off
* in include/xen/interface/io/ring.h with req_event and req_prod
* corresponding to event_idx + 1 and new respectively.
* Note also that req_event and req_prod in Xen start at 1,
* event indexes in virtio start at 0. */
return (uint16_t)(new - event - 1) < (uint16_t)(new - old);
}
static bool vring_notify(VirtIODevice *vdev, VirtQueue *vq)
{
uint16_t old, new;
bool v;
/* We need to expose used array entries before checking used event. */
smp_mb();
/* Always notify when queue is empty (when feature acknowledge) */
if (((vdev->guest_features & (1 << VIRTIO_F_NOTIFY_ON_EMPTY)) &&
!vq->inuse && vring_avail_idx(vq) == vq->last_avail_idx)) {
return true;
}
if (!(vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX))) {
return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT);
}
v = vq->signalled_used_valid;
vq->signalled_used_valid = true;
old = vq->signalled_used;
new = vq->signalled_used = vring_used_idx(vq);
return !v || vring_need_event(vring_used_event(vq), new, old);
}
void virtio_notify(VirtIODevice *vdev, VirtQueue *vq)
{
if (!vring_notify(vdev, vq)) {
return;
}
trace_virtio_notify(vdev, vq);
vdev->isr |= 0x01;
virtio_notify_vector(vdev, vq->vector);
}
void virtio_notify_config(VirtIODevice *vdev)
{
if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))
return;
vdev->isr |= 0x03;
virtio_notify_vector(vdev, vdev->config_vector);
}
void virtio_save(VirtIODevice *vdev, QEMUFile *f)
{
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
int i;
if (k->save_config) {
k->save_config(qbus->parent, f);
}
qemu_put_8s(f, &vdev->status);
qemu_put_8s(f, &vdev->isr);
qemu_put_be16s(f, &vdev->queue_sel);
qemu_put_be32s(f, &vdev->guest_features);
qemu_put_be32(f, vdev->config_len);
qemu_put_buffer(f, vdev->config, vdev->config_len);
for (i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
if (vdev->vq[i].vring.num == 0)
break;
}
qemu_put_be32(f, i);
for (i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
if (vdev->vq[i].vring.num == 0)
break;
qemu_put_be32(f, vdev->vq[i].vring.num);
qemu_put_be64(f, vdev->vq[i].pa);
qemu_put_be16s(f, &vdev->vq[i].last_avail_idx);
if (k->save_queue) {
k->save_queue(qbus->parent, i, f);
}
}
}
int virtio_set_features(VirtIODevice *vdev, uint32_t val)
{
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *vbusk = VIRTIO_BUS_GET_CLASS(qbus);
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint32_t supported_features = vbusk->get_features(qbus->parent);
bool bad = (val & ~supported_features) != 0;
val &= supported_features;
if (k->set_features) {
k->set_features(vdev, val);
}
vdev->guest_features = val;
return bad ? -1 : 0;
}
int virtio_load(VirtIODevice *vdev, QEMUFile *f)
{
int num, i, ret;
uint32_t features;
uint32_t supported_features;
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->load_config) {
ret = k->load_config(qbus->parent, f);
if (ret)
return ret;
}
qemu_get_8s(f, &vdev->status);
qemu_get_8s(f, &vdev->isr);
qemu_get_be16s(f, &vdev->queue_sel);
qemu_get_be32s(f, &features);
if (virtio_set_features(vdev, features) < 0) {
supported_features = k->get_features(qbus->parent);
error_report("Features 0x%x unsupported. Allowed features: 0x%x",
features, supported_features);
return -1;
}
vdev->config_len = qemu_get_be32(f);
qemu_get_buffer(f, vdev->config, vdev->config_len);
num = qemu_get_be32(f);
for (i = 0; i < num; i++) {
vdev->vq[i].vring.num = qemu_get_be32(f);
vdev->vq[i].pa = qemu_get_be64(f);
qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
if (vdev->vq[i].pa) {
uint16_t nheads;
virtqueue_init(&vdev->vq[i]);
nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (nheads > vdev->vq[i].vring.num) {
error_report("VQ %d size 0x%x Guest index 0x%x "
"inconsistent with Host index 0x%x: delta 0x%x",
i, vdev->vq[i].vring.num,
vring_avail_idx(&vdev->vq[i]),
vdev->vq[i].last_avail_idx, nheads);
return -1;
}
} else if (vdev->vq[i].last_avail_idx) {
error_report("VQ %d address 0x0 "
"inconsistent with Host index 0x%x",
i, vdev->vq[i].last_avail_idx);
return -1;
}
if (k->load_queue) {
ret = k->load_queue(qbus->parent, i, f);
if (ret)
return ret;
}
}
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
return 0;
}
void virtio_cleanup(VirtIODevice *vdev)
{
qemu_del_vm_change_state_handler(vdev->vmstate);
g_free(vdev->config);
g_free(vdev->vq);
}
static void virtio_vmstate_change(void *opaque, int running, RunState state)
{
VirtIODevice *vdev = opaque;
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
bool backend_run = running && (vdev->status & VIRTIO_CONFIG_S_DRIVER_OK);
vdev->vm_running = running;
if (backend_run) {
virtio_set_status(vdev, vdev->status);
}
if (k->vmstate_change) {
k->vmstate_change(qbus->parent, backend_run);
}
if (!backend_run) {
virtio_set_status(vdev, vdev->status);
}
}
void virtio_init(VirtIODevice *vdev, const char *name,
uint16_t device_id, size_t config_size)
{
int i;
vdev->device_id = device_id;
vdev->status = 0;
vdev->isr = 0;
vdev->queue_sel = 0;
vdev->config_vector = VIRTIO_NO_VECTOR;
vdev->vq = g_malloc0(sizeof(VirtQueue) * VIRTIO_PCI_QUEUE_MAX);
vdev->vm_running = runstate_is_running();
for (i = 0; i < VIRTIO_PCI_QUEUE_MAX; i++) {
vdev->vq[i].vector = VIRTIO_NO_VECTOR;
vdev->vq[i].vdev = vdev;
vdev->vq[i].queue_index = i;
}
vdev->name = name;
vdev->config_len = config_size;
if (vdev->config_len) {
vdev->config = g_malloc0(config_size);
} else {
vdev->config = NULL;
}
vdev->vmstate = qemu_add_vm_change_state_handler(virtio_vmstate_change,
vdev);
}
hwaddr virtio_queue_get_desc_addr(VirtIODevice *vdev, int n)
{
return vdev->vq[n].vring.desc;
}
hwaddr virtio_queue_get_avail_addr(VirtIODevice *vdev, int n)
{
return vdev->vq[n].vring.avail;
}
hwaddr virtio_queue_get_used_addr(VirtIODevice *vdev, int n)
{
return vdev->vq[n].vring.used;
}
hwaddr virtio_queue_get_ring_addr(VirtIODevice *vdev, int n)
{
return vdev->vq[n].vring.desc;
}
hwaddr virtio_queue_get_desc_size(VirtIODevice *vdev, int n)
{
return sizeof(VRingDesc) * vdev->vq[n].vring.num;
}
hwaddr virtio_queue_get_avail_size(VirtIODevice *vdev, int n)
{
return offsetof(VRingAvail, ring) +
sizeof(uint64_t) * vdev->vq[n].vring.num;
}
hwaddr virtio_queue_get_used_size(VirtIODevice *vdev, int n)
{
return offsetof(VRingUsed, ring) +
sizeof(VRingUsedElem) * vdev->vq[n].vring.num;
}
hwaddr virtio_queue_get_ring_size(VirtIODevice *vdev, int n)
{
return vdev->vq[n].vring.used - vdev->vq[n].vring.desc +
virtio_queue_get_used_size(vdev, n);
}
uint16_t virtio_queue_get_last_avail_idx(VirtIODevice *vdev, int n)
{
return vdev->vq[n].last_avail_idx;
}
void virtio_queue_set_last_avail_idx(VirtIODevice *vdev, int n, uint16_t idx)
{
vdev->vq[n].last_avail_idx = idx;
}
VirtQueue *virtio_get_queue(VirtIODevice *vdev, int n)
{
return vdev->vq + n;
}
uint16_t virtio_get_queue_index(VirtQueue *vq)
{
return vq->queue_index;
}
static void virtio_queue_guest_notifier_read(EventNotifier *n)
{
VirtQueue *vq = container_of(n, VirtQueue, guest_notifier);
if (event_notifier_test_and_clear(n)) {
virtio_irq(vq);
}
}
void virtio_queue_set_guest_notifier_fd_handler(VirtQueue *vq, bool assign,
bool with_irqfd)
{
if (assign && !with_irqfd) {
event_notifier_set_handler(&vq->guest_notifier,
virtio_queue_guest_notifier_read);
} else {
event_notifier_set_handler(&vq->guest_notifier, NULL);
}
if (!assign) {
/* Test and clear notifier before closing it,
* in case poll callback didn't have time to run. */
virtio_queue_guest_notifier_read(&vq->guest_notifier);
}
}
EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq)
{
return &vq->guest_notifier;
}
static void virtio_queue_host_notifier_read(EventNotifier *n)
{
VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
if (event_notifier_test_and_clear(n)) {
virtio_queue_notify_vq(vq);
}
}
void virtio_queue_set_host_notifier_fd_handler(VirtQueue *vq, bool assign,
bool set_handler)
{
if (assign && set_handler) {
event_notifier_set_handler(&vq->host_notifier,
virtio_queue_host_notifier_read);
} else {
event_notifier_set_handler(&vq->host_notifier, NULL);
}
if (!assign) {
/* Test and clear notifier before after disabling event,
* in case poll callback didn't have time to run. */
virtio_queue_host_notifier_read(&vq->host_notifier);
}
}
EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq)
{
return &vq->host_notifier;
}
void virtio_device_set_child_bus_name(VirtIODevice *vdev, char *bus_name)
{
if (vdev->bus_name) {
g_free(vdev->bus_name);
vdev->bus_name = NULL;
}
if (bus_name) {
vdev->bus_name = g_strdup(bus_name);
}
}
static int virtio_device_init(DeviceState *qdev)
{
VirtIODevice *vdev = VIRTIO_DEVICE(qdev);
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(qdev);
assert(k->init != NULL);
if (k->init(vdev) < 0) {
return -1;
}
virtio_bus_plug_device(vdev);
return 0;
}
static int virtio_device_exit(DeviceState *qdev)
{
VirtIODevice *vdev = VIRTIO_DEVICE(qdev);
if (vdev->bus_name) {
g_free(vdev->bus_name);
vdev->bus_name = NULL;
}
return 0;
}
static void virtio_device_class_init(ObjectClass *klass, void *data)
{
/* Set the default value here. */
DeviceClass *dc = DEVICE_CLASS(klass);
dc->init = virtio_device_init;
dc->exit = virtio_device_exit;
dc->bus_type = TYPE_VIRTIO_BUS;
}
static const TypeInfo virtio_device_info = {
.name = TYPE_VIRTIO_DEVICE,
.parent = TYPE_DEVICE,
.instance_size = sizeof(VirtIODevice),
.class_init = virtio_device_class_init,
.abstract = true,
.class_size = sizeof(VirtioDeviceClass),
};
static void virtio_register_types(void)
{
type_register_static(&virtio_device_info);
}
type_init(virtio_register_types)
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_5626_0 |
crossvul-cpp_data_bad_3230_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3230_0 |
crossvul-cpp_data_bad_3233_4 | /*
===========================================================================
Return to Castle Wolfenstein single player GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein single player GPL Source Code (RTCW SP Source Code).
RTCW SP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW SP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
/*****************************************************************************
* name: files.c
*
* desc: handle based filesystem for Quake III Arena
*
*
*****************************************************************************/
#include "q_shared.h"
#include "qcommon.h"
#include "../zlib-1.2.8/unzip.h"
/*
=============================================================================
QUAKE3 FILESYSTEM
All of Quake's data access is through a hierarchical file system, but the contents of
the file system can be transparently merged from several sources.
A "qpath" is a reference to game file data. MAX_ZPATH is 256 characters, which must include
a terminating zero. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any
references outside the quake directory system.
The "base path" is the path to the directory holding all the game directories and usually
the executable. It defaults to ".", but can be overridden with a "+set fs_basepath c:\quake3"
command line to allow code debugging in a different directory. Basepath cannot
be modified at all after startup. Any files that are created (demos, screenshots,
etc) will be created relative to the base path, so base path should usually be writable.
The "home path" is the path used for all write access. On win32 systems we have "base path"
== "home path", but on *nix systems the base installation is usually readonly, and
"home path" points to ~/.q3a or similar
The user can also install custom mods and content in "home path", so it should be searched
along with "home path" and "cd path" for game content.
The "base game" is the directory under the paths where data comes from by default, and
can be either "baseq3" or "demoq3".
The "current game" may be the same as the base game, or it may be the name of another
directory under the paths that should be searched for files before looking in the base game.
This is the basis for addons.
Clients automatically set the game directory after receiving a gamestate from a server,
so only servers need to worry about +set fs_game.
No other directories outside of the base game and current game will ever be referenced by
filesystem functions.
To save disk space and speed loading, directory trees can be collapsed into zip files.
The files use a ".pk3" extension to prevent users from unzipping them accidentally, but
otherwise the are simply normal uncompressed zip files. A game directory can have multiple
zip files of the form "pak0.pk3", "pak1.pk3", etc. Zip files are searched in decending order
from the highest number to the lowest, and will always take precedence over the filesystem.
This allows a pk3 distributed as a patch to override all existing data.
Because we will have updated executables freely available online, there is no point to
trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
should be exactly the same executables as release versions, but with different data that
automatically restricts where game media can come from to prevent add-ons from working.
Additionaly, we search in several subdirectories:
current game is the current mode
base game is a variable to allow mods based on other mods
(such as baseq3 + missionpack content combination in a mod for instance)
BASEGAME is the hardcoded base game ("baseq3")
e.g. the qpath "sound/newstuff/test.wav" would be searched for in the following places:
home path + current game's zip files
home path + current game's directory
base path + current game's zip files
base path + current game's directory
cd path + current game's zip files
cd path + current game's directory
home path + base game's zip file
home path + base game's directory
base path + base game's zip file
base path + base game's directory
cd path + base game's zip file
cd path + base game's directory
home path + BASEGAME's zip file
home path + BASEGAME's directory
base path + BASEGAME's zip file
base path + BASEGAME's directory
cd path + BASEGAME's zip file
cd path + BASEGAME's directory
server download, to be written to home path + current game's directory
The filesystem can be safely shutdown and reinitialized with different
basedir / cddir / game combinations, but all other subsystems that rely on it
(sound, video) must also be forced to restart.
Because the same files are loaded by both the clip model (CM_) and renderer (TR_)
subsystems, a simple single-file caching scheme is used. The CM_ subsystems will
load the file with a request to cache. Only one file will be kept cached at a time,
so any models that are going to be referenced by both subsystems should alternate
between the CM_ load function and the ref load function.
TODO: A qpath that starts with a leading slash will always refer to the base game, even if another
game is currently active. This allows character models, skins, and sounds to be downloaded
to a common directory no matter which game is active.
How to prevent downloading zip files?
Pass pk3 file names in systeminfo, and download before FS_Restart()?
Aborting a download disconnects the client from the server.
How to mark files as downloadable? Commercial add-ons won't be downloadable.
Non-commercial downloads will want to download the entire zip file.
the game would have to be reset to actually read the zip in
Auto-update information
Path separators
Casing
separate server gamedir and client gamedir, so if the user starts
a local game after having connected to a network game, it won't stick
with the network game.
allow menu options for game selection?
Read / write config to floppy option.
Different version coexistance?
When building a pak file, make sure a wolfconfig.cfg isn't present in it,
or configs will never get loaded from disk!
todo:
downloading (outside fs?)
game directory passing and restarting
=============================================================================
*/
// every time a new demo pk3 file is built, this checksum must be updated.
// the easiest way to get it is to just run the game and see what it spits out
#define DEMO_PAK0_CHECKSUM 2985661941u
static const unsigned int pak_checksums[] = {
1886207346u
};
static const unsigned int en_sppak_checksums[] = {
2837138611u,
3033901371u,
483593179u,
// sp_pak4.pk3 from GOTY edition
4131017020u
};
static const unsigned int fr_sppak_checksums[] = {
2183777857u,
3033901371u,
839012592u,
// sp_pak4.pk3 from GOTY edition
4131017020u
};
static const unsigned int gm_sppak_checksums[] = {
3078133571u,
285968110u,
2694180987u,
// sp_pak4.pk3 from GOTY edition
4131017020u
};
static const unsigned int it_sppak_checksums[] = {
3826630960u,
3033901371u,
652965486u,
// sp_pak4.pk3 from GOTY edition
4131017020u
};
static const unsigned int sp_sppak_checksums[] = {
652879493u,
3033901371u,
1162920123u,
// sp_pak4.pk3 from GOTY edition
4131017020u
};
// if this is defined, the executable positively won't work with any paks other
// than the demo pak, even if productid is present. This is only used for our
// last demo release to prevent the mac and linux users from using the demo
// executable with the production windows pak before the mac/linux products
// hit the shelves a little later
// NOW defined in build files
//#define PRE_RELEASE_TADEMO
#define MAX_ZPATH 256
#define MAX_SEARCH_PATHS 4096
#define MAX_FILEHASH_SIZE 1024
typedef struct fileInPack_s {
char *name; // name of the file
unsigned long pos; // file info position in zip
unsigned long len; // uncompress file size
struct fileInPack_s* next; // next file in the hash
} fileInPack_t;
typedef struct {
char pakPathname[MAX_OSPATH]; // c:\quake3\baseq3
char pakFilename[MAX_OSPATH]; // c:\quake3\baseq3\pak0.pk3
char pakBasename[MAX_OSPATH]; // pak0
char pakGamename[MAX_OSPATH]; // baseq3
unzFile handle; // handle to zip file
int checksum; // regular checksum
int pure_checksum; // checksum for pure
int numfiles; // number of files in pk3
int referenced; // referenced file flags
int hashSize; // hash table size (power of 2)
fileInPack_t* *hashTable; // hash table
fileInPack_t* buildBuffer; // buffer with the filenames etc.
} pack_t;
typedef struct {
char path[MAX_OSPATH]; // c:\quake3
char fullpath[MAX_OSPATH]; // c:\quake3\baseq3
char gamedir[MAX_OSPATH]; // baseq3
} directory_t;
typedef struct searchpath_s {
struct searchpath_s *next;
pack_t *pack; // only one of pack / dir will be non NULL
directory_t *dir;
} searchpath_t;
static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators
static cvar_t *fs_debug;
static cvar_t *fs_homepath;
#ifdef __APPLE__
// Also search the .app bundle for .pk3 files
static cvar_t *fs_apppath;
#endif
#ifndef STANDALONE
static cvar_t *fs_steampath;
#endif
static cvar_t *fs_basepath;
static cvar_t *fs_basegame;
static cvar_t *fs_gamedirvar;
static searchpath_t *fs_searchpaths;
static int fs_readCount; // total bytes read
static int fs_loadCount; // total files read
static int fs_loadStack; // total files in memory
static int fs_packFiles = 0; // total number of files in packs
static int fs_checksumFeed;
typedef union qfile_gus {
FILE* o;
unzFile z;
} qfile_gut;
typedef struct qfile_us {
qfile_gut file;
qboolean unique;
} qfile_ut;
typedef struct {
qfile_ut handleFiles;
qboolean handleSync;
int fileSize;
int zipFilePos;
int zipFileLen;
qboolean zipFile;
qboolean streamed;
char name[MAX_ZPATH];
} fileHandleData_t;
static fileHandleData_t fsh[MAX_FILE_HANDLES];
// TTimo - https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
// wether we did a reorder on the current search path when joining the server
static qboolean fs_reordered;
// never load anything from pk3 files that are not present at the server when pure
static int fs_numServerPaks = 0;
static int fs_serverPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverPakNames[MAX_SEARCH_PATHS]; // pk3 names
// only used for autodownload, to make sure the client has at least
// all the pk3 files that are referenced at the server side
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS]; // pk3 names
// last valid game folder used
char lastValidBase[MAX_OSPATH];
char lastValidComBaseGame[MAX_OSPATH];
char lastValidFsBaseGame[MAX_OSPATH];
char lastValidGame[MAX_OSPATH];
#ifdef FS_MISSING
FILE* missingFiles = NULL;
#endif
/* C99 defines __func__ */
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2 || _MSC_VER >= 1300
# define __func__ __FUNCTION__
# else
# define __func__ "(unknown)"
# endif
#endif
/*
==============
FS_Initialized
==============
*/
qboolean FS_Initialized( void ) {
return ( fs_searchpaths != NULL );
}
/*
=================
FS_PakIsPure
=================
*/
qboolean FS_PakIsPure( pack_t *pack ) {
int i;
if ( fs_numServerPaks ) {
// NOTE TTimo we are matching checksums without checking the pak names
// this means you can have the same pk3 as the server under a different name, you will still get through sv_pure validation
// (what happens when two pk3's have the same checkums? is it a likely situation?)
// also, if there's a wrong checksumed pk3 and autodownload is enabled, the checksum will be appended to the downloaded pk3 name
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
// FIXME: also use hashed file names
if ( pack->checksum == fs_serverPaks[i] ) {
return qtrue; // on the aproved list
}
}
return qfalse; // not on the pure server pak list
}
return qtrue;
}
/*
=================
FS_LoadStack
return load stack
=================
*/
int FS_LoadStack( void ) {
return fs_loadStack;
}
/*
================
return a hash value for the filename
================
*/
static long FS_HashFileName( const char *fname, int hashSize ) {
int i;
long hash;
char letter;
hash = 0;
i = 0;
while ( fname[i] != '\0' ) {
letter = tolower( fname[i] );
if ( letter == '.' ) {
break; // don't include extension
}
if ( letter == '\\' ) {
letter = '/'; // damn path names
}
if ( letter == PATH_SEP ) {
letter = '/'; // damn path names
}
hash += (long)( letter ) * ( i + 119 );
i++;
}
hash = ( hash ^ ( hash >> 10 ) ^ ( hash >> 20 ) );
hash &= ( hashSize - 1 );
return hash;
}
static fileHandle_t FS_HandleForFile( void ) {
int i;
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o == NULL ) {
return i;
}
}
Com_Error( ERR_DROP, "FS_HandleForFile: none free" );
return 0;
}
static FILE *FS_FileForHandle( fileHandle_t f ) {
if ( f < 1 || f >= MAX_FILE_HANDLES ) {
Com_Error( ERR_DROP, "FS_FileForHandle: out of range" );
}
if ( fsh[f].zipFile == qtrue ) {
Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" );
}
if ( !fsh[f].handleFiles.file.o ) {
Com_Error( ERR_DROP, "FS_FileForHandle: NULL" );
}
return fsh[f].handleFiles.file.o;
}
void FS_ForceFlush( fileHandle_t f ) {
FILE *file;
file = FS_FileForHandle( f );
setvbuf( file, NULL, _IONBF, 0 );
}
/*
================
FS_fplength
================
*/
long FS_fplength(FILE *h)
{
long pos;
long end;
pos = ftell(h);
fseek(h, 0, SEEK_END);
end = ftell(h);
fseek(h, pos, SEEK_SET);
return end;
}
/*
================
FS_filelength
If this is called on a non-unique FILE (from a pak file),
it will return the size of the pak file, not the expected
size of the file.
================
*/
long FS_filelength(fileHandle_t f)
{
FILE *h;
h = FS_FileForHandle( f );
if(h == NULL)
return -1;
else
return FS_fplength(h);
}
/*
====================
FS_ReplaceSeparators
Fix things up differently for win/unix/mac
====================
*/
static void FS_ReplaceSeparators( char *path ) {
char *s;
qboolean lastCharWasSep = qfalse;
for ( s = path ; *s ; s++ ) {
if ( *s == '/' || *s == '\\' ) {
if ( !lastCharWasSep ) {
*s = PATH_SEP;
lastCharWasSep = qtrue;
} else {
memmove (s, s + 1, strlen (s));
}
} else {
lastCharWasSep = qfalse;
}
}
}
/*
===================
FS_BuildOSPath
Qpath may have either forward or backwards slashes
===================
*/
char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) {
char temp[MAX_OSPATH];
static char ospath[2][MAX_OSPATH];
static int toggle;
toggle ^= 1; // flip-flop to allow two returns without clash
if ( !game || !game[0] ) {
game = fs_gamedir;
}
Com_sprintf( temp, sizeof( temp ), "/%s/%s", game, qpath );
FS_ReplaceSeparators( temp );
Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp );
return ospath[toggle];
}
/*
============
FS_CreatePath
Creates any directories needed to store the given filename
============
*/
qboolean FS_CreatePath (char *OSPath) {
char *ofs;
char path[MAX_OSPATH];
// make absolutely sure that it can't back up the path
// FIXME: is c: allowed???
if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) {
Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath );
return qtrue;
}
Q_strncpyz( path, OSPath, sizeof( path ) );
FS_ReplaceSeparators( path );
// Skip creation of the root directory as it will always be there
ofs = strchr( path, PATH_SEP );
if ( ofs != NULL ) {
ofs++;
}
for (; ofs != NULL && *ofs ; ofs++) {
if (*ofs == PATH_SEP) {
// create the directory
*ofs = 0;
if (!Sys_Mkdir (path)) {
Com_Error( ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"",
path );
}
*ofs = PATH_SEP;
}
}
return qfalse;
}
/*
=================
FS_CopyFile
Copy a fully specified file from one place to another
=================
*/
static void FS_CopyFile( char *fromOSPath, char *toOSPath ) {
FILE *f;
int len;
byte *buf;
//Com_Printf( "copy %s to %s\n", fromOSPath, toOSPath );
if ( strstr( fromOSPath, "journal.dat" ) || strstr( fromOSPath, "journaldata.dat" ) ) {
Com_Printf( "Ignoring journal files\n" );
return;
}
f = Sys_FOpen( fromOSPath, "rb" );
if ( !f ) {
return;
}
fseek( f, 0, SEEK_END );
len = ftell( f );
fseek( f, 0, SEEK_SET );
// we are using direct malloc instead of Z_Malloc here, so it
// probably won't work on a mac... Its only for developers anyway...
buf = malloc( len );
if ( fread( buf, 1, len, f ) != len ) {
Com_Error( ERR_FATAL, "Short read in FS_Copyfiles()\n" );
}
fclose( f );
if ( FS_CreatePath( toOSPath ) ) {
free( buf );
return;
}
f = Sys_FOpen( toOSPath, "wb" );
if ( !f ) {
free( buf );
return;
}
if ( fwrite( buf, 1, len, f ) != len ) {
Com_Error( ERR_FATAL, "Short write in FS_Copyfiles()\n" );
}
fclose( f );
free( buf );
}
void FS_CopyFileOS( char *from, char *to ) {
FILE *f;
int len;
byte *buf;
char *fromOSPath, *toOSPath;
fromOSPath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from );
toOSPath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to );
//Com_Printf( "copy %s to %s\n", fromOSPath, toOSPath );
if ( strstr( fromOSPath, "journal.dat" ) || strstr( fromOSPath, "journaldata.dat" ) ) {
Com_Printf( "Ignoring journal files\n" );
return;
}
f = Sys_FOpen( fromOSPath, "rb" );
if ( !f ) {
return;
}
fseek( f, 0, SEEK_END );
len = ftell( f );
fseek( f, 0, SEEK_SET );
// we are using direct malloc instead of Z_Malloc here, so it
// probably won't work on a mac... Its only for developers anyway...
buf = malloc( len );
if ( fread( buf, 1, len, f ) != len ) {
Com_Error( ERR_FATAL, "Short read in FS_Copyfiles()\n" );
}
fclose( f );
if ( FS_CreatePath( toOSPath ) ) {
free( buf );
return;
}
f = Sys_FOpen( toOSPath, "wb" );
if ( !f ) {
free( buf );
return;
}
if ( fwrite( buf, 1, len, f ) != len ) {
Com_Error( ERR_FATAL, "Short write in FS_Copyfiles()\n" );
}
fclose( f );
free( buf );
}
/*
=================
FS_CheckFilenameIsMutable
ERR_FATAL if trying to maniuplate a file with the platform library, QVM, or pk3 extension
=================
*/
static void FS_CheckFilenameIsMutable( const char *filename,
const char *function )
{
// Check if the filename ends with the library, QVM, or pk3 extension
if(COM_CompareExtension( filename, DLL_EXT )
|| COM_CompareExtension( filename, ".qvm" )
|| COM_CompareExtension( filename, ".pk3" ) )
{
Com_Error( ERR_FATAL, "%s: Not allowed to manipulate '%s' due "
"to %s extension", function, filename, COM_GetExtension( filename ) );
}
}
/*
===========
FS_Remove
===========
*/
void FS_Remove( const char *osPath ) {
FS_CheckFilenameIsMutable( osPath, __func__ );
remove( osPath );
}
/*
===========
FS_HomeRemove
===========
*/
void FS_HomeRemove( const char *homePath ) {
FS_CheckFilenameIsMutable( homePath, __func__ );
remove( FS_BuildOSPath( fs_homepath->string,
fs_gamedir, homePath ) );
}
/*
================
FS_FileInPathExists
Tests if path and file exists
================
*/
qboolean FS_FileInPathExists(const char *testpath)
{
FILE *filep;
filep = Sys_FOpen(testpath, "rb");
if(filep)
{
fclose(filep);
return qtrue;
}
return qfalse;
}
/*
================
FS_FileExists
Tests if the file exists in the current gamedir, this DOES NOT
search the paths. This is to determine if opening a file to write
(which always goes into the current gamedir) will cause any overwrites.
NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards
================
*/
qboolean FS_FileExists(const char *file)
{
return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file));
}
/*
================
FS_SV_FileExists
Tests if the file exists
================
*/
qboolean FS_SV_FileExists( const char *file )
{
char *testpath;
testpath = FS_BuildOSPath( fs_homepath->string, file, "");
testpath[strlen(testpath)-1] = '\0';
return FS_FileInPathExists(testpath);
}
/*
===========
FS_SV_FOpenFileWrite
===========
*/
fileHandle_t FS_SV_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileWrite: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_SV_FOpenFileRead
Search for a file somewhere below the home path then base path
in that order
===========
*/
long FS_SV_FOpenFileRead(const char *filename, fileHandle_t *fp)
{
char *ospath;
fileHandle_t f = 0;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
// S_ClearSoundBuffer();
// search homepath
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
// remove trailing slash
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o)
{
// If fs_homepath == fs_basepath, don't bother
if (Q_stricmp(fs_homepath->string,fs_basepath->string))
{
// search basepath
ospath = FS_BuildOSPath( fs_basepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
#ifndef STANDALONE
// Check fs_steampath too
if (!fsh[f].handleFiles.file.o && fs_steampath->string[0])
{
ospath = FS_BuildOSPath( fs_steampath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_steampath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
#endif
if ( !fsh[f].handleFiles.file.o )
{
f = 0;
}
}
*fp = f;
if (f) {
return FS_filelength(f);
}
return -1;
}
/*
===========
FS_SV_Rename
===========
*/
void FS_SV_Rename( const char *from, const char *to, qboolean safe ) {
char *from_ospath, *to_ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
// don't let sound stutter
// S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, from, "" );
to_ospath = FS_BuildOSPath( fs_homepath->string, to, "" );
from_ospath[strlen( from_ospath ) - 1] = '\0';
to_ospath[strlen( to_ospath ) - 1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath );
}
if ( safe ) {
FS_CheckFilenameIsMutable( to_ospath, __func__ );
}
if ( rename( from_ospath, to_ospath ) ) {
// Failed, try copying it and deleting the original
FS_CopyFile( from_ospath, to_ospath );
FS_Remove( from_ospath );
}
}
/*
===========
FS_Rename
===========
*/
void FS_Rename( const char *from, const char *to ) {
char *from_ospath, *to_ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
// don't let sound stutter
// S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from );
to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to );
if ( fs_debug->integer ) {
Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath );
}
FS_CheckFilenameIsMutable( to_ospath, __func__ );
if ( rename( from_ospath, to_ospath ) ) {
// Failed first attempt, try deleting destination, and renaming again
FS_Remove( to_ospath );
if ( rename( from_ospath, to_ospath ) ) {
// Failed, try copying it and deleting the original
FS_CopyFile( from_ospath, to_ospath );
FS_Remove( from_ospath );
}
}
}
/*
==============
FS_FCloseFile
If the FILE pointer is an open pak file, leave it open.
For some reason, other dll's can't just cal fclose()
on files returned by FS_FOpenFile...
==============
*/
void FS_FCloseFile( fileHandle_t f ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( fsh[f].zipFile == qtrue ) {
unzCloseCurrentFile( fsh[f].handleFiles.file.z );
if ( fsh[f].handleFiles.unique ) {
unzClose( fsh[f].handleFiles.file.z );
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
return;
}
// we didn't find it as a pak, so close it as a unique file
if ( fsh[f].handleFiles.file.o ) {
fclose( fsh[f].handleFiles.file.o );
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
}
/*
===========
FS_FOpenFileWrite
===========
*/
fileHandle_t FS_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileWrite: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if ( FS_CreatePath( ospath ) ) {
return 0;
}
// enabling the following line causes a recursive function call loop
// when running with +set logfile 1 +set developer 1
//Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if ( !fsh[f].handleFiles.file.o ) {
f = 0;
}
return f;
}
/*
===========
FS_FOpenFileAppend
===========
*/
fileHandle_t FS_FOpenFileAppend( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
// S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileAppend: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if ( FS_CreatePath( ospath ) ) {
return 0;
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "ab" );
fsh[f].handleSync = qfalse;
if ( !fsh[f].handleFiles.file.o ) {
f = 0;
}
return f;
}
/*
===========
FS_FCreateOpenPipeFile
===========
*/
fileHandle_t FS_FCreateOpenPipeFile( const char *filename ) {
char *ospath;
FILE *fifo;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
// S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FCreateOpenPipeFile: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
fifo = Sys_Mkfifo( ospath );
if( fifo ) {
fsh[f].handleFiles.file.o = fifo;
fsh[f].handleSync = qfalse;
}
else
{
Com_Printf( S_COLOR_YELLOW "WARNING: Could not create new com_pipefile at %s. "
"com_pipefile will not be used.\n", ospath );
f = 0;
}
return f;
}
/*
===========
FS_FilenameCompare
Ignore case and seprator char distinctions
===========
*/
qboolean FS_FilenameCompare( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if ( Q_islower( c1 ) ) {
c1 -= ( 'a' - 'A' );
}
if ( Q_islower( c2 ) ) {
c2 -= ( 'a' - 'A' );
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if ( c1 != c2 ) {
return qtrue; // strings not equal
}
} while ( c1 );
return qfalse; // strings are equal
}
/*
===========
FS_FileCompare
Do a binary check of the two files, return qfalse if they are different, otherwise qtrue
===========
*/
qboolean FS_FileCompare( const char *s1, const char *s2 ) {
FILE *f1, *f2;
int len1, len2, pos;
byte *b1, *b2, *p1, *p2;
f1 = fopen( s1, "rb" );
if ( !f1 ) {
Com_Error( ERR_FATAL, "FS_FileCompare: %s does not exist\n", s1 );
}
f2 = fopen( s2, "rb" );
if ( !f2 ) { // this file is allowed to not be there, since it might not exist in the previous build
fclose( f1 );
return qfalse;
//Com_Error( ERR_FATAL, "FS_FileCompare: %s does not exist\n", s2 );
}
// first do a length test
pos = ftell( f1 );
fseek( f1, 0, SEEK_END );
len1 = ftell( f1 );
fseek( f1, pos, SEEK_SET );
pos = ftell( f2 );
fseek( f2, 0, SEEK_END );
len2 = ftell( f2 );
fseek( f2, pos, SEEK_SET );
if ( len1 != len2 ) {
fclose( f1 );
fclose( f2 );
return qfalse;
}
// now do a binary compare
b1 = malloc( len1 );
if ( fread( b1, 1, len1, f1 ) != len1 ) {
Com_Error( ERR_FATAL, "Short read in FS_FileCompare()\n" );
}
fclose( f1 );
b2 = malloc( len2 );
if ( fread( b2, 1, len2, f2 ) != len2 ) {
Com_Error( ERR_FATAL, "Short read in FS_FileCompare()\n" );
}
fclose( f2 );
//if (!memcmp(b1, b2, (int)min(len1,len2) )) {
p1 = b1;
p2 = b2;
for ( pos = 0; pos < len1; pos++, p1++, p2++ )
{
if ( *p1 != *p2 ) {
free( b1 );
free( b2 );
return qfalse;
}
}
//}
// they are identical
free( b1 );
free( b2 );
return qtrue;
}
/*
===========
FS_IsExt
Return qtrue if ext matches file extension filename
===========
*/
qboolean FS_IsExt(const char *filename, const char *ext, int namelen)
{
int extlen;
extlen = strlen(ext);
if(extlen > namelen)
return qfalse;
filename += namelen - extlen;
return !Q_stricmp(filename, ext);
}
/*
===========
FS_IsDemoExt
Return qtrue if filename has a demo extension
===========
*/
qboolean FS_IsDemoExt(const char *filename, int namelen)
{
char *ext_test;
int index, protocol;
ext_test = strrchr(filename, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMOEXT, ARRAY_LEN(DEMOEXT) - 1))
{
protocol = atoi(ext_test + ARRAY_LEN(DEMOEXT));
if(protocol == com_protocol->integer)
return qtrue;
#ifdef LEGACY_PROTOCOL
if(protocol == com_legacyprotocol->integer)
return qtrue;
#endif
for(index = 0; demo_protocols[index]; index++)
{
if(demo_protocols[index] == protocol)
return qtrue;
}
}
return qfalse;
}
/*
===========
FS_FOpenFileReadDir
Tries opening file "filename" in searchpath "search"
Returns filesize and an open FILE pointer.
===========
*/
extern qboolean com_fullyInitialized;
long FS_FOpenFileReadDir(const char *filename, searchpath_t *search, fileHandle_t *file, qboolean uniqueFILE, qboolean unpure)
{
long hash;
pack_t *pak;
fileInPack_t *pakFile;
directory_t *dir;
char *netpath;
FILE *filep;
int len;
if(filename == NULL)
Com_Error(ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed");
// qpaths are not supposed to have a leading slash
if(filename[0] == '/' || filename[0] == '\\')
filename++;
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if(strstr(filename, ".." ) || strstr(filename, "::"))
{
if(file == NULL)
return qfalse;
*file = 0;
return -1;
}
// make sure the rtcwkey file is only readable by the iortcw.exe at initialization
// any other time the key should only be accessed in memory using the provided functions
if(com_fullyInitialized && strstr(filename, "rtcwkey"))
{
if(file == NULL)
return qfalse;
*file = 0;
return -1;
}
if(file == NULL)
{
// just wants to see if file is there
// is the element a pak file?
if(search->pack)
{
hash = FS_HashFileName(filename, search->pack->hashSize);
if(search->pack->hashTable[hash])
{
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do
{
// case and separator insensitive comparisons
if(!FS_FilenameCompare(pakFile->name, filename))
{
// found it!
if(pakFile->len)
return pakFile->len;
else
{
// It's not nice, but legacy code depends
// on positive value if file exists no matter
// what size
return 1;
}
}
pakFile = pakFile->next;
} while ( pakFile != NULL );
}
}
else if(search->dir)
{
dir = search->dir;
netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
filep = Sys_FOpen(netpath, "rb");
if(filep)
{
len = FS_fplength(filep);
fclose(filep);
if(len)
return len;
else
return 1;
}
}
return 0;
}
*file = FS_HandleForFile();
fsh[*file].handleFiles.unique = uniqueFILE;
// is the element a pak file?
if(search->pack)
{
hash = FS_HashFileName(filename, search->pack->hashSize);
if(search->pack->hashTable[hash])
{
// disregard if it doesn't match one of the allowed pure pak files
if(!unpure && !FS_PakIsPure(search->pack))
{
*file = 0;
return -1;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do
{
// case and separator insensitive comparisons
if(!FS_FilenameCompare(pakFile->name, filename))
{
// found it!
// mark the pak as having been referenced and mark specifics on cgame and ui
// shaders, txt, arena files by themselves do not count as a reference as
// these are loaded from all pk3s
// from every pk3 file..
len = strlen(filename);
if (!(pak->referenced & FS_GENERAL_REF))
{
if(!FS_IsExt(filename, ".shader", len) &&
!FS_IsExt(filename, ".txt", len) &&
!FS_IsExt(filename, ".cfg", len) &&
!FS_IsExt(filename, ".config", len) &&
!FS_IsExt(filename, ".bot", len) &&
!FS_IsExt(filename, ".arena", len) &&
!FS_IsExt(filename, ".menu", len) &&
!strstr(filename, "levelshots"))
{
pak->referenced |= FS_GENERAL_REF;
}
}
if(strstr(filename, Sys_GetDLLName( "cgame" )))
pak->referenced |= FS_CGAME_REF;
if(strstr(filename, Sys_GetDLLName( "ui" )))
pak->referenced |= FS_UI_REF;
if(strstr(filename, "cgame.sp.qvm"))
pak->referenced |= FS_CGAME_REF;
if(strstr(filename, "ui.sp.qvm"))
pak->referenced |= FS_UI_REF;
if(uniqueFILE)
{
// open a new file on the pakfile
fsh[*file].handleFiles.file.z = unzOpen(pak->pakFilename);
if(fsh[*file].handleFiles.file.z == NULL)
Com_Error(ERR_FATAL, "Couldn't open %s", pak->pakFilename);
}
else
fsh[*file].handleFiles.file.z = pak->handle;
Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
fsh[*file].zipFile = qtrue;
// set the file position in the zip file (also sets the current file info)
unzSetOffset(fsh[*file].handleFiles.file.z, pakFile->pos);
// open the file in the zip
unzOpenCurrentFile(fsh[*file].handleFiles.file.z);
fsh[*file].zipFilePos = pakFile->pos;
fsh[*file].zipFileLen = pakFile->len;
if(fs_debug->integer)
{
Com_Printf("FS_FOpenFileRead: %s (found in '%s')\n",
filename, pak->pakFilename);
}
return pakFile->len;
}
pakFile = pakFile->next;
} while ( pakFile != NULL );
}
}
else if(search->dir)
{
// check a file in the directory tree
// if we are running restricted, the only files we
// will allow to come from the directory are .cfg files
len = strlen(filename);
// FIXME TTimo I'm not sure about the fs_numServerPaks test
// if you are using FS_ReadFile to find out if a file exists,
// this test can make the search fail although the file is in the directory
// I had the problem on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8
// turned out I used FS_FileExists instead
if(!unpure && fs_numServerPaks)
{
if(!FS_IsExt(filename, ".cfg", len) && // for config files
// !FS_IsExt(filename, ".menu", len) && // menu files
!FS_IsExt(filename, ".svg", len) && // savegames
!FS_IsExt(filename, ".game", len) && // menu files
!FS_IsExt(filename, ".dat", len) && // for journal files
!FS_IsDemoExt(filename, len)) // demos
{
*file = 0;
return -1;
}
}
dir = search->dir;
netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
filep = Sys_FOpen(netpath, "rb");
if (filep == NULL)
{
*file = 0;
return -1;
}
Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
fsh[*file].zipFile = qfalse;
if(fs_debug->integer)
{
Com_Printf("FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename,
dir->path, PATH_SEP, dir->gamedir);
}
fsh[*file].handleFiles.file.o = filep;
return FS_fplength(filep);
}
*file = 0;
return -1;
}
/*
===========
FS_FOpenFileRead
Finds the file in the search path.
Returns filesize and an open FILE pointer.
Used for streaming data out of either a
separate file or a ZIP file.
===========
*/
long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE)
{
searchpath_t *search;
long len;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
for(search = fs_searchpaths; search; search = search->next)
{
len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse);
if(file == NULL)
{
if(len > 0)
return len;
}
else
{
if(len >= 0 && *file)
return len;
}
}
#ifdef FS_MISSING
if(missingFiles)
fprintf(missingFiles, "%s\n", filename);
#endif
if(file)
{
*file = 0;
return -1;
}
else
{
// When file is NULL, we're querying the existance of the file
// If we've got here, it doesn't exist
return 0;
}
}
/*
=================
FS_FindVM
Find a suitable VM file in search path order.
In each searchpath try:
- open DLL file if DLL loading enabled
- open QVM file
Enable search for DLL by setting enableDll to FSVM_ENABLEDLL
write found DLL or QVM to "found" and return VMI_NATIVE if DLL, VMI_COMPILED if QVM
Return the searchpath in "startSearch".
=================
*/
int FS_FindVM(void **startSearch, char *found, int foundlen, const char *name, int enableDll)
{
searchpath_t *search, *lastSearch;
directory_t *dir;
pack_t *pack;
char dllName[MAX_OSPATH], qvmName[MAX_OSPATH];
char *netpath;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
if(enableDll)
Q_strncpyz(dllName, Sys_GetDLLName(name), sizeof(dllName));
Com_sprintf(qvmName, sizeof(qvmName), "vm/%s.sp.qvm", name);
lastSearch = *startSearch;
if(*startSearch == NULL)
search = fs_searchpaths;
else
search = lastSearch->next;
while(search)
{
if(search->dir && !fs_numServerPaks)
{
dir = search->dir;
if(enableDll)
{
netpath = FS_BuildOSPath(dir->path, dir->gamedir, dllName);
if(FS_FileInPathExists(netpath))
{
Q_strncpyz(found, netpath, foundlen);
*startSearch = search;
return VMI_NATIVE;
}
}
if(FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, qfalse) > 0)
{
*startSearch = search;
return VMI_COMPILED;
}
}
else if(search->pack)
{
pack = search->pack;
if(lastSearch && lastSearch->pack)
{
// make sure we only try loading one VM file per game dir
// i.e. if VM from pak7.pk3 fails we won't try one from pak6.pk3
if(!FS_FilenameCompare(lastSearch->pack->pakPathname, pack->pakPathname))
{
search = search->next;
continue;
}
}
if(FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, qfalse) > 0)
{
*startSearch = search;
return VMI_COMPILED;
}
}
search = search->next;
}
return -1;
}
/*
==============
FS_Delete
TTimo - this was not in the 1.30 filesystem code
using fs_homepath for the file to remove
==============
*/
int FS_Delete( char *filename ) {
char *ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !filename || filename[0] == 0 ) {
return 0;
}
// for safety, only allow deletion from the save directory
if ( Q_strncmp( filename, "save/", 5 ) != 0 ) {
return 0;
}
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( remove( ospath ) != -1 ) { // success
return 1;
}
return 0;
}
/*
=================
FS_Read2
Properly handles partial reads
=================
*/
int FS_Read2( void *buffer, int len, fileHandle_t f ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !f ) {
return 0;
}
if ( fsh[f].streamed ) {
int r;
fsh[f].streamed = qfalse;
r = FS_Read( buffer, len, f );
fsh[f].streamed = qtrue;
return r;
} else {
return FS_Read( buffer, len, f );
}
}
int FS_Read( void *buffer, int len, fileHandle_t f ) {
int block, remaining;
int read;
byte *buf;
int tries;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !f ) {
return 0;
}
buf = (byte *)buffer;
fs_readCount += len;
if ( fsh[f].zipFile == qfalse ) {
remaining = len;
tries = 0;
while ( remaining ) {
block = remaining;
read = fread( buf, 1, block, fsh[f].handleFiles.file.o );
if ( read == 0 ) {
// we might have been trying to read from a CD, which
// sometimes returns a 0 read on windows
if ( !tries ) {
tries = 1;
} else {
return len - remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read");
}
}
if ( read == -1 ) {
Com_Error( ERR_FATAL, "FS_Read: -1 bytes read" );
}
remaining -= read;
buf += read;
}
return len;
} else {
return unzReadCurrentFile( fsh[f].handleFiles.file.z, buffer, len );
}
}
/*
=================
FS_Write
Properly handles partial writes
=================
*/
int FS_Write( const void *buffer, int len, fileHandle_t h ) {
int block, remaining;
int written;
byte *buf;
int tries;
FILE *f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !h ) {
return 0;
}
f = FS_FileForHandle( h );
buf = (byte *)buffer;
remaining = len;
tries = 0;
while ( remaining ) {
block = remaining;
written = fwrite( buf, 1, block, f );
if ( written == 0 ) {
if ( !tries ) {
tries = 1;
} else {
Com_Printf( "FS_Write: 0 bytes written\n" );
return 0;
}
}
if ( written == -1 ) {
Com_Printf( "FS_Write: -1 bytes written\n" );
return 0;
}
remaining -= written;
buf += written;
}
if ( fsh[h].handleSync ) {
fflush( f );
}
return len;
}
#define MAXPRINTMSG 4096
void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof( msg ), fmt, argptr );
va_end( argptr );
FS_Write( msg, strlen( msg ), h );
}
#define PK3_SEEK_BUFFER_SIZE 65536
/*
=================
FS_Seek
=================
*/
int FS_Seek( fileHandle_t f, long offset, int origin ) {
int _origin;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
return -1;
}
if ( fsh[f].streamed ) {
int r;
fsh[f].streamed = qfalse;
r = FS_Seek( f, offset, origin );
fsh[f].streamed = qtrue;
return r;
}
if ( fsh[f].zipFile == qtrue ) {
//FIXME: this is really, really crappy
//(but better than what was here before)
byte buffer[PK3_SEEK_BUFFER_SIZE];
int remainder;
int currentPosition = FS_FTell( f );
// change negative offsets into FS_SEEK_SET
if ( offset < 0 ) {
switch( origin ) {
case FS_SEEK_END:
remainder = fsh[f].zipFileLen + offset;
break;
case FS_SEEK_CUR:
remainder = currentPosition + offset;
break;
case FS_SEEK_SET:
default:
remainder = 0;
break;
}
if ( remainder < 0 ) {
remainder = 0;
}
origin = FS_SEEK_SET;
} else {
if ( origin == FS_SEEK_END ) {
remainder = fsh[f].zipFileLen - currentPosition + offset;
} else {
remainder = offset;
}
}
switch( origin ) {
case FS_SEEK_SET:
if ( remainder == currentPosition ) {
return offset;
}
unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
unzOpenCurrentFile(fsh[f].handleFiles.file.z);
//fallthrough
case FS_SEEK_END:
case FS_SEEK_CUR:
while( remainder > PK3_SEEK_BUFFER_SIZE ) {
FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f );
remainder -= PK3_SEEK_BUFFER_SIZE;
}
FS_Read( buffer, remainder, f );
return offset;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
return -1;
}
} else {
FILE *file;
file = FS_FileForHandle( f );
switch ( origin ) {
case FS_SEEK_CUR:
_origin = SEEK_CUR;
break;
case FS_SEEK_END:
_origin = SEEK_END;
break;
case FS_SEEK_SET:
_origin = SEEK_SET;
break;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
break;
}
return fseek( file, offset, _origin );
}
}
/*
======================================================================================
CONVENIENCE FUNCTIONS FOR ENTIRE FILES
======================================================================================
*/
int FS_FileIsInPAK( const char *filename, int *pChecksum ) {
searchpath_t *search;
pack_t *pak;
fileInPack_t *pakFile;
long hash = 0;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !filename ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed" );
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
return -1;
}
//
// search through the path, one element at a time
//
for ( search = fs_searchpaths ; search ; search = search->next ) {
//
if ( search->pack ) {
hash = FS_HashFileName( filename, search->pack->hashSize );
}
// is the element a pak file?
if ( search->pack && search->pack->hashTable[hash] ) {
// disregard if it doesn't match one of the allowed pure pak files
if ( !FS_PakIsPure( search->pack ) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
if ( pChecksum ) {
*pChecksum = pak->pure_checksum;
}
return 1;
}
pakFile = pakFile->next;
} while ( pakFile != NULL );
}
}
return -1;
}
/*
============
FS_ReadFileDir
Filename are relative to the quake search path
a null buffer will just return the file length without loading
If searchPath is non-NULL search only in that specific search path
============
*/
long FS_ReadFileDir(const char *qpath, void *searchPath, qboolean unpure, void **buffer)
{
fileHandle_t h;
searchpath_t *search;
byte* buf;
qboolean isConfig;
long len;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !qpath || !qpath[0] ) {
Com_Error( ERR_FATAL, "FS_ReadFile with empty name" );
}
buf = NULL; // quiet compiler warning
// if this is a .cfg file and we are playing back a journal, read
// it from the journal file
if ( strstr( qpath, ".cfg" ) ) {
isConfig = qtrue;
if ( com_journal && com_journal->integer == 2 ) {
int r;
Com_DPrintf( "Loading %s from journal file.\n", qpath );
r = FS_Read( &len, sizeof( len ), com_journalDataFile );
if ( r != sizeof( len ) ) {
if ( buffer != NULL ) {
*buffer = NULL;
}
return -1;
}
// if the file didn't exist when the journal was created
if ( !len ) {
if ( buffer == NULL ) {
return 1; // hack for old journal files
}
*buffer = NULL;
return -1;
}
if ( buffer == NULL ) {
return len;
}
buf = Hunk_AllocateTempMemory( len + 1 );
*buffer = buf;
r = FS_Read( buf, len, com_journalDataFile );
if ( r != len ) {
Com_Error( ERR_FATAL, "Read from journalDataFile failed" );
}
fs_loadCount++;
fs_loadStack++;
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
return len;
}
} else {
isConfig = qfalse;
}
search = searchPath;
if(search == NULL)
{
// look for it in the filesystem or pack files
len = FS_FOpenFileRead(qpath, &h, qfalse);
}
else
{
// look for it in a specific search path only
len = FS_FOpenFileReadDir(qpath, search, &h, qfalse, unpure);
}
if ( h == 0 ) {
if ( buffer ) {
*buffer = NULL;
}
// if we are journalling and it is a config file, write a zero to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing zero for %s to journal file.\n", qpath );
len = 0;
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return -1;
}
if ( !buffer ) {
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing len for %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
FS_FCloseFile( h );
return len;
}
fs_loadCount++;
fs_loadStack++;
buf = Hunk_AllocateTempMemory( len + 1 );
*buffer = buf;
FS_Read( buf, len, h );
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
FS_FCloseFile( h );
// if we are journalling and it is a config file, write it to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Write( buf, len, com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return len;
}
/*
============
FS_ReadFile
Filename are relative to the quake search path
a null buffer will just return the file length without loading
============
*/
long FS_ReadFile(const char *qpath, void **buffer)
{
return FS_ReadFileDir(qpath, NULL, qfalse, buffer);
}
/*
=============
FS_FreeFile
=============
*/
void FS_FreeFile( void *buffer ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !buffer ) {
Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" );
}
fs_loadStack--;
Hunk_FreeTempMemory( buffer );
// if all of our temp files are free, clear all of our space
if ( fs_loadStack == 0 ) {
Hunk_ClearTempMemory();
}
}
/*
============
FS_WriteFile
Filename are relative to the quake search path
============
*/
void FS_WriteFile( const char *qpath, const void *buffer, int size ) {
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !qpath || !buffer ) {
Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" );
}
f = FS_FOpenFileWrite( qpath );
if ( !f ) {
Com_Printf( "Failed to open %s\n", qpath );
return;
}
FS_Write( buffer, size, f );
FS_FCloseFile( f );
}
/*
==========================================================================
ZIP FILE LOADING
==========================================================================
*/
/*
=================
FS_LoadZipFile
Creates a new pak_t in the search chain for the contents
of a zip file.
=================
*/
static pack_t *FS_LoadZipFile(const char *zipfile, const char *basename)
{
fileInPack_t *buildBuffer;
pack_t *pack;
unzFile uf;
int err;
unz_global_info gi;
char filename_inzip[MAX_ZPATH];
unz_file_info file_info;
int i, len;
long hash;
int fs_numHeaderLongs;
int *fs_headerLongs;
char *namePtr;
fs_numHeaderLongs = 0;
uf = unzOpen( zipfile );
err = unzGetGlobalInfo( uf,&gi );
if ( err != UNZ_OK ) {
return NULL;
}
fs_packFiles += gi.number_entry;
len = 0;
unzGoToFirstFile( uf );
for ( i = 0; i < gi.number_entry; i++ )
{
err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 );
if ( err != UNZ_OK ) {
break;
}
len += strlen( filename_inzip ) + 1;
unzGoToNextFile( uf );
}
buildBuffer = Z_Malloc( ( gi.number_entry * sizeof( fileInPack_t ) ) + len );
namePtr = ( (char *) buildBuffer ) + gi.number_entry * sizeof( fileInPack_t );
fs_headerLongs = Z_Malloc( ( gi.number_entry + 1 ) * sizeof(int) );
fs_headerLongs[ fs_numHeaderLongs++ ] = LittleLong( fs_checksumFeed );
// get the hash table size from the number of files in the zip
// because lots of custom pk3 files have less than 32 or 64 files
for ( i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1 ) {
if ( i > gi.number_entry ) {
break;
}
}
pack = Z_Malloc( sizeof( pack_t ) + i * sizeof( fileInPack_t * ) );
pack->hashSize = i;
pack->hashTable = ( fileInPack_t ** )( ( (char *) pack ) + sizeof( pack_t ) );
for ( i = 0; i < pack->hashSize; i++ ) {
pack->hashTable[i] = NULL;
}
Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) );
Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) );
// strip .pk3 if needed
if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) {
pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0;
}
pack->handle = uf;
pack->numfiles = gi.number_entry;
unzGoToFirstFile( uf );
for ( i = 0; i < gi.number_entry; i++ )
{
err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 );
if ( err != UNZ_OK ) {
break;
}
if ( file_info.uncompressed_size > 0 ) {
fs_headerLongs[fs_numHeaderLongs++] = LittleLong( file_info.crc );
}
Q_strlwr( filename_inzip );
hash = FS_HashFileName( filename_inzip, pack->hashSize );
buildBuffer[i].name = namePtr;
strcpy( buildBuffer[i].name, filename_inzip );
namePtr += strlen( filename_inzip ) + 1;
// store the file position in the zip
buildBuffer[i].pos = unzGetOffset(uf);
buildBuffer[i].len = file_info.uncompressed_size;
buildBuffer[i].next = pack->hashTable[hash];
pack->hashTable[hash] = &buildBuffer[i];
unzGoToNextFile( uf );
}
pack->checksum = Com_BlockChecksum( &fs_headerLongs[ 1 ], sizeof(*fs_headerLongs) * ( fs_numHeaderLongs - 1 ) );
pack->pure_checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs );
pack->checksum = LittleLong( pack->checksum );
pack->pure_checksum = LittleLong( pack->pure_checksum );
Z_Free( fs_headerLongs );
pack->buildBuffer = buildBuffer;
return pack;
}
/*
=================
FS_FreePak
Frees a pak structure and releases all associated resources
=================
*/
static void FS_FreePak(pack_t *thepak)
{
unzClose(thepak->handle);
Z_Free(thepak->buildBuffer);
Z_Free(thepak);
}
/*
=================
FS_GetZipChecksum
Compares whether the given pak file matches a referenced checksum
=================
*/
qboolean FS_CompareZipChecksum(const char *zipfile)
{
pack_t *thepak;
int index, checksum;
thepak = FS_LoadZipFile(zipfile, "");
if(!thepak)
return qfalse;
checksum = thepak->checksum;
FS_FreePak(thepak);
for(index = 0; index < fs_numServerReferencedPaks; index++)
{
if(checksum == fs_serverReferencedPaks[index])
return qtrue;
}
return qfalse;
}
/*
=================================================================================
DIRECTORY SCANNING FUNCTIONS
=================================================================================
*/
#define MAX_FOUND_FILES 0x1000
static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) {
int len, at, newdep;
newdep = 0;
zpath[0] = 0;
len = 0;
at = 0;
while ( zname[at] != 0 )
{
if ( zname[at] == '/' || zname[at] == '\\' ) {
len = at;
newdep++;
}
at++;
}
strcpy( zpath, zname );
zpath[len] = 0;
*depth = newdep;
return len;
}
/*
==================
FS_AddFileToList
==================
*/
static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) {
int i;
if ( nfiles == MAX_FOUND_FILES - 1 ) {
return nfiles;
}
for ( i = 0 ; i < nfiles ; i++ ) {
if ( !Q_stricmp( name, list[i] ) ) {
return nfiles; // allready in list
}
}
list[nfiles] = CopyString( name );
nfiles++;
return nfiles;
}
/*
===============
FS_ListFilteredFiles
Returns a uniqued list of files that match the given criteria
from all search paths
===============
*/
char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles, qboolean allowNonPureFilesOnDisk ) {
int nfiles;
char **listCopy;
char *list[MAX_FOUND_FILES];
searchpath_t *search;
int i;
int pathLength;
int extensionLength;
int length, pathDepth, temp;
pack_t *pak;
fileInPack_t *buildBuffer;
char zpath[MAX_ZPATH];
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !path ) {
*numfiles = 0;
return NULL;
}
if ( !extension ) {
extension = "";
}
pathLength = strlen( path );
if ( path[pathLength - 1] == '\\' || path[pathLength - 1] == '/' ) {
pathLength--;
}
extensionLength = strlen( extension );
nfiles = 0;
FS_ReturnPath( path, zpath, &pathDepth );
//
// search through the path, one element at a time, adding to list
//
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
//ZOID: If we are pure, don't search for files on paks that
// aren't on the pure list
if ( !FS_PakIsPure( search->pack ) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
buildBuffer = pak->buildBuffer;
for ( i = 0; i < pak->numfiles; i++ ) {
char *name;
int zpathLen, depth;
// check for directory match
name = buildBuffer[i].name;
//
if ( filter ) {
// case insensitive
if ( !Com_FilterPath( filter, name, qfalse ) ) {
continue;
}
// unique the match
nfiles = FS_AddFileToList( name, list, nfiles );
} else {
zpathLen = FS_ReturnPath( name, zpath, &depth );
if ( ( depth - pathDepth ) > 2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) {
continue;
}
// check for extension match
length = strlen( name );
if ( length < extensionLength ) {
continue;
}
if ( Q_stricmp( name + length - extensionLength, extension ) ) {
continue;
}
// unique the match
temp = pathLength;
if ( pathLength ) {
temp++; // include the '/'
}
nfiles = FS_AddFileToList( name + temp, list, nfiles );
}
}
} else if ( search->dir ) { // scan for files in the filesystem
char *netpath;
int numSysFiles;
char **sysFiles;
char *name;
// don't scan directories for files if we are pure or restricted
// allow listing of savegames for the demo menus
if ( fs_numServerPaks && !allowNonPureFilesOnDisk && Q_stricmp( extension, "svg" ) ) {
continue;
} else {
netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path );
sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse );
for ( i = 0 ; i < numSysFiles ; i++ ) {
// unique the match
name = sysFiles[i];
nfiles = FS_AddFileToList( name, list, nfiles );
}
Sys_FreeFileList( sysFiles );
}
}
}
// return a copy of the list
*numfiles = nfiles;
if ( !nfiles ) {
return NULL;
}
listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
for ( i = 0 ; i < nfiles ; i++ ) {
listCopy[i] = list[i];
}
listCopy[i] = NULL;
return listCopy;
}
/*
=================
FS_ListFiles
=================
*/
char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) {
return FS_ListFilteredFiles( path, extension, NULL, numfiles, qfalse );
}
/*
=================
FS_FreeFileList
=================
*/
void FS_FreeFileList( char **list ) {
int i;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !list ) {
return;
}
for ( i = 0 ; list[i] ; i++ ) {
Z_Free( list[i] );
}
Z_Free( list );
}
/*
================
FS_GetFileList
================
*/
int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
int nFiles, i, nTotal, nLen;
char **pFiles = NULL;
*listbuf = 0;
nFiles = 0;
nTotal = 0;
if ( Q_stricmp( path, "$modlist" ) == 0 ) {
return FS_GetModList( listbuf, bufsize );
}
pFiles = FS_ListFiles( path, extension, &nFiles );
for ( i = 0; i < nFiles; i++ ) {
nLen = strlen( pFiles[i] ) + 1;
if ( nTotal + nLen + 1 < bufsize ) {
strcpy( listbuf, pFiles[i] );
listbuf += nLen;
nTotal += nLen;
} else {
nFiles = i;
break;
}
}
FS_FreeFileList( pFiles );
return nFiles;
}
/*
=======================
Sys_ConcatenateFileLists
mkv: Naive implementation. Concatenates three lists into a
new list, and frees the old lists from the heap.
bk001129 - from cvs1.17 (mkv)
FIXME TTimo those two should move to common.c next to Sys_ListFiles
=======================
*/
static unsigned int Sys_CountFileList( char **list ) {
int i = 0;
if (list)
{
while (*list)
{
list++;
i++;
}
}
return i;
}
static char** Sys_ConcatenateFileLists( char **list0, char **list1 )
{
int totalLength = 0;
char** cat = NULL, **dst, **src;
totalLength += Sys_CountFileList(list0);
totalLength += Sys_CountFileList(list1);
/* Create new list. */
dst = cat = Z_Malloc( ( totalLength + 1 ) * sizeof( char* ) );
/* Copy over lists. */
if (list0)
{
for (src = list0; *src; src++, dst++)
*dst = *src;
}
if (list1)
{
for (src = list1; *src; src++, dst++)
*dst = *src;
}
// Terminate the list
*dst = NULL;
// Free our old lists.
// NOTE: not freeing their content, it's been merged in dst and still being used
if (list0) Z_Free( list0 );
if (list1) Z_Free( list1 );
return cat;
}
/*
================
FS_GetModDescription
================
*/
void FS_GetModDescription( const char *modDir, char *description, int descriptionLen ) {
fileHandle_t descHandle;
char descPath[MAX_QPATH];
int nDescLen;
FILE *file;
Com_sprintf( descPath, sizeof ( descPath ), "%s/description.txt", modDir );
nDescLen = FS_SV_FOpenFileRead( descPath, &descHandle );
if ( nDescLen > 0 && descHandle ) {
file = FS_FileForHandle(descHandle);
Com_Memset( description, 0, descriptionLen );
nDescLen = fread(description, 1, descriptionLen, file);
if (nDescLen >= 0) {
description[nDescLen] = '\0';
}
FS_FCloseFile(descHandle);
} else {
Q_strncpyz( description, modDir, descriptionLen );
}
}
/*
================
FS_GetModList
Returns a list of mod directory names
A mod directory is a peer to baseq3 with a pk3 in it
The directories are searched in base path, cd path and home path
================
*/
int FS_GetModList( char *listbuf, int bufsize ) {
int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen;
char **pFiles = NULL;
char **pPaks = NULL;
char *name, *path;
char description[MAX_OSPATH];
int dummy;
char **pFiles0 = NULL;
char **pFiles1 = NULL;
#ifndef STANDALONE
char **pFiles2 = NULL;
char **pFiles3 = NULL;
#endif
qboolean bDrop = qfalse;
*listbuf = 0;
nMods = nTotal = 0;
pFiles0 = Sys_ListFiles( fs_homepath->string, NULL, NULL, &dummy, qtrue );
pFiles1 = Sys_ListFiles( fs_basepath->string, NULL, NULL, &dummy, qtrue );
#ifndef STANDALONE
pFiles2 = Sys_ListFiles( fs_steampath->string, NULL, NULL, &dummy, qtrue );
#endif
// we searched for mods in the three paths
// it is likely that we have duplicate names now, which we will cleanup below
#ifndef STANDALONE
pFiles3 = Sys_ConcatenateFileLists( pFiles0, pFiles1 );
pFiles = Sys_ConcatenateFileLists( pFiles2, pFiles3 );
#else
pFiles = Sys_ConcatenateFileLists( pFiles0, pFiles1 );
#endif
nPotential = Sys_CountFileList(pFiles);
for ( i = 0 ; i < nPotential ; i++ ) {
name = pFiles[i];
// NOTE: cleaner would involve more changes
// ignore duplicate mod directories
if (i!=0) {
bDrop = qfalse;
for(j=0; j<i; j++)
{
if (Q_stricmp(pFiles[j],name)==0) {
// this one can be dropped
bDrop = qtrue;
break;
}
}
}
if (bDrop) {
continue;
}
// we drop "baseq3" "." and ".."
if (Q_stricmp(name, com_basegame->string) && Q_stricmpn(name, ".", 1)) {
// now we need to find some .pk3 files to validate the mod
// NOTE TTimo: (actually I'm not sure why .. what if it's a mod under developement with no .pk3?)
// we didn't keep the information when we merged the directory names, as to what OS Path it was found under
// so it could be in base path, cd path or home path
// we will try each three of them here (yes, it's a bit messy)
path = FS_BuildOSPath( fs_basepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse);
Sys_FreeFileList( pPaks ); // we only use Sys_ListFiles to check wether .pk3 files are present
/* try on home path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_homepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
#ifndef STANDALONE
/* try on steam path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_steampath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
#endif
if (nPaks > 0) {
nLen = strlen(name) + 1;
// nLen is the length of the mod path
// we need to see if there is a description available
FS_GetModDescription( name, description, sizeof( description ) );
nDescLen = strlen(description) + 1;
if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) {
strcpy(listbuf, name);
listbuf += nLen;
strcpy(listbuf, description);
listbuf += nDescLen;
nTotal += nLen + nDescLen;
nMods++;
}
else {
break;
}
}
}
}
Sys_FreeFileList( pFiles );
return nMods;
}
//============================================================================
/*
================
FS_Dir_f
================
*/
void FS_Dir_f( void ) {
char *path;
char *extension;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) {
Com_Printf( "usage: dir <directory> [extension]\n" );
return;
}
if ( Cmd_Argc() == 2 ) {
path = Cmd_Argv( 1 );
extension = "";
} else {
path = Cmd_Argv( 1 );
extension = Cmd_Argv( 2 );
}
Com_Printf( "Directory of %s %s\n", path, extension );
Com_Printf( "---------------\n" );
dirnames = FS_ListFiles( path, extension, &ndirs );
for ( i = 0; i < ndirs; i++ ) {
Com_Printf( "%s\n", dirnames[i] );
}
FS_FreeFileList( dirnames );
}
/*
===========
FS_ConvertPath
===========
*/
void FS_ConvertPath( char *s ) {
while ( *s ) {
if ( *s == '\\' || *s == ':' ) {
*s = '/';
}
s++;
}
}
/*
===========
FS_PathCmp
Ignore case and seprator char distinctions
===========
*/
int FS_PathCmp( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if ( Q_islower( c1 ) ) {
c1 -= ( 'a' - 'A' );
}
if ( Q_islower( c2 ) ) {
c2 -= ( 'a' - 'A' );
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if ( c1 < c2 ) {
return -1; // strings not equal
}
if ( c1 > c2 ) {
return 1;
}
} while ( c1 );
return 0; // strings are equal
}
/*
================
FS_SortFileList
================
*/
void FS_SortFileList( char **filelist, int numfiles ) {
int i, j, k, numsortedfiles;
char **sortedlist;
sortedlist = Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ) );
sortedlist[0] = NULL;
numsortedfiles = 0;
for ( i = 0; i < numfiles; i++ ) {
for ( j = 0; j < numsortedfiles; j++ ) {
if ( FS_PathCmp( filelist[i], sortedlist[j] ) < 0 ) {
break;
}
}
for ( k = numsortedfiles; k > j; k-- ) {
sortedlist[k] = sortedlist[k - 1];
}
sortedlist[j] = filelist[i];
numsortedfiles++;
}
Com_Memcpy( filelist, sortedlist, numfiles * sizeof( *filelist ) );
Z_Free( sortedlist );
}
/*
================
FS_NewDir_f
================
*/
void FS_NewDir_f( void ) {
char *filter;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 ) {
Com_Printf( "usage: fdir <filter>\n" );
Com_Printf( "example: fdir *q3dm*.bsp\n" );
return;
}
filter = Cmd_Argv( 1 );
Com_Printf( "---------------\n" );
dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs, qfalse );
FS_SortFileList( dirnames, ndirs );
for ( i = 0; i < ndirs; i++ ) {
FS_ConvertPath( dirnames[i] );
Com_Printf( "%s\n", dirnames[i] );
}
Com_Printf( "%d files listed\n", ndirs );
FS_FreeFileList( dirnames );
}
/*
============
FS_Path_f
============
*/
void FS_Path_f( void ) {
searchpath_t *s;
int i;
Com_Printf( "Current search path:\n" );
for ( s = fs_searchpaths; s; s = s->next ) {
if ( s->pack ) {
Com_Printf( "%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles );
if ( fs_numServerPaks ) {
if ( !FS_PakIsPure( s->pack ) ) {
Com_Printf( " not on the pure list\n" );
} else {
Com_Printf( " on the pure list\n" );
}
}
} else {
Com_Printf ("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir );
}
}
Com_Printf( "\n" );
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o ) {
Com_Printf( "handle %i: %s\n", i, fsh[i].name );
}
}
}
/*
============
FS_TouchFile_f
============
*/
void FS_TouchFile_f( void ) {
fileHandle_t f;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: touchFile <file>\n" );
return;
}
FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse );
if ( f ) {
FS_FCloseFile( f );
}
}
/*
============
FS_Which
============
*/
qboolean FS_Which(const char *filename, void *searchPath)
{
searchpath_t *search = searchPath;
if(FS_FOpenFileReadDir(filename, search, NULL, qfalse, qfalse) > 0)
{
if(search->pack)
{
Com_Printf("File \"%s\" found in \"%s\"\n", filename, search->pack->pakFilename);
return qtrue;
}
else if(search->dir)
{
Com_Printf( "File \"%s\" found at \"%s\"\n", filename, search->dir->fullpath);
return qtrue;
}
}
return qfalse;
}
/*
============
FS_Which_f
============
*/
void FS_Which_f( void ) {
searchpath_t *search;
char *filename;
filename = Cmd_Argv(1);
if ( !filename[0] ) {
Com_Printf( "Usage: which <file>\n" );
return;
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// just wants to see if file is there
for(search = fs_searchpaths; search; search = search->next)
{
if(FS_Which(filename, search))
return;
}
Com_Printf("File not found: \"%s\"\n", filename);
}
//===========================================================================
static int QDECL paksort( const void *a, const void *b ) {
char *aa, *bb;
aa = *(char **)a;
bb = *(char **)b;
return FS_PathCmp( aa, bb );
}
/*
================
FS_AddGameDirectory
Sets fs_gamedir, adds the directory to the head of the path,
then loads the zip headers
================
*/
#define MAX_PAKFILES 1024
void FS_AddGameDirectory( const char *path, const char *dir ) {
searchpath_t *sp;
int i;
searchpath_t *search;
pack_t *pak;
char *pakfile;
int numfiles;
char **pakfiles;
char *sorted[MAX_PAKFILES];
// this fixes the case where fs_basepath is the same as fs_cdpath
// which happens on full installs
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->dir && !Q_stricmp( sp->dir->path, path ) && !Q_stricmp( sp->dir->gamedir, dir ) ) {
return; // we've already got this one
}
}
Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) );
//
// add the directory to the search path
//
search = Z_Malloc( sizeof( searchpath_t ) );
search->dir = Z_Malloc( sizeof( *search->dir ) );
Q_strncpyz( search->dir->path, path, sizeof( search->dir->path ) );
Q_strncpyz( search->dir->gamedir, dir, sizeof( search->dir->gamedir ) );
search->next = fs_searchpaths;
fs_searchpaths = search;
// find all pak files in this directory
pakfile = FS_BuildOSPath( path, dir, "" );
pakfile[ strlen( pakfile ) - 1 ] = 0; // strip the trailing slash
pakfiles = Sys_ListFiles( pakfile, ".pk3", NULL, &numfiles, qfalse );
// sort them so that later alphabetic matches override
// earlier ones. This makes pak1.pk3 override pak0.pk3
if ( numfiles > MAX_PAKFILES ) {
numfiles = MAX_PAKFILES;
}
for ( i = 0 ; i < numfiles ; i++ ) {
sorted[i] = pakfiles[i];
// JPW NERVE sp_* to _p_* so "sp_pak*" gets alphabetically sorted before "pak*"
//----(SA) SP mod
// (SA) sort order to be further clarified later (10/8/01)
if ( !Q_strncmp( sorted[i],"sp_",3 ) ) { // sort sp first
memcpy( sorted[i],"zz",2 );
}
}
qsort( sorted, numfiles, sizeof(char *), paksort );
for ( i = 0 ; i < numfiles ; i++ ) {
if ( Q_strncmp( sorted[i],"mp_",3 ) ) { // (SA) SP mod -- exclude mp_*
// JPW NERVE KLUDGE: fix filenames broken in mp/sp/pak sort above
//----(SA) mod for SP
if ( !Q_strncmp( sorted[i],"zz_",3 ) ) {
memcpy( sorted[i],"sp",2 );
}
// jpw
pakfile = FS_BuildOSPath( path, dir, sorted[i] );
if ( ( pak = FS_LoadZipFile( pakfile, sorted[i] ) ) == 0 ) {
continue;
}
// store the game name for downloading
strcpy( pak->pakGamename, dir );
search = Z_Malloc( sizeof( searchpath_t ) );
search->pack = pak;
search->next = fs_searchpaths;
fs_searchpaths = search;
}
}
// done
Sys_FreeFileList( pakfiles );
}
/*
================
FS_idPak
================
*/
qboolean FS_idPak(char *pak, char *base, int numPaks)
{
int i;
for ( i = 0; i < NUM_ID_PAKS; i++ ) {
if ( !FS_FilenameCompare( pak, va( "%s/pak%d", base, i ) ) ) {
break;
}
// JPW NERVE -- this fn prevents external sources from downloading/overwriting official files, so exclude both SP and MP files from this list as well
if ( !FS_FilenameCompare( pak, va( "%s/mp_pak%d",base,i ) ) ) {
break;
}
if ( !FS_FilenameCompare( pak, va( "%s/sp_pak%d",base,i + 1) ) ) {
break;
}
// jpw
}
if ( i < numPaks ) {
return qtrue;
}
return qfalse;
}
/*
================
FS_CheckDirTraversal
Check whether the string contains stuff like "../" to prevent directory traversal bugs
and return qtrue if it does.
================
*/
qboolean FS_CheckDirTraversal(const char *checkdir)
{
if(strstr(checkdir, "../") || strstr(checkdir, "..\\"))
return qtrue;
return qfalse;
}
/*
================
FS_ComparePaks
----------------
dlstring == qtrue
Returns a list of pak files that we should download from the server. They all get stored
in the current gamedir and an FS_Restart will be fired up after we download them all.
The string is the format:
@remotename@localname [repeat]
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS];
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS];
----------------
dlstring == qfalse
we are not interested in a download string format, we want something human-readable
(this is used for diagnostics while connecting to a pure server)
================
*/
qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring ) {
searchpath_t *sp;
qboolean havepak;
char *origpos = neededpaks;
int i;
if ( !fs_numServerReferencedPaks )
return qfalse; // Server didn't send any pack information along
*neededpaks = 0;
for ( i = 0 ; i < fs_numServerReferencedPaks ; i++ )
{
// Ok, see if we have this pak file
havepak = qfalse;
// never autodownload any of the id paks
if(FS_idPak(fs_serverReferencedPakNames[i], BASEGAME, NUM_ID_PAKS))
{
continue;
}
// Make sure the server cannot make us write to non-quake3 directories.
if(FS_CheckDirTraversal(fs_serverReferencedPakNames[i]))
{
Com_Printf("WARNING: Invalid download name %s\n", fs_serverReferencedPakNames[i]);
continue;
}
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i] ) {
havepak = qtrue; // This is it!
break;
}
}
if ( !havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i] ) {
// Don't got it
if (dlstring)
{
// We need this to make sure we won't hit the end of the buffer or the server could
// overwrite non-pk3 files on clients by writing so much crap into neededpaks that
// Q_strcat cuts off the .pk3 extension.
origpos += strlen(origpos);
// Remote name
Q_strcat( neededpaks, len, "@");
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Local name
Q_strcat( neededpaks, len, "@");
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
{
char st[MAX_ZPATH];
// We already have one called this, we need to download it to another name
// Make something up with the checksum in it
Com_sprintf( st, sizeof( st ), "%s.%08x.pk3", fs_serverReferencedPakNames[i], fs_serverReferencedPaks[i] );
Q_strcat( neededpaks, len, st );
}
else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
}
// Find out whether it might have overflowed the buffer and don't add this file to the
// list if that is the case.
if(strlen(origpos) + (origpos - neededpaks) >= len - 1)
{
*origpos = '\0';
break;
}
}
else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
{
Q_strcat( neededpaks, len, " (local file exists with wrong checksum)");
}
Q_strcat( neededpaks, len, "\n");
}
}
}
if ( *neededpaks ) {
Com_Printf( "Need paks: %s\n", neededpaks );
return qtrue;
}
return qfalse; // We have them all
}
/*
================
FS_Shutdown
Frees all resources.
================
*/
void FS_Shutdown( qboolean closemfp ) {
searchpath_t *p, *next;
int i;
for ( i = 0; i < MAX_FILE_HANDLES; i++ ) {
if ( fsh[i].fileSize ) {
FS_FCloseFile( i );
}
}
// free everything
for(p = fs_searchpaths; p; p = next)
{
next = p->next;
if(p->pack)
FS_FreePak(p->pack);
if (p->dir)
Z_Free(p->dir);
Z_Free(p);
}
// any FS_ calls will now be an error until reinitialized
fs_searchpaths = NULL;
Cmd_RemoveCommand( "path" );
Cmd_RemoveCommand( "dir" );
Cmd_RemoveCommand( "fdir" );
Cmd_RemoveCommand( "touchFile" );
Cmd_RemoveCommand( "which" );
#ifdef FS_MISSING
if ( closemfp ) {
fclose( missingFiles );
}
#endif
}
#ifndef STANDALONE
void Com_AppendCDKey( const char *filename );
void Com_ReadCDKey( const char *filename );
#endif
/*
================
FS_ReorderPurePaks
NOTE TTimo: the reordering that happens here is not reflected in the cvars (\cvarlist *pak*)
this can lead to misleading situations, see https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
================
*/
static void FS_ReorderPurePaks( void )
{
searchpath_t *s;
int i;
searchpath_t **p_insert_index, // for linked list reordering
**p_previous; // when doing the scan
fs_reordered = qfalse;
// only relevant when connected to pure server
if ( !fs_numServerPaks )
return;
p_insert_index = &fs_searchpaths; // we insert in order at the beginning of the list
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
p_previous = p_insert_index; // track the pointer-to-current-item
for (s = *p_insert_index; s; s = s->next) {
// the part of the list before p_insert_index has been sorted already
if (s->pack && fs_serverPaks[i] == s->pack->checksum) {
fs_reordered = qtrue;
// move this element to the insert list
*p_previous = s->next;
s->next = *p_insert_index;
*p_insert_index = s;
// increment insert list
p_insert_index = &s->next;
break; // iterate to next server pack
}
p_previous = &s->next;
}
}
}
/*
================
FS_Startup
================
*/
static void FS_Startup( const char *gameName )
{
const char *homePath;
Com_Printf( "----- FS_Startup -----\n" );
fs_packFiles = 0;
fs_debug = Cvar_Get( "fs_debug", "0", 0 );
fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT|CVAR_PROTECTED );
fs_basegame = Cvar_Get( "fs_basegame", "", CVAR_INIT );
homePath = Sys_DefaultHomePath();
if (!homePath || !homePath[0]) {
homePath = fs_basepath->string;
}
fs_homepath = Cvar_Get ("fs_homepath", homePath, CVAR_INIT|CVAR_PROTECTED );
fs_gamedirvar = Cvar_Get( "fs_game", "", CVAR_INIT | CVAR_SYSTEMINFO );
// add search path elements in reverse priority order
#ifndef STANDALONE
fs_steampath = Cvar_Get ("fs_steampath", Sys_SteamPath(), CVAR_INIT|CVAR_PROTECTED );
if (fs_steampath->string[0]) {
FS_AddGameDirectory( fs_steampath->string, gameName );
}
#endif
if ( fs_basepath->string[0] ) {
FS_AddGameDirectory( fs_basepath->string, gameName );
}
#ifdef __APPLE__
fs_apppath = Cvar_Get ("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT|CVAR_PROTECTED );
// Make MacOSX also include the base path included with the .app bundle
if (fs_apppath->string[0])
FS_AddGameDirectory(fs_apppath->string, gameName);
#endif
// NOTE: same filtering below for mods and basegame
if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string)) {
FS_CreatePath ( fs_homepath->string );
FS_AddGameDirectory( fs_homepath->string, gameName );
}
// check for additional base game so mods can be based upon other mods
if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) ) {
#ifndef STANDALONE
if ( fs_steampath->string[0] ) {
FS_AddGameDirectory( fs_steampath->string, fs_basegame->string );
}
#endif
if ( fs_basepath->string[0] ) {
FS_AddGameDirectory( fs_basepath->string, fs_basegame->string );
}
if ( fs_homepath->string[0] && Q_stricmp( fs_homepath->string,fs_basepath->string ) ) {
FS_AddGameDirectory( fs_homepath->string, fs_basegame->string );
}
}
// check for additional game folder for mods
if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) ) {
#ifndef STANDALONE
if ( fs_steampath->string[0] ) {
FS_AddGameDirectory( fs_steampath->string, fs_gamedirvar->string );
}
#endif
if ( fs_basepath->string[0] ) {
FS_AddGameDirectory( fs_basepath->string, fs_gamedirvar->string );
}
if ( fs_homepath->string[0] && Q_stricmp( fs_homepath->string,fs_basepath->string ) ) {
FS_AddGameDirectory( fs_homepath->string, fs_gamedirvar->string );
}
}
#ifndef STANDALONE
if(!com_standalone->integer)
{
cvar_t *fs;
Com_ReadCDKey(BASEGAME);
fs = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
if (fs && fs->string[0] != 0) {
Com_AppendCDKey( fs->string );
}
}
#endif
// add our commands
Cmd_AddCommand( "path", FS_Path_f );
Cmd_AddCommand( "dir", FS_Dir_f );
Cmd_AddCommand( "fdir", FS_NewDir_f );
Cmd_AddCommand( "touchFile", FS_TouchFile_f );
Cmd_AddCommand ("which", FS_Which_f );
// print the current search paths
FS_Path_f();
fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified
Com_Printf( "----------------------\n" );
#ifdef FS_MISSING
if ( missingFiles == NULL ) {
missingFiles = Sys_FOpen( "\\missing.txt", "ab" );
}
#endif
Com_Printf( "%d files in pk3 files\n", fs_packFiles );
}
#ifndef STANDALONE
/*
===================
FS_CheckSPPaks
Check whether any of the original id pak files is present,
and start up in standalone mode, if there are none and a
different com_basegame was set.
Note: If you're building a game that doesn't depend on the
Q3 media pak0.pk3, you'll want to remove this by defining
STANDALONE in q_shared.h
===================
*/
static void FS_CheckSPPaks( void )
{
searchpath_t *path;
pack_t *curpack;
unsigned int foundPak = 0;
for( path = fs_searchpaths; path; path = path->next )
{
const char* pakBasename = path->pack->pakBasename;
if(!path->pack)
continue;
curpack = path->pack;
if(!Q_stricmpn( curpack->pakGamename, BASEGAME, MAX_OSPATH )
&& strlen(pakBasename) == 7 && !Q_stricmpn( pakBasename, "sp_pak", 6 )
&& pakBasename[6] >= '1' && pakBasename[6] <= '1' + NUM_SP_PAKS - 1)
{
if( curpack->checksum != en_sppak_checksums[pakBasename[6]-'1'] &&
curpack->checksum != fr_sppak_checksums[pakBasename[6]-'1'] &&
curpack->checksum != gm_sppak_checksums[pakBasename[6]-'1'] &&
curpack->checksum != it_sppak_checksums[pakBasename[6]-'1'] &&
curpack->checksum != sp_sppak_checksums[pakBasename[6]-'1'] )
{
if(pakBasename[6] == '1')
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/sp_pak1.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-copy sp_pak1.pk3 from your\n"
"legitimate RTCW CDROM.\n"
"**************************************************\n\n\n",
curpack->checksum );
}
else
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/sp_pak%d.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-install the point release\n"
"**************************************************\n\n\n",
pakBasename[6]-'0', curpack->checksum );
}
}
foundPak |= 1<<(pakBasename[6]-'1');
}
else
{
int index;
// Finally check whether this pak's checksum is listed because the user tried
// to trick us by renaming the file, and set foundPak's highest bit to indicate this case.
for(index = 0; index < ARRAY_LEN( en_sppak_checksums ); index++)
{
if( curpack->checksum == en_sppak_checksums[index] ||
curpack->checksum == fr_sppak_checksums[index] ||
curpack->checksum == gm_sppak_checksums[index] ||
curpack->checksum == it_sppak_checksums[index] ||
curpack->checksum == sp_sppak_checksums[index] )
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: %s is renamed pak file %s%csp_pak%d.pk3\n"
"Running in standalone mode won't work\n"
"Please rename, or remove this file\n"
"**************************************************\n\n\n",
curpack->pakFilename, BASEGAME, PATH_SEP, index + 1 );
foundPak |= 0x80000000;
}
}
}
}
if(!foundPak && Q_stricmp(com_basegame->string, BASEGAME))
{
Cvar_Set("com_standalone", "1");
}
else
Cvar_Set("com_standalone", "0");
if(!com_standalone->integer && (foundPak & 0xf) != 0xf)
{
char errorText[MAX_STRING_CHARS] = "";
char missingPaks[MAX_STRING_CHARS] = "";
int i = 0;
if((foundPak & 0xf) != 0xf)
{
for( i = 0; i < NUM_SP_PAKS; i++ ) {
if ( !( foundPak & ( 1 << i ) ) ) {
Q_strcat( missingPaks, sizeof( missingPaks ), va( "sp_pak%d.pk3 ", i + 1 ) );
}
}
Q_strcat( errorText, sizeof( errorText ),
va( "\n\nPoint Release files are missing: %s \n"
"Please re-install the 1.41 point release.\n\n", missingPaks ) );
}
Com_Error(ERR_FATAL, "%s", errorText);
}
}
/*
===================
FS_CheckPak0
Check whether any of the original id pak files is present,
and start up in standalone mode, if there are none and a
different com_basegame was set.
Note: If you're building a game that doesn't depend on the
RTCW media pak0.pk3, you'll want to remove this by defining
STANDALONE in q_shared.h
===================
*/
static void FS_CheckPak0( void )
{
searchpath_t *path;
pack_t *curpack;
qboolean founddemo = qfalse;
unsigned int foundPak = 0;
for( path = fs_searchpaths; path; path = path->next )
{
const char* pakBasename = path->pack->pakBasename;
if(!path->pack)
continue;
curpack = path->pack;
if(!Q_stricmpn( curpack->pakGamename, "demomain", MAX_OSPATH )
&& !Q_stricmpn( pakBasename, "pak0", MAX_OSPATH ))
{
if(curpack->checksum == DEMO_PAK0_CHECKSUM)
founddemo = qtrue;
}
else if(!Q_stricmpn( curpack->pakGamename, BASEGAME, MAX_OSPATH )
&& strlen(pakBasename) == 4 && !Q_stricmpn( pakBasename, "pak", 3 )
&& pakBasename[3] >= '0' && pakBasename[3] <= '0' + NUM_ID_PAKS - 1)
{
if( curpack->checksum != pak_checksums[pakBasename[3]-'0'] )
{
if(pakBasename[3] == '0')
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/pak0.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-copy pak0.pk3 from your\n"
"legitimate RTCW CDROM.\n"
"**************************************************\n\n\n",
curpack->checksum );
Com_Error(ERR_FATAL, NULL);
}
/*
else
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/pak%d.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-install the point release\n"
"**************************************************\n\n\n",
pakBasename[3]-'0', curpack->checksum );
}
*/
}
foundPak |= 1<<(pakBasename[3]-'0');
}
else
{
int index;
// Finally check whether this pak's checksum is listed because the user tried
// to trick us by renaming the file, and set foundPak's highest bit to indicate this case.
for(index = 0; index < ARRAY_LEN(pak_checksums); index++)
{
if(curpack->checksum == pak_checksums[index])
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: %s is renamed pak file %s%cpak%d.pk3\n"
"Running in standalone mode won't work\n"
"Please rename, or remove this file\n"
"**************************************************\n\n\n",
curpack->pakFilename, BASEGAME, PATH_SEP, index);
foundPak |= 0x80000000;
}
}
}
}
if(!foundPak && Q_stricmp(com_basegame->string, BASEGAME))
{
Cvar_Set("com_standalone", "1");
}
else
Cvar_Set("com_standalone", "0");
if(!com_standalone->integer)
{
if(!(foundPak & 0x01))
{
if(founddemo)
{
Com_Printf( "\n\n"
"**************************************************\n"
"WARNING: It looks like you're using pak0.pk3\n"
"from the demo. This may work fine, but it is not\n"
"guaranteed or supported.\n"
"**************************************************\n\n\n" );
foundPak |= 0x01;
}
}
}
if(!com_standalone->integer && (foundPak & 0x01) != 0x01)
{
char errorText[MAX_STRING_CHARS] = "";
if((foundPak & 0x01) != 0x01)
{
Q_strcat(errorText, sizeof(errorText),
"\n\n\"pak0.pk3\" is missing. Please copy it\n"
"from your legitimate RTCW CDROM.\n\n");
}
Q_strcat(errorText, sizeof(errorText),
va("Also check that your iortcw executable is in\n"
"the correct place and that every file\n"
"in the \"%s\" directory is present and readable.\n\n", BASEGAME));
Com_Error(ERR_FATAL, "%s", errorText);
}
if(!founddemo)
FS_CheckSPPaks();
}
#endif
/*
=====================
FS_LoadedPakChecksums
Returns a space separated string containing the checksums of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->checksum ) );
}
return info;
}
/*
=====================
FS_LoadedPakNames
Returns a space separated string containing the names of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
if ( *info ) {
Q_strcat( info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
return info;
}
/*
=====================
FS_LoadedPakPureChecksums
Returns a space separated string containing the pure checksums of all loaded pk3 files.
Servers with sv_pure use these checksums to compare with the checksums the clients send
back to the server.
=====================
*/
const char *FS_LoadedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->pure_checksum ) );
}
return info;
}
/*
=====================
FS_ReferencedPakChecksums
Returns a space separated string containing the checksums of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) {
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->checksum ) );
}
}
}
return info;
}
/*
=====================
FS_ReferencedPakPureChecksums
Returns a space separated string containing the pure checksums of all referenced pk3 files.
Servers with sv_pure set will get this string back from clients for pure validation
The string has a specific order, "cgame ui @ ref1 ref2 ref3 ..."
NOTE TTimo: this code is taken from Wolf MP source
pure checksums code is not relevant to SP binary anyway
=====================
*/
const char *FS_ReferencedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
int nFlags, numPaks, checksum;
info[0] = 0;
checksum = fs_checksumFeed;
numPaks = 0;
for ( nFlags = FS_GENERAL_REF; nFlags; nFlags = nFlags >> 1 ) {
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file and has it been referenced based on flag?
if ( search->pack && ( search->pack->referenced & nFlags ) ) {
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->pure_checksum ) );
checksum ^= search->pack->pure_checksum;
numPaks++;
}
}
}
// last checksum is the encoded number of referenced pk3s
checksum ^= numPaks;
Q_strcat( info, sizeof( info ), va( "%i ", checksum ) );
return info;
}
/*
=====================
FS_ReferencedPakNames
Returns a space separated string containing the names of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
// we want to return ALL pk3's from the fs_game path
// and referenced one's from baseq3
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) {
if (*info) {
Q_strcat(info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakGamename );
Q_strcat( info, sizeof( info ), "/" );
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
}
}
return info;
}
/*
=====================
FS_ClearPakReferences
=====================
*/
void FS_ClearPakReferences( int flags ) {
searchpath_t *search;
if ( !flags ) {
flags = -1;
}
for ( search = fs_searchpaths; search; search = search->next ) {
// is the element a pak file and has it been referenced?
if ( search->pack ) {
search->pack->referenced &= ~flags;
}
}
}
/*
=====================
FS_PureServerSetLoadedPaks
If the string is empty, all data sources will be allowed.
If not empty, only pk3 files that match one of the space
separated checksums will be checked for files, with the
exception of .cfg and .dat files.
=====================
*/
void FS_PureServerSetLoadedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
fs_numServerPaks = c;
for ( i = 0 ; i < c ; i++ ) {
fs_serverPaks[i] = atoi( Cmd_Argv( i ) );
}
if ( fs_numServerPaks ) {
Com_DPrintf( "Connected to a pure server.\n" );
}
for ( i = 0 ; i < c ; i++ ) {
if ( fs_serverPakNames[i] ) {
Z_Free( fs_serverPakNames[i] );
}
fs_serverPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if ( d > MAX_SEARCH_PATHS ) {
d = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < d ; i++ ) {
fs_serverPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
}
/*
=====================
FS_PureServerSetReferencedPaks
The checksums and names of the pk3 files referenced at the server
are sent to the client and stored here. The client will use these
checksums to see if any pk3 files need to be auto-downloaded.
=====================
*/
void FS_PureServerSetReferencedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d = 0;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < c ; i++ ) {
fs_serverReferencedPaks[i] = atoi( Cmd_Argv( i ) );
}
for (i = 0 ; i < ARRAY_LEN(fs_serverReferencedPakNames); i++)
{
if(fs_serverReferencedPakNames[i])
Z_Free( fs_serverReferencedPakNames[i] );
fs_serverReferencedPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if(d > c)
d = c;
for ( i = 0 ; i < d ; i++ ) {
fs_serverReferencedPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
// ensure that there are as many checksums as there are pak names.
if(d < c)
c = d;
fs_numServerReferencedPaks = c;
}
/*
================
FS_InitFilesystem
Called only at inital startup, not when the filesystem
is resetting due to a game change
================
*/
void FS_InitFilesystem( void ) {
// allow command line parms to override our defaults
// we have to specially handle this, because normal command
// line variable sets don't happen until after the filesystem
// has already been initialized
Com_StartupVariable("fs_basepath");
Com_StartupVariable("fs_homepath");
Com_StartupVariable("fs_game");
if(!FS_FilenameCompare(Cvar_VariableString("fs_game"), com_basegame->string))
Cvar_Set("fs_game", "");
// try to start up normally
FS_Startup(com_basegame->string);
#ifndef STANDALONE
FS_CheckPak0( );
#endif
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
}
Q_strncpyz( lastValidBase, fs_basepath->string, sizeof( lastValidBase ) );
Q_strncpyz( lastValidComBaseGame, com_basegame->string, sizeof( lastValidComBaseGame ) );
Q_strncpyz( lastValidFsBaseGame, fs_basegame->string, sizeof( lastValidFsBaseGame ) );
Q_strncpyz( lastValidGame, fs_gamedirvar->string, sizeof( lastValidGame ) );
}
/*
================
FS_Restart
================
*/
void FS_Restart( int checksumFeed ) {
const char *lastGameDir;
// free anything we currently have loaded
FS_Shutdown( qfalse );
// set the checksum feed
fs_checksumFeed = checksumFeed;
// clear pak references
FS_ClearPakReferences( 0 );
// try to start up normally
FS_Startup(com_basegame->string);
#ifndef STANDALONE
FS_CheckPak0( );
#endif
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
// this might happen when connecting to a pure server not using BASEGAME/pak0.pk3
// (for instance a TA demo server)
if ( lastValidBase[0] ) {
FS_PureServerSetLoadedPaks( "", "" );
Cvar_Set( "fs_basepath", lastValidBase );
Cvar_Set( "com_basegame", lastValidComBaseGame );
Cvar_Set( "fs_basegame", lastValidFsBaseGame );
Cvar_Set( "fs_game", lastValidGame );
lastValidBase[0] = '\0';
lastValidComBaseGame[0] = '\0';
lastValidFsBaseGame[0] = '\0';
lastValidGame[0] = '\0';
FS_Restart( checksumFeed );
Com_Error( ERR_DROP, "Invalid game folder" );
return;
}
Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
}
lastGameDir = ( lastValidGame[0] ) ? lastValidGame : lastValidComBaseGame;
if ( Q_stricmp( FS_GetCurrentGameDir(), lastGameDir ) ) {
Sys_RemovePIDFile( lastGameDir );
Sys_InitPIDFile( FS_GetCurrentGameDir() );
// skip the wolfconfig.cfg if "safe" is on the command line
if ( !Com_SafeMode() ) {
Cbuf_AddText ("exec " Q3CONFIG_CFG "\n");
}
}
Q_strncpyz( lastValidBase, fs_basepath->string, sizeof( lastValidBase ) );
Q_strncpyz( lastValidComBaseGame, com_basegame->string, sizeof( lastValidComBaseGame ) );
Q_strncpyz( lastValidFsBaseGame, fs_basegame->string, sizeof( lastValidFsBaseGame ) );
Q_strncpyz( lastValidGame, fs_gamedirvar->string, sizeof( lastValidGame ) );
}
/*
=================
FS_ConditionalRestart
Restart if necessary
Return qtrue if restarting due to game directory changed, qfalse otherwise
=================
*/
qboolean FS_ConditionalRestart(int checksumFeed, qboolean disconnect)
{
if(fs_gamedirvar->modified)
{
if(FS_FilenameCompare(lastValidGame, fs_gamedirvar->string) &&
(*lastValidGame || FS_FilenameCompare(fs_gamedirvar->string, com_basegame->string)) &&
(*fs_gamedirvar->string || FS_FilenameCompare(lastValidGame, com_basegame->string)))
{
Com_GameRestart(checksumFeed, disconnect);
return qtrue;
}
else
fs_gamedirvar->modified = qfalse;
}
if(checksumFeed != fs_checksumFeed)
FS_Restart(checksumFeed);
else if(fs_numServerPaks && !fs_reordered)
FS_ReorderPurePaks();
return qfalse;
}
/*
========================================================================================
Handle based file calls for virtual machines
========================================================================================
*/
int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
int r;
qboolean sync;
sync = qfalse;
switch ( mode ) {
case FS_READ:
r = FS_FOpenFileRead( qpath, f, qtrue );
break;
case FS_WRITE:
*f = FS_FOpenFileWrite( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
case FS_APPEND_SYNC:
sync = qtrue;
case FS_APPEND:
*f = FS_FOpenFileAppend( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
default:
Com_Error( ERR_FATAL, "FS_FOpenFileByMode: bad mode" );
return -1;
}
if ( !f ) {
return r;
}
if ( *f ) {
fsh[*f].fileSize = r;
fsh[*f].streamed = qfalse;
if (mode == FS_READ) {
fsh[*f].streamed = qtrue;
}
}
fsh[*f].handleSync = sync;
return r;
}
int FS_FTell( fileHandle_t f ) {
int pos;
if ( fsh[f].zipFile == qtrue ) {
pos = unztell( fsh[f].handleFiles.file.z );
} else {
pos = ftell( fsh[f].handleFiles.file.o );
}
return pos;
}
void FS_Flush( fileHandle_t f ) {
fflush( fsh[f].handleFiles.file.o );
}
void FS_FilenameCompletion( const char *dir, const char *ext,
qboolean stripExt, void(*callback)(const char *s), qboolean allowNonPureFilesOnDisk ) {
char **filenames;
int nfiles;
int i;
char filename[ MAX_STRING_CHARS ];
filenames = FS_ListFilteredFiles( dir, ext, NULL, &nfiles, allowNonPureFilesOnDisk );
FS_SortFileList( filenames, nfiles );
for( i = 0; i < nfiles; i++ ) {
FS_ConvertPath( filenames[ i ] );
Q_strncpyz( filename, filenames[ i ], MAX_STRING_CHARS );
if( stripExt ) {
COM_StripExtension(filename, filename, sizeof(filename));
}
callback( filename );
}
FS_FreeFileList( filenames );
}
const char *FS_GetCurrentGameDir(void)
{
if(fs_gamedirvar->string[0])
return fs_gamedirvar->string;
return com_basegame->string;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3233_4 |
crossvul-cpp_data_good_3151_2 | /*
* Copyright (C) 2014-2016 Firejail Authors
*
* This file is part of firejail 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "firejail.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <syslog.h>
#include <errno.h>
#include <dirent.h>
#include <grp.h>
#include <ftw.h>
#include <sys/ioctl.h>
#include <termios.h>
#define MAX_GROUPS 1024
// drop privileges
// - for root group or if nogroups is set, supplementary groups are not configured
void drop_privs(int nogroups) {
gid_t gid = getgid();
// configure supplementary groups
if (gid == 0 || nogroups) {
if (setgroups(0, NULL) < 0)
errExit("setgroups");
if (arg_debug)
printf("Username %s, no supplementary groups\n", cfg.username);
}
else {
assert(cfg.username);
gid_t groups[MAX_GROUPS];
int ngroups = MAX_GROUPS;
int rv = getgrouplist(cfg.username, gid, groups, &ngroups);
if (arg_debug && rv) {
printf("Username %s, groups ", cfg.username);
int i;
for (i = 0; i < ngroups; i++)
printf("%u, ", groups[i]);
printf("\n");
}
if (rv == -1) {
fprintf(stderr, "Warning: cannot extract supplementary group list, dropping them\n");
if (setgroups(0, NULL) < 0)
errExit("setgroups");
}
else {
rv = setgroups(ngroups, groups);
if (rv) {
fprintf(stderr, "Warning: cannot set supplementary group list, dropping them\n");
if (setgroups(0, NULL) < 0)
errExit("setgroups");
}
}
}
// set uid/gid
if (setgid(getgid()) < 0)
errExit("setgid/getgid");
if (setuid(getuid()) < 0)
errExit("setuid/getuid");
}
int mkpath_as_root(const char* path) {
assert(path && *path);
// work on a copy of the path
char *file_path = strdup(path);
if (!file_path)
errExit("strdup");
char* p;
int done = 0;
for (p=strchr(file_path+1, '/'); p; p=strchr(p+1, '/')) {
*p='\0';
if (mkdir(file_path, 0755)==-1) {
if (errno != EEXIST) {
*p='/';
free(file_path);
return -1;
}
}
else {
if (chmod(file_path, 0755) == -1)
errExit("chmod");
if (chown(file_path, 0, 0) == -1)
errExit("chown");
done = 1;
}
*p='/';
}
if (done)
fs_logger2("mkpath", path);
free(file_path);
return 0;
}
void logsignal(int s) {
if (!arg_debug)
return;
openlog("firejail", LOG_NDELAY | LOG_PID, LOG_USER);
syslog(LOG_INFO, "Signal %d caught", s);
closelog();
}
void logmsg(const char *msg) {
if (!arg_debug)
return;
openlog("firejail", LOG_NDELAY | LOG_PID, LOG_USER);
syslog(LOG_INFO, "%s\n", msg);
closelog();
}
void logargs(int argc, char **argv) {
if (!arg_debug)
return;
int i;
int len = 0;
// calculate message length
for (i = 0; i < argc; i++)
len += strlen(argv[i]) + 1; // + ' '
// build message
char msg[len + 1];
char *ptr = msg;
for (i = 0; i < argc; i++) {
sprintf(ptr, "%s ", argv[i]);
ptr += strlen(ptr);
}
// log message
logmsg(msg);
}
void logerr(const char *msg) {
if (!arg_debug)
return;
openlog("firejail", LOG_NDELAY | LOG_PID, LOG_USER);
syslog(LOG_ERR, "%s\n", msg);
closelog();
}
// return -1 if error, 0 if no error
int copy_file(const char *srcname, const char *destname) {
assert(srcname);
assert(destname);
// open source
int src = open(srcname, O_RDONLY);
if (src < 0) {
fprintf(stderr, "Warning: cannot open %s, file not copied\n", srcname);
return -1;
}
// open destination
int dst = open(destname, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (dst < 0) {
fprintf(stderr, "Warning: cannot open %s, file not copied\n", destname);
close(src);
return -1;
}
// copy
ssize_t len;
static const int BUFLEN = 1024;
unsigned char buf[BUFLEN];
while ((len = read(src, buf, BUFLEN)) > 0) {
int done = 0;
while (done != len) {
int rv = write(dst, buf + done, len - done);
if (rv == -1) {
close(src);
close(dst);
return -1;
}
done += rv;
}
}
close(src);
close(dst);
return 0;
}
// return -1 if error, 0 if no error
void copy_file_as_user(const char *srcname, const char *destname, uid_t uid, gid_t gid, mode_t mode) {
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
// drop privileges
drop_privs(0);
// copy, set permissions and ownership
int rv = copy_file(srcname, destname); // already a regular user
if (rv)
fprintf(stderr, "Warning: cannot copy %s\n", srcname);
else {
if (chown(destname, uid, gid) == -1)
errExit("fchown");
if (chmod(destname, mode) == -1)
errExit("fchmod");
}
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
}
// return -1 if error, 0 if no error
void touch_file_as_user(const char *fname, uid_t uid, gid_t gid, mode_t mode) {
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
// drop privileges
drop_privs(0);
FILE *fp = fopen(fname, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, uid, gid, mode);
fclose(fp);
}
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
}
// return 1 if the file is a directory
int is_dir(const char *fname) {
assert(fname);
if (*fname == '\0')
return 0;
// if fname doesn't end in '/', add one
int rv;
struct stat s;
if (fname[strlen(fname) - 1] == '/')
rv = stat(fname, &s);
else {
char *tmp;
if (asprintf(&tmp, "%s/", fname) == -1) {
fprintf(stderr, "Error: cannot allocate memory, %s:%d\n", __FILE__, __LINE__);
errExit("asprintf");
}
rv = stat(tmp, &s);
free(tmp);
}
if (rv == -1)
return 0;
if (S_ISDIR(s.st_mode))
return 1;
return 0;
}
// return 1 if the file is a link
int is_link(const char *fname) {
assert(fname);
if (*fname == '\0')
return 0;
struct stat s;
if (lstat(fname, &s) == 0) {
if (S_ISLNK(s.st_mode))
return 1;
}
return 0;
}
// remove multiple spaces and return allocated memory
char *line_remove_spaces(const char *buf) {
assert(buf);
if (strlen(buf) == 0)
return NULL;
// allocate memory for the new string
char *rv = malloc(strlen(buf) + 1);
if (rv == NULL)
errExit("malloc");
// remove space at start of line
const char *ptr1 = buf;
while (*ptr1 == ' ' || *ptr1 == '\t')
ptr1++;
// copy data and remove additional spaces
char *ptr2 = rv;
int state = 0;
while (*ptr1 != '\0') {
if (*ptr1 == '\n' || *ptr1 == '\r')
break;
if (state == 0) {
if (*ptr1 != ' ' && *ptr1 != '\t')
*ptr2++ = *ptr1++;
else {
*ptr2++ = ' ';
ptr1++;
state = 1;
}
}
else { // state == 1
while (*ptr1 == ' ' || *ptr1 == '\t')
ptr1++;
state = 0;
}
}
// strip last blank character if any
if (ptr2 > rv && *(ptr2 - 1) == ' ')
--ptr2;
*ptr2 = '\0';
// if (arg_debug)
// printf("Processing line #%s#\n", rv);
return rv;
}
char *split_comma(char *str) {
if (str == NULL || *str == '\0')
return NULL;
char *ptr = strchr(str, ',');
if (!ptr)
return NULL;
*ptr = '\0';
ptr++;
if (*ptr == '\0')
return NULL;
return ptr;
}
int not_unsigned(const char *str) {
int rv = 0;
const char *ptr = str;
while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0') {
if (!isdigit(*ptr)) {
rv = 1;
break;
}
ptr++;
}
return rv;
}
#define BUFLEN 4096
// find the first child for this parent; return 1 if error
int find_child(pid_t parent, pid_t *child) {
*child = 0; // use it to flag a found child
DIR *dir;
if (!(dir = opendir("/proc"))) {
// sleep 2 seconds and try again
sleep(2);
if (!(dir = opendir("/proc"))) {
fprintf(stderr, "Error: cannot open /proc directory\n");
exit(1);
}
}
struct dirent *entry;
char *end;
while (*child == 0 && (entry = readdir(dir))) {
pid_t pid = strtol(entry->d_name, &end, 10);
if (end == entry->d_name || *end)
continue;
if (pid == parent)
continue;
// open stat file
char *file;
if (asprintf(&file, "/proc/%u/status", pid) == -1) {
perror("asprintf");
exit(1);
}
FILE *fp = fopen(file, "r");
if (!fp) {
free(file);
continue;
}
// look for firejail executable name
char buf[BUFLEN];
while (fgets(buf, BUFLEN - 1, fp)) {
if (strncmp(buf, "PPid:", 5) == 0) {
char *ptr = buf + 5;
while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t')) {
ptr++;
}
if (*ptr == '\0') {
fprintf(stderr, "Error: cannot read /proc file\n");
exit(1);
}
if (parent == atoi(ptr))
*child = pid;
break; // stop reading the file
}
}
fclose(fp);
free(file);
}
closedir(dir);
return (*child)? 0:1; // 0 = found, 1 = not found
}
void extract_command_name(int index, char **argv) {
assert(argv);
assert(argv[index]);
// configure command index
cfg.original_program_index = index;
char *str = strdup(argv[index]);
if (!str)
errExit("strdup");
// if we have a symbolic link, use the real path to extract the name
if (is_link(argv[index])) {
char*newname = realpath(argv[index], NULL);
if (newname) {
free(str);
str = newname;
}
}
// configure command name
cfg.command_name = str;
if (!cfg.command_name)
errExit("strdup");
// restrict the command name to the first word
char *ptr = cfg.command_name;
while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0')
ptr++;
*ptr = '\0';
// remove the path: /usr/bin/firefox becomes firefox
ptr = strrchr(cfg.command_name, '/');
if (ptr) {
ptr++;
if (*ptr == '\0') {
fprintf(stderr, "Error: invalid command name\n");
exit(1);
}
char *tmp = strdup(ptr);
if (!tmp)
errExit("strdup");
// limit the command to the first '.'
char *ptr2 = tmp;
while (*ptr2 != '.' && *ptr2 != '\0')
ptr2++;
*ptr2 = '\0';
free(cfg.command_name);
cfg.command_name = tmp;
}
}
void update_map(char *mapping, char *map_file) {
int fd;
size_t j;
size_t map_len; /* Length of 'mapping' */
/* Replace commas in mapping string with newlines */
map_len = strlen(mapping);
for (j = 0; j < map_len; j++)
if (mapping[j] == ',')
mapping[j] = '\n';
fd = open(map_file, O_RDWR);
if (fd == -1) {
fprintf(stderr, "Error: cannot open %s: %s\n", map_file, strerror(errno));
exit(EXIT_FAILURE);
}
if (write(fd, mapping, map_len) != (ssize_t)map_len) {
fprintf(stderr, "Error: cannot write to %s: %s\n", map_file, strerror(errno));
exit(EXIT_FAILURE);
}
close(fd);
}
void wait_for_other(int fd) {
//****************************
// wait for the parent to be initialized
//****************************
char childstr[BUFLEN + 1];
int newfd = dup(fd);
if (newfd == -1)
errExit("dup");
FILE* stream;
stream = fdopen(newfd, "r");
*childstr = '\0';
if (fgets(childstr, BUFLEN, stream)) {
// remove \n)
char *ptr = childstr;
while(*ptr !='\0' && *ptr != '\n')
ptr++;
if (*ptr == '\0')
errExit("fgets");
*ptr = '\0';
}
else {
fprintf(stderr, "Error: cannot establish communication with the parent, exiting...\n");
exit(1);
}
fclose(stream);
}
void notify_other(int fd) {
FILE* stream;
int newfd = dup(fd);
if (newfd == -1)
errExit("dup");
stream = fdopen(newfd, "w");
fprintf(stream, "%u\n", getpid());
fflush(stream);
fclose(stream);
}
// This function takes a pathname supplied by the user and expands '~' and
// '${HOME}' at the start, to refer to a path relative to the user's home
// directory (supplied).
// The return value is allocated using malloc and must be freed by the caller.
// The function returns NULL if there are any errors.
char *expand_home(const char *path, const char* homedir)
{
assert(path);
assert(homedir);
// Replace home macro
char *new_name = NULL;
if (strncmp(path, "${HOME}", 7) == 0) {
if (asprintf(&new_name, "%s%s", homedir, path + 7) == -1)
errExit("asprintf");
return new_name;
}
else if (strncmp(path, "~/", 2) == 0) {
if (asprintf(&new_name, "%s%s", homedir, path + 1) == -1)
errExit("asprintf");
return new_name;
}
return strdup(path);
}
// Equivalent to the GNU version of basename, which is incompatible with
// the POSIX basename. A few lines of code saves any portability pain.
// https://www.gnu.org/software/libc/manual/html_node/Finding-Tokens-in-a-String.html#index-basename
const char *gnu_basename(const char *path)
{
const char *last_slash = strrchr(path, '/');
if (!last_slash)
return path;
return last_slash+1;
}
uid_t pid_get_uid(pid_t pid) {
uid_t rv = 0;
// open status file
char *file;
if (asprintf(&file, "/proc/%u/status", pid) == -1) {
perror("asprintf");
exit(1);
}
FILE *fp = fopen(file, "r");
if (!fp) {
free(file);
fprintf(stderr, "Error: cannot open /proc file\n");
exit(1);
}
// extract uid
static const int PIDS_BUFLEN = 1024;
char buf[PIDS_BUFLEN];
while (fgets(buf, PIDS_BUFLEN - 1, fp)) {
if (strncmp(buf, "Uid:", 4) == 0) {
char *ptr = buf + 5;
while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t')) {
ptr++;
}
if (*ptr == '\0')
break;
rv = atoi(ptr);
break; // break regardless!
}
}
fclose(fp);
free(file);
if (rv == 0) {
fprintf(stderr, "Error: cannot read /proc file\n");
exit(1);
}
return rv;
}
void invalid_filename(const char *fname) {
assert(fname);
const char *ptr = fname;
if (arg_debug_check_filename)
printf("Checking filename %s\n", fname);
if (strncmp(ptr, "${HOME}", 7) == 0)
ptr = fname + 7;
else if (strncmp(ptr, "${PATH}", 7) == 0)
ptr = fname + 7;
else if (strcmp(fname, "${DOWNLOADS}") == 0)
return;
int len = strlen(ptr);
// file globbing ('*') is allowed
if (strcspn(ptr, "\\&!?\"'<>%^(){}[];,") != (size_t)len) {
fprintf(stderr, "Error: \"%s\" is an invalid filename\n", ptr);
exit(1);
}
}
static int remove_callback(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
(void) sb;
(void) typeflag;
(void) ftwbuf;
int rv = remove(fpath);
if (rv)
perror(fpath);
return rv;
}
int remove_directory(const char *path) {
// FTW_PHYS - do not follow symbolic links
return nftw(path, remove_callback, 64, FTW_DEPTH | FTW_PHYS);
}
void flush_stdin(void) {
if (isatty(STDIN_FILENO)) {
int cnt = 0;
ioctl(STDIN_FILENO, FIONREAD, &cnt);
if (cnt) {
if (!arg_quiet)
printf("Warning: removing %d bytes from stdin\n", cnt);
ioctl(STDIN_FILENO, TCFLSH, TCIFLUSH);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3151_2 |
crossvul-cpp_data_good_3229_0 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// console.c
#include "client.h"
int g_console_field_width = 78;
#define NUM_CON_TIMES 4
#define CON_TEXTSIZE 32768
typedef struct {
qboolean initialized;
short text[CON_TEXTSIZE];
int current; // line where next message will be printed
int x; // offset in current line for next print
int display; // bottom of console displays this line
int linewidth; // characters across screen
int totallines; // total lines in console scrollback
float xadjust; // for wide aspect screens
float displayFrac; // aproaches finalFrac at scr_conspeed
float finalFrac; // 0.0 to 1.0 lines of console to display
int vislines; // in scanlines
int times[NUM_CON_TIMES]; // cls.realtime time the line was generated
// for transparent notify lines
vec4_t color;
} console_t;
console_t con;
cvar_t *con_conspeed;
cvar_t *con_notifytime;
#define DEFAULT_CONSOLE_WIDTH 78
/*
================
Con_ToggleConsole_f
================
*/
void Con_ToggleConsole_f (void) {
// Can't toggle the console when it's the only thing available
if ( clc.state == CA_DISCONNECTED && Key_GetCatcher( ) == KEYCATCH_CONSOLE ) {
return;
}
Field_Clear( &g_consoleField );
g_consoleField.widthInChars = g_console_field_width;
Con_ClearNotify ();
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_CONSOLE );
}
/*
===================
Con_ToggleMenu_f
===================
*/
void Con_ToggleMenu_f( void ) {
CL_KeyEvent( K_ESCAPE, qtrue, Sys_Milliseconds() );
CL_KeyEvent( K_ESCAPE, qfalse, Sys_Milliseconds() );
}
/*
================
Con_MessageMode_f
================
*/
void Con_MessageMode_f (void) {
chat_playerNum = -1;
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode2_f
================
*/
void Con_MessageMode2_f (void) {
chat_playerNum = -1;
chat_team = qtrue;
Field_Clear( &chatField );
chatField.widthInChars = 25;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode3_f
================
*/
void Con_MessageMode3_f (void) {
chat_playerNum = VM_Call( cgvm, CG_CROSSHAIR_PLAYER );
if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) {
chat_playerNum = -1;
return;
}
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode4_f
================
*/
void Con_MessageMode4_f (void) {
chat_playerNum = VM_Call( cgvm, CG_LAST_ATTACKER );
if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) {
chat_playerNum = -1;
return;
}
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_Clear_f
================
*/
void Con_Clear_f (void) {
int i;
for ( i = 0 ; i < CON_TEXTSIZE ; i++ ) {
con.text[i] = (ColorIndex(COLOR_WHITE)<<8) | ' ';
}
Con_Bottom(); // go to end
}
/*
================
Con_Dump_f
Save the console contents out to a file
================
*/
void Con_Dump_f (void)
{
int l, x, i;
short *line;
fileHandle_t f;
int bufferlen;
char *buffer;
char filename[MAX_QPATH];
if (Cmd_Argc() != 2)
{
Com_Printf ("usage: condump <filename>\n");
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".txt" );
if (!COM_CompareExtension(filename, ".txt"))
{
Com_Printf("Con_Dump_f: Only the \".txt\" extension is supported by this command!\n");
return;
}
f = FS_FOpenFileWrite( filename );
if (!f)
{
Com_Printf ("ERROR: couldn't open %s.\n", filename);
return;
}
Com_Printf ("Dumped console text to %s.\n", filename );
// skip empty lines
for (l = con.current - con.totallines + 1 ; l <= con.current ; l++)
{
line = con.text + (l%con.totallines)*con.linewidth;
for (x=0 ; x<con.linewidth ; x++)
if ((line[x] & 0xff) != ' ')
break;
if (x != con.linewidth)
break;
}
#ifdef _WIN32
bufferlen = con.linewidth + 3 * sizeof ( char );
#else
bufferlen = con.linewidth + 2 * sizeof ( char );
#endif
buffer = Hunk_AllocateTempMemory( bufferlen );
// write the remaining lines
buffer[bufferlen-1] = 0;
for ( ; l <= con.current ; l++)
{
line = con.text + (l%con.totallines)*con.linewidth;
for(i=0; i<con.linewidth; i++)
buffer[i] = line[i] & 0xff;
for (x=con.linewidth-1 ; x>=0 ; x--)
{
if (buffer[x] == ' ')
buffer[x] = 0;
else
break;
}
#ifdef _WIN32
Q_strcat(buffer, bufferlen, "\r\n");
#else
Q_strcat(buffer, bufferlen, "\n");
#endif
FS_Write(buffer, strlen(buffer), f);
}
Hunk_FreeTempMemory( buffer );
FS_FCloseFile( f );
}
/*
================
Con_ClearNotify
================
*/
void Con_ClearNotify( void ) {
int i;
for ( i = 0 ; i < NUM_CON_TIMES ; i++ ) {
con.times[i] = 0;
}
}
/*
================
Con_CheckResize
If the line width has changed, reformat the buffer.
================
*/
void Con_CheckResize (void)
{
int i, j, width, oldwidth, oldtotallines, numlines, numchars;
short tbuf[CON_TEXTSIZE];
width = (SCREEN_WIDTH / SMALLCHAR_WIDTH) - 2;
if (width == con.linewidth)
return;
if (width < 1) // video hasn't been initialized yet
{
width = DEFAULT_CONSOLE_WIDTH;
con.linewidth = width;
con.totallines = CON_TEXTSIZE / con.linewidth;
for(i=0; i<CON_TEXTSIZE; i++)
con.text[i] = (ColorIndex(COLOR_WHITE)<<8) | ' ';
}
else
{
oldwidth = con.linewidth;
con.linewidth = width;
oldtotallines = con.totallines;
con.totallines = CON_TEXTSIZE / con.linewidth;
numlines = oldtotallines;
if (con.totallines < numlines)
numlines = con.totallines;
numchars = oldwidth;
if (con.linewidth < numchars)
numchars = con.linewidth;
Com_Memcpy (tbuf, con.text, CON_TEXTSIZE * sizeof(short));
for(i=0; i<CON_TEXTSIZE; i++)
con.text[i] = (ColorIndex(COLOR_WHITE)<<8) | ' ';
for (i=0 ; i<numlines ; i++)
{
for (j=0 ; j<numchars ; j++)
{
con.text[(con.totallines - 1 - i) * con.linewidth + j] =
tbuf[((con.current - i + oldtotallines) %
oldtotallines) * oldwidth + j];
}
}
Con_ClearNotify ();
}
con.current = con.totallines - 1;
con.display = con.current;
}
/*
==================
Cmd_CompleteTxtName
==================
*/
void Cmd_CompleteTxtName( char *args, int argNum ) {
if( argNum == 2 ) {
Field_CompleteFilename( "", "txt", qfalse, qtrue );
}
}
/*
================
Con_Init
================
*/
void Con_Init (void) {
int i;
con_notifytime = Cvar_Get ("con_notifytime", "3", 0);
con_conspeed = Cvar_Get ("scr_conspeed", "3", 0);
Field_Clear( &g_consoleField );
g_consoleField.widthInChars = g_console_field_width;
for ( i = 0 ; i < COMMAND_HISTORY ; i++ ) {
Field_Clear( &historyEditLines[i] );
historyEditLines[i].widthInChars = g_console_field_width;
}
CL_LoadConsoleHistory( );
Cmd_AddCommand ("toggleconsole", Con_ToggleConsole_f);
Cmd_AddCommand ("togglemenu", Con_ToggleMenu_f);
Cmd_AddCommand ("messagemode", Con_MessageMode_f);
Cmd_AddCommand ("messagemode2", Con_MessageMode2_f);
Cmd_AddCommand ("messagemode3", Con_MessageMode3_f);
Cmd_AddCommand ("messagemode4", Con_MessageMode4_f);
Cmd_AddCommand ("clear", Con_Clear_f);
Cmd_AddCommand ("condump", Con_Dump_f);
Cmd_SetCommandCompletionFunc( "condump", Cmd_CompleteTxtName );
}
/*
================
Con_Shutdown
================
*/
void Con_Shutdown(void)
{
Cmd_RemoveCommand("toggleconsole");
Cmd_RemoveCommand("togglemenu");
Cmd_RemoveCommand("messagemode");
Cmd_RemoveCommand("messagemode2");
Cmd_RemoveCommand("messagemode3");
Cmd_RemoveCommand("messagemode4");
Cmd_RemoveCommand("clear");
Cmd_RemoveCommand("condump");
}
/*
===============
Con_Linefeed
===============
*/
void Con_Linefeed (qboolean skipnotify)
{
int i;
// mark time for transparent overlay
if (con.current >= 0)
{
if (skipnotify)
con.times[con.current % NUM_CON_TIMES] = 0;
else
con.times[con.current % NUM_CON_TIMES] = cls.realtime;
}
con.x = 0;
if (con.display == con.current)
con.display++;
con.current++;
for(i=0; i<con.linewidth; i++)
con.text[(con.current%con.totallines)*con.linewidth+i] = (ColorIndex(COLOR_WHITE)<<8) | ' ';
}
/*
================
CL_ConsolePrint
Handles cursor positioning, line wrapping, etc
All console printing must go through this in order to be logged to disk
If no console is visible, the text will appear at the top of the game window
================
*/
void CL_ConsolePrint( char *txt ) {
int y, l;
unsigned char c;
unsigned short color;
qboolean skipnotify = qfalse; // NERVE - SMF
int prev; // NERVE - SMF
// TTimo - prefix for text that shows up in console but not in notify
// backported from RTCW
if ( !Q_strncmp( txt, "[skipnotify]", 12 ) ) {
skipnotify = qtrue;
txt += 12;
}
// for some demos we don't want to ever show anything on the console
if ( cl_noprint && cl_noprint->integer ) {
return;
}
if (!con.initialized) {
con.color[0] =
con.color[1] =
con.color[2] =
con.color[3] = 1.0f;
con.linewidth = -1;
Con_CheckResize ();
con.initialized = qtrue;
}
color = ColorIndex(COLOR_WHITE);
while ( (c = *((unsigned char *) txt)) != 0 ) {
if ( Q_IsColorString( txt ) ) {
color = ColorIndex( *(txt+1) );
txt += 2;
continue;
}
// count word length
for (l=0 ; l< con.linewidth ; l++) {
if ( txt[l] <= ' ') {
break;
}
}
// word wrap
if (l != con.linewidth && (con.x + l >= con.linewidth) ) {
Con_Linefeed(skipnotify);
}
txt++;
switch (c)
{
case '\n':
Con_Linefeed (skipnotify);
break;
case '\r':
con.x = 0;
break;
default: // display character and advance
y = con.current % con.totallines;
con.text[y*con.linewidth+con.x] = (color << 8) | c;
con.x++;
if(con.x >= con.linewidth)
Con_Linefeed(skipnotify);
break;
}
}
// mark time for transparent overlay
if (con.current >= 0) {
// NERVE - SMF
if ( skipnotify ) {
prev = con.current % NUM_CON_TIMES - 1;
if ( prev < 0 )
prev = NUM_CON_TIMES - 1;
con.times[prev] = 0;
}
else
// -NERVE - SMF
con.times[con.current % NUM_CON_TIMES] = cls.realtime;
}
}
/*
==============================================================================
DRAWING
==============================================================================
*/
/*
================
Con_DrawInput
Draw the editline after a ] prompt
================
*/
void Con_DrawInput (void) {
int y;
if ( clc.state != CA_DISCONNECTED && !(Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ) {
return;
}
y = con.vislines - ( SMALLCHAR_HEIGHT * 2 );
re.SetColor( con.color );
SCR_DrawSmallChar( con.xadjust + 1 * SMALLCHAR_WIDTH, y, ']' );
Field_Draw( &g_consoleField, con.xadjust + 2 * SMALLCHAR_WIDTH, y,
SCREEN_WIDTH - 3 * SMALLCHAR_WIDTH, qtrue, qtrue );
}
/*
================
Con_DrawNotify
Draws the last few lines of output transparently over the game top
================
*/
void Con_DrawNotify (void)
{
int x, v;
short *text;
int i;
int time;
int skip;
int currentColor;
currentColor = 7;
re.SetColor( g_color_table[currentColor] );
v = 0;
for (i= con.current-NUM_CON_TIMES+1 ; i<=con.current ; i++)
{
if (i < 0)
continue;
time = con.times[i % NUM_CON_TIMES];
if (time == 0)
continue;
time = cls.realtime - time;
if (time > con_notifytime->value*1000)
continue;
text = con.text + (i % con.totallines)*con.linewidth;
if (cl.snap.ps.pm_type != PM_INTERMISSION && Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME) ) {
continue;
}
for (x = 0 ; x < con.linewidth ; x++) {
if ( ( text[x] & 0xff ) == ' ' ) {
continue;
}
if ( ColorIndexForNumber( text[x]>>8 ) != currentColor ) {
currentColor = ColorIndexForNumber( text[x]>>8 );
re.SetColor( g_color_table[currentColor] );
}
SCR_DrawSmallChar( cl_conXOffset->integer + con.xadjust + (x+1)*SMALLCHAR_WIDTH, v, text[x] & 0xff );
}
v += SMALLCHAR_HEIGHT;
}
re.SetColor( NULL );
if (Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME) ) {
return;
}
// draw the chat line
if ( Key_GetCatcher( ) & KEYCATCH_MESSAGE )
{
if (chat_team)
{
SCR_DrawBigString (8, v, "say_team:", 1.0f, qfalse );
skip = 10;
}
else
{
SCR_DrawBigString (8, v, "say:", 1.0f, qfalse );
skip = 5;
}
Field_BigDraw( &chatField, skip * BIGCHAR_WIDTH, v,
SCREEN_WIDTH - ( skip + 1 ) * BIGCHAR_WIDTH, qtrue, qtrue );
}
}
/*
================
Con_DrawSolidConsole
Draws the console with the solid background
================
*/
void Con_DrawSolidConsole( float frac ) {
int i, x, y;
int rows;
short *text;
int row;
int lines;
// qhandle_t conShader;
int currentColor;
vec4_t color;
lines = cls.glconfig.vidHeight * frac;
if (lines <= 0)
return;
if (lines > cls.glconfig.vidHeight )
lines = cls.glconfig.vidHeight;
// on wide screens, we will center the text
con.xadjust = 0;
SCR_AdjustFrom640( &con.xadjust, NULL, NULL, NULL );
// draw the background
y = frac * SCREEN_HEIGHT;
if ( y < 1 ) {
y = 0;
}
else {
SCR_DrawPic( 0, 0, SCREEN_WIDTH, y, cls.consoleShader );
}
color[0] = 1;
color[1] = 0;
color[2] = 0;
color[3] = 1;
SCR_FillRect( 0, y, SCREEN_WIDTH, 2, color );
// draw the version number
re.SetColor( g_color_table[ColorIndex(COLOR_RED)] );
i = strlen( Q3_VERSION );
for (x=0 ; x<i ; x++) {
SCR_DrawSmallChar( cls.glconfig.vidWidth - ( i - x + 1 ) * SMALLCHAR_WIDTH,
lines - SMALLCHAR_HEIGHT, Q3_VERSION[x] );
}
// draw the text
con.vislines = lines;
rows = (lines-SMALLCHAR_HEIGHT)/SMALLCHAR_HEIGHT; // rows of text to draw
y = lines - (SMALLCHAR_HEIGHT*3);
// draw from the bottom up
if (con.display != con.current)
{
// draw arrows to show the buffer is backscrolled
re.SetColor( g_color_table[ColorIndex(COLOR_RED)] );
for (x=0 ; x<con.linewidth ; x+=4)
SCR_DrawSmallChar( con.xadjust + (x+1)*SMALLCHAR_WIDTH, y, '^' );
y -= SMALLCHAR_HEIGHT;
rows--;
}
row = con.display;
if ( con.x == 0 ) {
row--;
}
currentColor = 7;
re.SetColor( g_color_table[currentColor] );
for (i=0 ; i<rows ; i++, y -= SMALLCHAR_HEIGHT, row--)
{
if (row < 0)
break;
if (con.current - row >= con.totallines) {
// past scrollback wrap point
continue;
}
text = con.text + (row % con.totallines)*con.linewidth;
for (x=0 ; x<con.linewidth ; x++) {
if ( ( text[x] & 0xff ) == ' ' ) {
continue;
}
if ( ColorIndexForNumber( text[x]>>8 ) != currentColor ) {
currentColor = ColorIndexForNumber( text[x]>>8 );
re.SetColor( g_color_table[currentColor] );
}
SCR_DrawSmallChar( con.xadjust + (x+1)*SMALLCHAR_WIDTH, y, text[x] & 0xff );
}
}
// draw the input prompt, user text, and cursor if desired
Con_DrawInput ();
re.SetColor( NULL );
}
/*
==================
Con_DrawConsole
==================
*/
void Con_DrawConsole( void ) {
// check for console width changes from a vid mode change
Con_CheckResize ();
// if disconnected, render console full screen
if ( clc.state == CA_DISCONNECTED ) {
if ( !( Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME)) ) {
Con_DrawSolidConsole( 1.0 );
return;
}
}
if ( con.displayFrac ) {
Con_DrawSolidConsole( con.displayFrac );
} else {
// draw notify lines
if ( clc.state == CA_ACTIVE ) {
Con_DrawNotify ();
}
}
}
//================================================================
/*
==================
Con_RunConsole
Scroll it up or down
==================
*/
void Con_RunConsole (void) {
// decide on the destination height of the console
if ( Key_GetCatcher( ) & KEYCATCH_CONSOLE )
con.finalFrac = 0.5; // half screen
else
con.finalFrac = 0; // none visible
// scroll towards the destination height
if (con.finalFrac < con.displayFrac)
{
con.displayFrac -= con_conspeed->value*cls.realFrametime*0.001;
if (con.finalFrac > con.displayFrac)
con.displayFrac = con.finalFrac;
}
else if (con.finalFrac > con.displayFrac)
{
con.displayFrac += con_conspeed->value*cls.realFrametime*0.001;
if (con.finalFrac < con.displayFrac)
con.displayFrac = con.finalFrac;
}
}
void Con_PageUp( void ) {
con.display -= 2;
if ( con.current - con.display >= con.totallines ) {
con.display = con.current - con.totallines + 1;
}
}
void Con_PageDown( void ) {
con.display += 2;
if (con.display > con.current) {
con.display = con.current;
}
}
void Con_Top( void ) {
con.display = con.totallines;
if ( con.current - con.display >= con.totallines ) {
con.display = con.current - con.totallines + 1;
}
}
void Con_Bottom( void ) {
con.display = con.current;
}
void Con_Close( void ) {
if ( !com_cl_running->integer ) {
return;
}
Field_Clear( &g_consoleField );
Con_ClearNotify ();
Key_SetCatcher( Key_GetCatcher( ) & ~KEYCATCH_CONSOLE );
con.finalFrac = 0; // none visible
con.displayFrac = 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3229_0 |
crossvul-cpp_data_good_3230_0 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
Copyright (C) 2005 Stuart Dalton (badcdev@gmail.com)
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "snd_local.h"
#include "snd_codec.h"
#include "client.h"
#ifdef USE_OPENAL
#include "qal.h"
// Console variables specific to OpenAL
cvar_t *s_alPrecache;
cvar_t *s_alGain;
cvar_t *s_alSources;
cvar_t *s_alDopplerFactor;
cvar_t *s_alDopplerSpeed;
cvar_t *s_alMinDistance;
cvar_t *s_alMaxDistance;
cvar_t *s_alRolloff;
cvar_t *s_alGraceDistance;
cvar_t *s_alDriver;
cvar_t *s_alDevice;
cvar_t *s_alInputDevice;
cvar_t *s_alAvailableDevices;
cvar_t *s_alAvailableInputDevices;
static qboolean enumeration_ext = qfalse;
static qboolean enumeration_all_ext = qfalse;
#ifdef USE_VOIP
static qboolean capture_ext = qfalse;
#endif
/*
=================
S_AL_Format
=================
*/
static
ALuint S_AL_Format(int width, int channels)
{
ALuint format = AL_FORMAT_MONO16;
// Work out format
if(width == 1)
{
if(channels == 1)
format = AL_FORMAT_MONO8;
else if(channels == 2)
format = AL_FORMAT_STEREO8;
}
else if(width == 2)
{
if(channels == 1)
format = AL_FORMAT_MONO16;
else if(channels == 2)
format = AL_FORMAT_STEREO16;
}
return format;
}
/*
=================
S_AL_ErrorMsg
=================
*/
static const char *S_AL_ErrorMsg(ALenum error)
{
switch(error)
{
case AL_NO_ERROR:
return "No error";
case AL_INVALID_NAME:
return "Invalid name";
case AL_INVALID_ENUM:
return "Invalid enumerator";
case AL_INVALID_VALUE:
return "Invalid value";
case AL_INVALID_OPERATION:
return "Invalid operation";
case AL_OUT_OF_MEMORY:
return "Out of memory";
default:
return "Unknown error";
}
}
/*
=================
S_AL_ClearError
=================
*/
static void S_AL_ClearError( qboolean quiet )
{
int error = qalGetError();
if( quiet )
return;
if(error != AL_NO_ERROR)
{
Com_Printf(S_COLOR_YELLOW "WARNING: unhandled AL error: %s\n",
S_AL_ErrorMsg(error));
}
}
//===========================================================================
typedef struct alSfx_s
{
char filename[MAX_QPATH];
ALuint buffer; // OpenAL buffer
snd_info_t info; // information for this sound like rate, sample count..
qboolean isDefault; // Couldn't be loaded - use default FX
qboolean isDefaultChecked; // Sound has been check if it isDefault
qboolean inMemory; // Sound is stored in memory
qboolean isLocked; // Sound is locked (can not be unloaded)
int lastUsedTime; // Time last used
int loopCnt; // number of loops using this sfx
int loopActiveCnt; // number of playing loops using this sfx
int masterLoopSrc; // All other sources looping this buffer are synced to this master src
} alSfx_t;
static qboolean alBuffersInitialised = qfalse;
// Sound effect storage, data structures
#define MAX_SFX 4096
static alSfx_t knownSfx[MAX_SFX];
static sfxHandle_t numSfx = 0;
static sfxHandle_t default_sfx;
/*
=================
S_AL_BufferFindFree
Find a free handle
=================
*/
static sfxHandle_t S_AL_BufferFindFree( void )
{
int i;
for(i = 0; i < MAX_SFX; i++)
{
// Got one
if(knownSfx[i].filename[0] == '\0')
{
if(i >= numSfx)
numSfx = i + 1;
return i;
}
}
// Shit...
Com_Error(ERR_FATAL, "S_AL_BufferFindFree: No free sound handles");
return -1;
}
/*
=================
S_AL_BufferFind
Find a sound effect if loaded, set up a handle otherwise
=================
*/
static sfxHandle_t S_AL_BufferFind(const char *filename)
{
// Look it up in the table
sfxHandle_t sfx = -1;
int i;
if ( !filename ) {
Com_Error( ERR_FATAL, "Sound name is NULL" );
}
if ( !filename[0] ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is empty\n" );
return 0;
}
if ( strlen( filename ) >= MAX_QPATH ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is too long: %s\n", filename );
return 0;
}
if ( filename[0] == '*' ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Tried to load player sound directly: %s\n", filename );
return 0;
}
for(i = 0; i < numSfx; i++)
{
if(!Q_stricmp(knownSfx[i].filename, filename))
{
sfx = i;
break;
}
}
// Not found in table?
if(sfx == -1)
{
alSfx_t *ptr;
sfx = S_AL_BufferFindFree();
// Clear and copy the filename over
ptr = &knownSfx[sfx];
memset(ptr, 0, sizeof(*ptr));
ptr->masterLoopSrc = -1;
strcpy(ptr->filename, filename);
}
// Return the handle
return sfx;
}
/*
=================
S_AL_BufferUseDefault
=================
*/
static void S_AL_BufferUseDefault(sfxHandle_t sfx)
{
if(sfx == default_sfx)
Com_Error(ERR_FATAL, "Can't load default sound effect %s", knownSfx[sfx].filename);
Com_Printf( S_COLOR_YELLOW "WARNING: Using default sound for %s\n", knownSfx[sfx].filename);
knownSfx[sfx].isDefault = qtrue;
knownSfx[sfx].buffer = knownSfx[default_sfx].buffer;
}
/*
=================
S_AL_BufferUnload
=================
*/
static void S_AL_BufferUnload(sfxHandle_t sfx)
{
if(knownSfx[sfx].filename[0] == '\0')
return;
if(!knownSfx[sfx].inMemory)
return;
// Delete it
S_AL_ClearError( qfalse );
qalDeleteBuffers(1, &knownSfx[sfx].buffer);
if(qalGetError() != AL_NO_ERROR)
Com_Printf( S_COLOR_RED "ERROR: Can't delete sound buffer for %s\n",
knownSfx[sfx].filename);
knownSfx[sfx].inMemory = qfalse;
}
/*
=================
S_AL_BufferEvict
=================
*/
static qboolean S_AL_BufferEvict( void )
{
int i, oldestBuffer = -1;
int oldestTime = Sys_Milliseconds( );
for( i = 0; i < numSfx; i++ )
{
if( !knownSfx[ i ].filename[ 0 ] )
continue;
if( !knownSfx[ i ].inMemory )
continue;
if( knownSfx[ i ].lastUsedTime < oldestTime )
{
oldestTime = knownSfx[ i ].lastUsedTime;
oldestBuffer = i;
}
}
if( oldestBuffer >= 0 )
{
S_AL_BufferUnload( oldestBuffer );
return qtrue;
}
else
return qfalse;
}
/*
=================
S_AL_GenBuffers
=================
*/
static qboolean S_AL_GenBuffers(ALsizei numBuffers, ALuint *buffers, const char *name)
{
ALenum error;
S_AL_ClearError( qfalse );
qalGenBuffers( numBuffers, buffers );
error = qalGetError();
// If we ran out of buffers, start evicting the least recently used sounds
while( error == AL_INVALID_VALUE )
{
if( !S_AL_BufferEvict( ) )
{
Com_Printf( S_COLOR_RED "ERROR: Out of audio buffers\n");
return qfalse;
}
// Try again
S_AL_ClearError( qfalse );
qalGenBuffers( numBuffers, buffers );
error = qalGetError();
}
if( error != AL_NO_ERROR )
{
Com_Printf( S_COLOR_RED "ERROR: Can't create a sound buffer for %s - %s\n",
name, S_AL_ErrorMsg(error));
return qfalse;
}
return qtrue;
}
/*
=================
S_AL_BufferLoad
=================
*/
static void S_AL_BufferLoad(sfxHandle_t sfx, qboolean cache)
{
ALenum error;
ALuint format;
void *data;
snd_info_t info;
alSfx_t *curSfx = &knownSfx[sfx];
// Nothing?
if(curSfx->filename[0] == '\0')
return;
// Already done?
if((curSfx->inMemory) || (curSfx->isDefault) || (!cache && curSfx->isDefaultChecked))
return;
// Try to load
data = S_CodecLoad(curSfx->filename, &info);
if(!data)
{
S_AL_BufferUseDefault(sfx);
return;
}
curSfx->isDefaultChecked = qtrue;
if (!cache)
{
// Don't create AL cache
Hunk_FreeTempMemory(data);
return;
}
format = S_AL_Format(info.width, info.channels);
// Create a buffer
if (!S_AL_GenBuffers(1, &curSfx->buffer, curSfx->filename))
{
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
return;
}
// Fill the buffer
if( info.size == 0 )
{
// We have no data to buffer, so buffer silence
byte dummyData[ 2 ] = { 0 };
qalBufferData(curSfx->buffer, AL_FORMAT_MONO16, (void *)dummyData, 2, 22050);
}
else
qalBufferData(curSfx->buffer, format, data, info.size, info.rate);
error = qalGetError();
// If we ran out of memory, start evicting the least recently used sounds
while(error == AL_OUT_OF_MEMORY)
{
if( !S_AL_BufferEvict( ) )
{
qalDeleteBuffers(1, &curSfx->buffer);
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
Com_Printf( S_COLOR_RED "ERROR: Out of memory loading %s\n", curSfx->filename);
return;
}
// Try load it again
qalBufferData(curSfx->buffer, format, data, info.size, info.rate);
error = qalGetError();
}
// Some other error condition
if(error != AL_NO_ERROR)
{
qalDeleteBuffers(1, &curSfx->buffer);
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
Com_Printf( S_COLOR_RED "ERROR: Can't fill sound buffer for %s - %s\n",
curSfx->filename, S_AL_ErrorMsg(error));
return;
}
curSfx->info = info;
// Free the memory
Hunk_FreeTempMemory(data);
// Woo!
curSfx->inMemory = qtrue;
}
/*
=================
S_AL_BufferUse
=================
*/
static
void S_AL_BufferUse(sfxHandle_t sfx)
{
if(knownSfx[sfx].filename[0] == '\0')
return;
if((!knownSfx[sfx].inMemory) && (!knownSfx[sfx].isDefault))
S_AL_BufferLoad(sfx, qtrue);
knownSfx[sfx].lastUsedTime = Sys_Milliseconds();
}
/*
=================
S_AL_BufferInit
=================
*/
static
qboolean S_AL_BufferInit( void )
{
if(alBuffersInitialised)
return qtrue;
// Clear the hash table, and SFX table
memset(knownSfx, 0, sizeof(knownSfx));
numSfx = 0;
// Load the default sound, and lock it
default_sfx = S_AL_BufferFind("sound/feedback/hit.wav");
S_AL_BufferUse(default_sfx);
knownSfx[default_sfx].isLocked = qtrue;
// All done
alBuffersInitialised = qtrue;
return qtrue;
}
/*
=================
S_AL_BufferShutdown
=================
*/
static
void S_AL_BufferShutdown( void )
{
int i;
if(!alBuffersInitialised)
return;
// Unlock the default sound effect
knownSfx[default_sfx].isLocked = qfalse;
// Free all used effects
for(i = 0; i < numSfx; i++)
S_AL_BufferUnload(i);
// Clear the tables
numSfx = 0;
// All undone
alBuffersInitialised = qfalse;
}
/*
=================
S_AL_RegisterSound
=================
*/
static
sfxHandle_t S_AL_RegisterSound( const char *sample, qboolean compressed )
{
sfxHandle_t sfx = S_AL_BufferFind(sample);
if((!knownSfx[sfx].inMemory) && (!knownSfx[sfx].isDefault))
S_AL_BufferLoad(sfx, s_alPrecache->integer);
knownSfx[sfx].lastUsedTime = Com_Milliseconds();
if (knownSfx[sfx].isDefault) {
return 0;
}
return sfx;
}
/*
=================
S_AL_BufferGet
Return's a sfx's buffer
=================
*/
static
ALuint S_AL_BufferGet(sfxHandle_t sfx)
{
return knownSfx[sfx].buffer;
}
//===========================================================================
typedef struct src_s
{
ALuint alSource; // OpenAL source object
sfxHandle_t sfx; // Sound effect in use
int lastUsedTime; // Last time used
alSrcPriority_t priority; // Priority
int entity; // Owning entity (-1 if none)
int channel; // Associated channel (-1 if none)
qboolean isActive; // Is this source currently in use?
qboolean isPlaying; // Is this source currently playing, or stopped?
qboolean isLocked; // This is locked (un-allocatable)
qboolean isLooping; // Is this a looping effect (attached to an entity)
qboolean isTracking; // Is this object tracking its owner
qboolean isStream; // Is this source a stream
float curGain; // gain employed if source is within maxdistance.
float scaleGain; // Last gain value for this source. 0 if muted.
float lastTimePos; // On stopped loops, the last position in the buffer
int lastSampleTime; // Time when this was stopped
vec3_t loopSpeakerPos; // Origin of the loop speaker
qboolean local; // Is this local (relative to the cam)
} src_t;
#ifdef __APPLE__
#define MAX_SRC 64
#else
#define MAX_SRC 128
#endif
static src_t srcList[MAX_SRC];
static int srcCount = 0;
static int srcActiveCnt = 0;
static qboolean alSourcesInitialised = qfalse;
static int lastListenerNumber = -1;
static vec3_t lastListenerOrigin = { 0.0f, 0.0f, 0.0f };
typedef struct sentity_s
{
vec3_t origin;
qboolean srcAllocated; // If a src_t has been allocated to this entity
int srcIndex;
qboolean loopAddedThisFrame;
alSrcPriority_t loopPriority;
sfxHandle_t loopSfx;
qboolean startLoopingSound;
} sentity_t;
static sentity_t entityList[MAX_GENTITIES];
/*
=================
S_AL_SanitiseVector
=================
*/
#define S_AL_SanitiseVector(v) _S_AL_SanitiseVector(v,__LINE__)
static void _S_AL_SanitiseVector( vec3_t v, int line )
{
if( Q_isnan( v[ 0 ] ) || Q_isnan( v[ 1 ] ) || Q_isnan( v[ 2 ] ) )
{
Com_DPrintf( S_COLOR_YELLOW "WARNING: vector with one or more NaN components "
"being passed to OpenAL at %s:%d -- zeroing\n", __FILE__, line );
VectorClear( v );
}
}
/*
=================
S_AL_Gain
Set gain to 0 if muted, otherwise set it to given value.
=================
*/
static void S_AL_Gain(ALuint source, float gainval)
{
if(s_muted->integer)
qalSourcef(source, AL_GAIN, 0.0f);
else
qalSourcef(source, AL_GAIN, gainval);
}
/*
=================
S_AL_ScaleGain
Adapt the gain if necessary to get a quicker fadeout when the source is too far away.
=================
*/
static void S_AL_ScaleGain(src_t *chksrc, vec3_t origin)
{
float distance;
if(!chksrc->local)
distance = Distance(origin, lastListenerOrigin);
// If we exceed a certain distance, scale the gain linearly until the sound
// vanishes into nothingness.
if(!chksrc->local && (distance -= s_alMaxDistance->value) > 0)
{
float scaleFactor;
if(distance >= s_alGraceDistance->value)
scaleFactor = 0.0f;
else
scaleFactor = 1.0f - distance / s_alGraceDistance->value;
scaleFactor *= chksrc->curGain;
if(chksrc->scaleGain != scaleFactor)
{
chksrc->scaleGain = scaleFactor;
S_AL_Gain(chksrc->alSource, chksrc->scaleGain);
}
}
else if(chksrc->scaleGain != chksrc->curGain)
{
chksrc->scaleGain = chksrc->curGain;
S_AL_Gain(chksrc->alSource, chksrc->scaleGain);
}
}
/*
=================
S_AL_HearingThroughEntity
Also see S_Base_HearingThroughEntity
=================
*/
static qboolean S_AL_HearingThroughEntity( int entityNum )
{
float distanceSq;
if( lastListenerNumber == entityNum )
{
// This is an outrageous hack to detect
// whether or not the player is rendering in third person or not. We can't
// ask the renderer because the renderer has no notion of entities and we
// can't ask cgame since that would involve changing the API and hence mod
// compatibility. I don't think there is any way around this, but I'll leave
// the FIXME just in case anyone has a bright idea.
distanceSq = DistanceSquared(
entityList[ entityNum ].origin,
lastListenerOrigin );
if( distanceSq > THIRD_PERSON_THRESHOLD_SQ )
return qfalse; //we're the player, but third person
else
return qtrue; //we're the player
}
else
return qfalse; //not the player
}
/*
=================
S_AL_SrcInit
=================
*/
static
qboolean S_AL_SrcInit( void )
{
int i;
int limit;
// Clear the sources data structure
memset(srcList, 0, sizeof(srcList));
srcCount = 0;
srcActiveCnt = 0;
// Cap s_alSources to MAX_SRC
limit = s_alSources->integer;
if(limit > MAX_SRC)
limit = MAX_SRC;
else if(limit < 16)
limit = 16;
S_AL_ClearError( qfalse );
// Allocate as many sources as possible
for(i = 0; i < limit; i++)
{
qalGenSources(1, &srcList[i].alSource);
if(qalGetError() != AL_NO_ERROR)
break;
srcCount++;
}
// All done. Print this for informational purposes
Com_Printf( "Allocated %d sources.\n", srcCount);
alSourcesInitialised = qtrue;
return qtrue;
}
/*
=================
S_AL_SrcShutdown
=================
*/
static
void S_AL_SrcShutdown( void )
{
int i;
src_t *curSource;
if(!alSourcesInitialised)
return;
// Destroy all the sources
for(i = 0; i < srcCount; i++)
{
curSource = &srcList[i];
if(curSource->isLocked)
Com_DPrintf( S_COLOR_YELLOW "WARNING: Source %d is locked\n", i);
if(curSource->entity > 0)
entityList[curSource->entity].srcAllocated = qfalse;
qalSourceStop(srcList[i].alSource);
qalDeleteSources(1, &srcList[i].alSource);
}
memset(srcList, 0, sizeof(srcList));
alSourcesInitialised = qfalse;
}
/*
=================
S_AL_SrcSetup
=================
*/
static void S_AL_SrcSetup(srcHandle_t src, sfxHandle_t sfx, alSrcPriority_t priority,
int entity, int channel, qboolean local)
{
src_t *curSource;
// Set up src struct
curSource = &srcList[src];
curSource->lastUsedTime = Sys_Milliseconds();
curSource->sfx = sfx;
curSource->priority = priority;
curSource->entity = entity;
curSource->channel = channel;
curSource->isPlaying = qfalse;
curSource->isLocked = qfalse;
curSource->isLooping = qfalse;
curSource->isTracking = qfalse;
curSource->isStream = qfalse;
curSource->curGain = s_alGain->value * s_volume->value;
curSource->scaleGain = curSource->curGain;
curSource->local = local;
// Set up OpenAL source
if(sfx >= 0)
{
// Mark the SFX as used, and grab the raw AL buffer
S_AL_BufferUse(sfx);
qalSourcei(curSource->alSource, AL_BUFFER, S_AL_BufferGet(sfx));
}
qalSourcef(curSource->alSource, AL_PITCH, 1.0f);
S_AL_Gain(curSource->alSource, curSource->curGain);
qalSourcefv(curSource->alSource, AL_POSITION, vec3_origin);
qalSourcefv(curSource->alSource, AL_VELOCITY, vec3_origin);
qalSourcei(curSource->alSource, AL_LOOPING, AL_FALSE);
qalSourcef(curSource->alSource, AL_REFERENCE_DISTANCE, s_alMinDistance->value);
if(local)
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_TRUE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, 0.0f);
}
else
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_FALSE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
}
}
/*
=================
S_AL_SaveLoopPos
Remove given source as loop master if it is the master and hand off master status to another source in this case.
=================
*/
static void S_AL_SaveLoopPos(src_t *dest, ALuint alSource)
{
int error;
S_AL_ClearError(qfalse);
qalGetSourcef(alSource, AL_SEC_OFFSET, &dest->lastTimePos);
if((error = qalGetError()) != AL_NO_ERROR)
{
// Old OpenAL implementations don't support AL_SEC_OFFSET
if(error != AL_INVALID_ENUM)
{
Com_Printf(S_COLOR_YELLOW "WARNING: Could not get time offset for alSource %d: %s\n",
alSource, S_AL_ErrorMsg(error));
}
dest->lastTimePos = -1;
}
else
dest->lastSampleTime = Sys_Milliseconds();
}
/*
=================
S_AL_NewLoopMaster
Remove given source as loop master if it is the master and hand off master status to another source in this case.
=================
*/
static void S_AL_NewLoopMaster(src_t *rmSource, qboolean iskilled)
{
int index;
src_t *curSource = NULL;
alSfx_t *curSfx;
curSfx = &knownSfx[rmSource->sfx];
if(rmSource->isPlaying)
curSfx->loopActiveCnt--;
if(iskilled)
curSfx->loopCnt--;
if(curSfx->loopCnt)
{
if(rmSource->priority == SRCPRI_ENTITY)
{
if(!iskilled && rmSource->isPlaying)
{
// only sync ambient loops...
// It makes more sense to have sounds for weapons/projectiles unsynced
S_AL_SaveLoopPos(rmSource, rmSource->alSource);
}
}
else if(rmSource == &srcList[curSfx->masterLoopSrc])
{
int firstInactive = -1;
// Only if rmSource was the master and if there are still playing loops for
// this sound will we need to find a new master.
if(iskilled || curSfx->loopActiveCnt)
{
for(index = 0; index < srcCount; index++)
{
curSource = &srcList[index];
if(curSource->sfx == rmSource->sfx && curSource != rmSource &&
curSource->isActive && curSource->isLooping && curSource->priority == SRCPRI_AMBIENT)
{
if(curSource->isPlaying)
{
curSfx->masterLoopSrc = index;
break;
}
else if(firstInactive < 0)
firstInactive = index;
}
}
}
if(!curSfx->loopActiveCnt)
{
if(firstInactive < 0)
{
if(iskilled)
{
curSfx->masterLoopSrc = -1;
return;
}
else
curSource = rmSource;
}
else
curSource = &srcList[firstInactive];
if(rmSource->isPlaying)
{
// this was the last not stopped source, save last sample position + time
S_AL_SaveLoopPos(curSource, rmSource->alSource);
}
else
{
// second case: all loops using this sound have stopped due to listener being of of range,
// and now the inactive master gets deleted. Just move over the soundpos settings to the
// new master.
curSource->lastTimePos = rmSource->lastTimePos;
curSource->lastSampleTime = rmSource->lastSampleTime;
}
}
}
}
else
curSfx->masterLoopSrc = -1;
}
/*
=================
S_AL_SrcKill
=================
*/
static void S_AL_SrcKill(srcHandle_t src)
{
src_t *curSource = &srcList[src];
// I'm not touching it. Unlock it first.
if(curSource->isLocked)
return;
// Remove the entity association and loop master status
if(curSource->isLooping)
{
curSource->isLooping = qfalse;
if(curSource->entity != -1)
{
sentity_t *curEnt = &entityList[curSource->entity];
curEnt->srcAllocated = qfalse;
curEnt->srcIndex = -1;
curEnt->loopAddedThisFrame = qfalse;
curEnt->startLoopingSound = qfalse;
}
S_AL_NewLoopMaster(curSource, qtrue);
}
// Stop it if it's playing
if(curSource->isPlaying)
{
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
// Detach any buffers
qalSourcei(curSource->alSource, AL_BUFFER, 0);
curSource->sfx = 0;
curSource->lastUsedTime = 0;
curSource->priority = 0;
curSource->entity = -1;
curSource->channel = -1;
if(curSource->isActive)
{
curSource->isActive = qfalse;
srcActiveCnt--;
}
curSource->isLocked = qfalse;
curSource->isTracking = qfalse;
curSource->local = qfalse;
}
/*
=================
S_AL_SrcAlloc
=================
*/
static
srcHandle_t S_AL_SrcAlloc( alSrcPriority_t priority, int entnum, int channel )
{
int i;
int empty = -1;
int weakest = -1;
int weakest_time = Sys_Milliseconds();
int weakest_pri = 999;
float weakest_gain = 1000.0;
qboolean weakest_isplaying = qtrue;
int weakest_numloops = 0;
src_t *curSource;
for(i = 0; i < srcCount; i++)
{
curSource = &srcList[i];
// If it's locked, we aren't even going to look at it
if(curSource->isLocked)
continue;
// Is it empty or not?
if(!curSource->isActive)
{
empty = i;
break;
}
if(curSource->isPlaying)
{
if(weakest_isplaying && curSource->priority < priority &&
(curSource->priority < weakest_pri ||
(!curSource->isLooping && (curSource->scaleGain < weakest_gain || curSource->lastUsedTime < weakest_time))))
{
// If it has lower priority, is fainter or older, flag it as weak
// the last two values are only compared if it's not a looping sound, because we want to prevent two
// loops (loops are added EVERY frame) fighting for a slot
weakest_pri = curSource->priority;
weakest_time = curSource->lastUsedTime;
weakest_gain = curSource->scaleGain;
weakest = i;
}
}
else
{
weakest_isplaying = qfalse;
if(weakest < 0 ||
knownSfx[curSource->sfx].loopCnt > weakest_numloops ||
curSource->priority < weakest_pri ||
curSource->lastUsedTime < weakest_time)
{
// Sources currently not playing of course have lowest priority
// also try to always keep at least one loop master for every loop sound
weakest_pri = curSource->priority;
weakest_time = curSource->lastUsedTime;
weakest_numloops = knownSfx[curSource->sfx].loopCnt;
weakest = i;
}
}
// The channel system is not actually adhered to by baseq3, and not
// implemented in snd_dma.c, so while the following is strictly correct, it
// causes incorrect behaviour versus defacto baseq3
#if 0
// Is it an exact match, and not on channel 0?
if((curSource->entity == entnum) && (curSource->channel == channel) && (channel != 0))
{
S_AL_SrcKill(i);
return i;
}
#endif
}
if(empty == -1)
empty = weakest;
if(empty >= 0)
{
S_AL_SrcKill(empty);
srcList[empty].isActive = qtrue;
srcActiveCnt++;
}
return empty;
}
/*
=================
S_AL_SrcFind
Finds an active source with matching entity and channel numbers
Returns -1 if there isn't one
=================
*/
#if 0
static
srcHandle_t S_AL_SrcFind(int entnum, int channel)
{
int i;
for(i = 0; i < srcCount; i++)
{
if(!srcList[i].isActive)
continue;
if((srcList[i].entity == entnum) && (srcList[i].channel == channel))
return i;
}
return -1;
}
#endif
/*
=================
S_AL_SrcLock
Locked sources will not be automatically reallocated or managed
=================
*/
static
void S_AL_SrcLock(srcHandle_t src)
{
srcList[src].isLocked = qtrue;
}
/*
=================
S_AL_SrcUnlock
Once unlocked, the source may be reallocated again
=================
*/
static
void S_AL_SrcUnlock(srcHandle_t src)
{
srcList[src].isLocked = qfalse;
}
/*
=================
S_AL_UpdateEntityPosition
=================
*/
static
void S_AL_UpdateEntityPosition( int entityNum, const vec3_t origin )
{
vec3_t sanOrigin;
VectorCopy( origin, sanOrigin );
S_AL_SanitiseVector( sanOrigin );
if ( entityNum < 0 || entityNum >= MAX_GENTITIES )
Com_Error( ERR_DROP, "S_UpdateEntityPosition: bad entitynum %i", entityNum );
VectorCopy( sanOrigin, entityList[entityNum].origin );
}
/*
=================
S_AL_CheckInput
Check whether input values from mods are out of range.
Necessary for i.g. Western Quake3 mod which is buggy.
=================
*/
static qboolean S_AL_CheckInput(int entityNum, sfxHandle_t sfx)
{
if (entityNum < 0 || entityNum >= MAX_GENTITIES)
Com_Error(ERR_DROP, "ERROR: S_AL_CheckInput: bad entitynum %i", entityNum);
if (sfx < 0 || sfx >= numSfx)
{
Com_Printf(S_COLOR_RED "ERROR: S_AL_CheckInput: handle %i out of range\n", sfx);
return qtrue;
}
return qfalse;
}
/*
=================
S_AL_StartLocalSound
Play a local (non-spatialized) sound effect
=================
*/
static
void S_AL_StartLocalSound(sfxHandle_t sfx, int channel)
{
srcHandle_t src;
if(S_AL_CheckInput(0, sfx))
return;
// Try to grab a source
src = S_AL_SrcAlloc(SRCPRI_LOCAL, -1, channel);
if(src == -1)
return;
// Set up the effect
S_AL_SrcSetup(src, sfx, SRCPRI_LOCAL, -1, channel, qtrue);
// Start it playing
srcList[src].isPlaying = qtrue;
qalSourcePlay(srcList[src].alSource);
}
/*
=================
S_AL_StartSound
Play a one-shot sound effect
=================
*/
static void S_AL_StartSound( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx )
{
vec3_t sorigin;
srcHandle_t src;
src_t *curSource;
if(origin)
{
if(S_AL_CheckInput(0, sfx))
return;
VectorCopy(origin, sorigin);
}
else
{
if(S_AL_CheckInput(entnum, sfx))
return;
if(S_AL_HearingThroughEntity(entnum))
{
S_AL_StartLocalSound(sfx, entchannel);
return;
}
VectorCopy(entityList[entnum].origin, sorigin);
}
S_AL_SanitiseVector(sorigin);
if((srcActiveCnt > 5 * srcCount / 3) &&
(DistanceSquared(sorigin, lastListenerOrigin) >=
(s_alMaxDistance->value + s_alGraceDistance->value) * (s_alMaxDistance->value + s_alGraceDistance->value)))
{
// We're getting tight on sources and source is not within hearing distance so don't add it
return;
}
// Try to grab a source
src = S_AL_SrcAlloc(SRCPRI_ONESHOT, entnum, entchannel);
if(src == -1)
return;
S_AL_SrcSetup(src, sfx, SRCPRI_ONESHOT, entnum, entchannel, qfalse);
curSource = &srcList[src];
if(!origin)
curSource->isTracking = qtrue;
qalSourcefv(curSource->alSource, AL_POSITION, sorigin );
S_AL_ScaleGain(curSource, sorigin);
// Start it playing
curSource->isPlaying = qtrue;
qalSourcePlay(curSource->alSource);
}
/*
=================
S_AL_ClearLoopingSounds
=================
*/
static
void S_AL_ClearLoopingSounds( qboolean killall )
{
int i;
for(i = 0; i < srcCount; i++)
{
if((srcList[i].isLooping) && (srcList[i].entity != -1))
entityList[srcList[i].entity].loopAddedThisFrame = qfalse;
}
}
/*
=================
S_AL_SrcLoop
=================
*/
static void S_AL_SrcLoop( alSrcPriority_t priority, sfxHandle_t sfx,
const vec3_t origin, const vec3_t velocity, int entityNum )
{
int src;
sentity_t *sent = &entityList[ entityNum ];
src_t *curSource;
vec3_t sorigin, svelocity;
if(S_AL_CheckInput(entityNum, sfx))
return;
// Do we need to allocate a new source for this entity
if( !sent->srcAllocated )
{
// Try to get a channel
src = S_AL_SrcAlloc( priority, entityNum, -1 );
if( src == -1 )
{
Com_DPrintf( S_COLOR_YELLOW "WARNING: Failed to allocate source "
"for loop sfx %d on entity %d\n", sfx, entityNum );
return;
}
curSource = &srcList[src];
sent->startLoopingSound = qtrue;
curSource->lastTimePos = -1.0;
curSource->lastSampleTime = Sys_Milliseconds();
}
else
{
src = sent->srcIndex;
curSource = &srcList[src];
}
sent->srcAllocated = qtrue;
sent->srcIndex = src;
sent->loopPriority = priority;
sent->loopSfx = sfx;
// If this is not set then the looping sound is stopped.
sent->loopAddedThisFrame = qtrue;
// UGH
// These lines should be called via S_AL_SrcSetup, but we
// can't call that yet as it buffers sfxes that may change
// with subsequent calls to S_AL_SrcLoop
curSource->entity = entityNum;
curSource->isLooping = qtrue;
if( S_AL_HearingThroughEntity( entityNum ) )
{
curSource->local = qtrue;
VectorClear(sorigin);
qalSourcefv(curSource->alSource, AL_POSITION, sorigin);
qalSourcefv(curSource->alSource, AL_VELOCITY, vec3_origin);
}
else
{
curSource->local = qfalse;
if(origin)
VectorCopy(origin, sorigin);
else
VectorCopy(sent->origin, sorigin);
S_AL_SanitiseVector(sorigin);
VectorCopy(sorigin, curSource->loopSpeakerPos);
if(velocity)
{
VectorCopy(velocity, svelocity);
S_AL_SanitiseVector(svelocity);
}
else
VectorClear(svelocity);
qalSourcefv(curSource->alSource, AL_POSITION, (ALfloat *) sorigin);
qalSourcefv(curSource->alSource, AL_VELOCITY, (ALfloat *) svelocity);
}
}
/*
=================
S_AL_AddLoopingSound
=================
*/
static void S_AL_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx)
{
S_AL_SrcLoop(SRCPRI_ENTITY, sfx, origin, velocity, entityNum);
}
/*
=================
S_AL_AddRealLoopingSound
=================
*/
static void S_AL_AddRealLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx)
{
S_AL_SrcLoop(SRCPRI_AMBIENT, sfx, origin, velocity, entityNum);
}
/*
=================
S_AL_StopLoopingSound
=================
*/
static
void S_AL_StopLoopingSound(int entityNum )
{
if(entityList[entityNum].srcAllocated)
S_AL_SrcKill(entityList[entityNum].srcIndex);
}
/*
=================
S_AL_SrcUpdate
Update state (move things around, manage sources, and so on)
=================
*/
static
void S_AL_SrcUpdate( void )
{
int i;
int entityNum;
ALint state;
src_t *curSource;
for(i = 0; i < srcCount; i++)
{
entityNum = srcList[i].entity;
curSource = &srcList[i];
if(curSource->isLocked)
continue;
if(!curSource->isActive)
continue;
// Update source parameters
if((s_alGain->modified) || (s_volume->modified))
curSource->curGain = s_alGain->value * s_volume->value;
if((s_alRolloff->modified) && (!curSource->local))
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
if(s_alMinDistance->modified)
qalSourcef(curSource->alSource, AL_REFERENCE_DISTANCE, s_alMinDistance->value);
if(curSource->isLooping)
{
sentity_t *sent = &entityList[ entityNum ];
// If a looping effect hasn't been touched this frame, pause or kill it
if(sent->loopAddedThisFrame)
{
alSfx_t *curSfx;
// The sound has changed without an intervening removal
if(curSource->isActive && !sent->startLoopingSound &&
curSource->sfx != sent->loopSfx)
{
S_AL_NewLoopMaster(curSource, qtrue);
curSource->isPlaying = qfalse;
qalSourceStop(curSource->alSource);
qalSourcei(curSource->alSource, AL_BUFFER, 0);
sent->startLoopingSound = qtrue;
}
// The sound hasn't been started yet
if(sent->startLoopingSound)
{
S_AL_SrcSetup(i, sent->loopSfx, sent->loopPriority,
entityNum, -1, curSource->local);
curSource->isLooping = qtrue;
knownSfx[curSource->sfx].loopCnt++;
sent->startLoopingSound = qfalse;
}
curSfx = &knownSfx[curSource->sfx];
S_AL_ScaleGain(curSource, curSource->loopSpeakerPos);
if(!curSource->scaleGain)
{
if(curSource->isPlaying)
{
// Sound is mute, stop playback until we are in range again
S_AL_NewLoopMaster(curSource, qfalse);
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
else if(!curSfx->loopActiveCnt && curSfx->masterLoopSrc < 0)
curSfx->masterLoopSrc = i;
continue;
}
if(!curSource->isPlaying)
{
qalSourcei(curSource->alSource, AL_LOOPING, AL_TRUE);
curSource->isPlaying = qtrue;
qalSourcePlay(curSource->alSource);
if(curSource->priority == SRCPRI_AMBIENT)
{
// If there are other ambient looping sources with the same sound,
// make sure the sound of these sources are in sync.
if(curSfx->loopActiveCnt)
{
int offset, error;
// we already have a master loop playing, get buffer position.
S_AL_ClearError(qfalse);
qalGetSourcei(srcList[curSfx->masterLoopSrc].alSource, AL_SAMPLE_OFFSET, &offset);
if((error = qalGetError()) != AL_NO_ERROR)
{
if(error != AL_INVALID_ENUM)
{
Com_Printf(S_COLOR_YELLOW "WARNING: Cannot get sample offset from source %d: "
"%s\n", i, S_AL_ErrorMsg(error));
}
}
else
qalSourcei(curSource->alSource, AL_SAMPLE_OFFSET, offset);
}
else if(curSfx->loopCnt && curSfx->masterLoopSrc >= 0)
{
float secofs;
src_t *master = &srcList[curSfx->masterLoopSrc];
// This loop sound used to be played, but all sources are stopped. Use last sample position/time
// to calculate offset so the player thinks the sources continued playing while they were inaudible.
if(master->lastTimePos >= 0)
{
secofs = master->lastTimePos + (Sys_Milliseconds() - master->lastSampleTime) / 1000.0f;
secofs = fmodf(secofs, (float) curSfx->info.samples / curSfx->info.rate);
qalSourcef(curSource->alSource, AL_SEC_OFFSET, secofs);
}
// I be the master now
curSfx->masterLoopSrc = i;
}
else
curSfx->masterLoopSrc = i;
}
else if(curSource->lastTimePos >= 0)
{
float secofs;
// For unsynced loops (SRCPRI_ENTITY) just carry on playing as if the sound was never stopped
secofs = curSource->lastTimePos + (Sys_Milliseconds() - curSource->lastSampleTime) / 1000.0f;
secofs = fmodf(secofs, (float) curSfx->info.samples / curSfx->info.rate);
qalSourcef(curSource->alSource, AL_SEC_OFFSET, secofs);
}
curSfx->loopActiveCnt++;
}
// Update locality
if(curSource->local)
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_TRUE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, 0.0f);
}
else
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_FALSE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
}
}
else if(curSource->priority == SRCPRI_AMBIENT)
{
if(curSource->isPlaying)
{
S_AL_NewLoopMaster(curSource, qfalse);
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
}
else
S_AL_SrcKill(i);
continue;
}
if(!curSource->isStream)
{
// Check if it's done, and flag it
qalGetSourcei(curSource->alSource, AL_SOURCE_STATE, &state);
if(state == AL_STOPPED)
{
curSource->isPlaying = qfalse;
S_AL_SrcKill(i);
continue;
}
}
// Query relativity of source, don't move if it's true
qalGetSourcei(curSource->alSource, AL_SOURCE_RELATIVE, &state);
// See if it needs to be moved
if(curSource->isTracking && !state)
{
qalSourcefv(curSource->alSource, AL_POSITION, entityList[entityNum].origin);
S_AL_ScaleGain(curSource, entityList[entityNum].origin);
}
}
}
/*
=================
S_AL_SrcShutup
=================
*/
static
void S_AL_SrcShutup( void )
{
int i;
for(i = 0; i < srcCount; i++)
S_AL_SrcKill(i);
}
/*
=================
S_AL_SrcGet
=================
*/
static
ALuint S_AL_SrcGet(srcHandle_t src)
{
return srcList[src].alSource;
}
//===========================================================================
// Q3A cinematics use up to 12 buffers at once
#define MAX_STREAM_BUFFERS 20
static srcHandle_t streamSourceHandles[MAX_RAW_STREAMS];
static qboolean streamPlaying[MAX_RAW_STREAMS];
static ALuint streamSources[MAX_RAW_STREAMS];
static ALuint streamBuffers[MAX_RAW_STREAMS][MAX_STREAM_BUFFERS];
static int streamNumBuffers[MAX_RAW_STREAMS];
static int streamBufIndex[MAX_RAW_STREAMS];
/*
=================
S_AL_AllocateStreamChannel
=================
*/
static void S_AL_AllocateStreamChannel(int stream, int entityNum)
{
srcHandle_t cursrc;
ALuint alsrc;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(entityNum >= 0)
{
// This is a stream that tracks an entity
// Allocate a streamSource at normal priority
cursrc = S_AL_SrcAlloc(SRCPRI_ENTITY, entityNum, 0);
if(cursrc < 0)
return;
S_AL_SrcSetup(cursrc, -1, SRCPRI_ENTITY, entityNum, 0, qfalse);
alsrc = S_AL_SrcGet(cursrc);
srcList[cursrc].isTracking = qtrue;
srcList[cursrc].isStream = qtrue;
}
else
{
// Unspatialized stream source
// Allocate a streamSource at high priority
cursrc = S_AL_SrcAlloc(SRCPRI_STREAM, -2, 0);
if(cursrc < 0)
return;
alsrc = S_AL_SrcGet(cursrc);
// Lock the streamSource so nobody else can use it, and get the raw streamSource
S_AL_SrcLock(cursrc);
// make sure that after unmuting the S_AL_Gain in S_Update() does not turn
// volume up prematurely for this source
srcList[cursrc].scaleGain = 0.0f;
// Set some streamSource parameters
qalSourcei (alsrc, AL_BUFFER, 0 );
qalSourcei (alsrc, AL_LOOPING, AL_FALSE );
qalSource3f(alsrc, AL_POSITION, 0.0, 0.0, 0.0);
qalSource3f(alsrc, AL_VELOCITY, 0.0, 0.0, 0.0);
qalSource3f(alsrc, AL_DIRECTION, 0.0, 0.0, 0.0);
qalSourcef (alsrc, AL_ROLLOFF_FACTOR, 0.0 );
qalSourcei (alsrc, AL_SOURCE_RELATIVE, AL_TRUE );
}
streamSourceHandles[stream] = cursrc;
streamSources[stream] = alsrc;
streamNumBuffers[stream] = 0;
streamBufIndex[stream] = 0;
}
/*
=================
S_AL_FreeStreamChannel
=================
*/
static void S_AL_FreeStreamChannel( int stream )
{
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
// Detach any buffers
qalSourcei(streamSources[stream], AL_BUFFER, 0);
// Delete the buffers
if (streamNumBuffers[stream] > 0) {
qalDeleteBuffers(streamNumBuffers[stream], streamBuffers[stream]);
streamNumBuffers[stream] = 0;
}
// Release the output streamSource
S_AL_SrcUnlock(streamSourceHandles[stream]);
S_AL_SrcKill(streamSourceHandles[stream]);
streamSources[stream] = 0;
streamSourceHandles[stream] = -1;
}
/*
=================
S_AL_RawSamples
=================
*/
static
void S_AL_RawSamples(int stream, int samples, int rate, int width, int channels, const byte *data, float volume, int entityNum)
{
int numBuffers;
ALuint buffer;
ALuint format;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
format = S_AL_Format( width, channels );
// Create the streamSource if necessary
if(streamSourceHandles[stream] == -1)
{
S_AL_AllocateStreamChannel(stream, entityNum);
// Failed?
if(streamSourceHandles[stream] == -1)
{
Com_Printf( S_COLOR_RED "ERROR: Can't allocate streaming streamSource\n");
return;
}
}
qalGetSourcei(streamSources[stream], AL_BUFFERS_QUEUED, &numBuffers);
if (numBuffers == MAX_STREAM_BUFFERS)
{
Com_DPrintf(S_COLOR_RED"WARNING: Steam dropping raw samples, reached MAX_STREAM_BUFFERS\n");
return;
}
// Allocate a new AL buffer if needed
if (numBuffers == streamNumBuffers[stream])
{
ALuint oldBuffers[MAX_STREAM_BUFFERS];
int i;
if (!S_AL_GenBuffers(1, &buffer, "stream"))
return;
Com_Memcpy(oldBuffers, &streamBuffers[stream], sizeof (oldBuffers));
// Reorder buffer array in order of oldest to newest
for ( i = 0; i < streamNumBuffers[stream]; ++i )
streamBuffers[stream][i] = oldBuffers[(streamBufIndex[stream] + i) % streamNumBuffers[stream]];
// Add the new buffer to end
streamBuffers[stream][streamNumBuffers[stream]] = buffer;
streamBufIndex[stream] = streamNumBuffers[stream];
streamNumBuffers[stream]++;
}
// Select next buffer in loop
buffer = streamBuffers[stream][ streamBufIndex[stream] ];
streamBufIndex[stream] = (streamBufIndex[stream] + 1) % streamNumBuffers[stream];
// Fill buffer
qalBufferData(buffer, format, (ALvoid *)data, (samples * width * channels), rate);
// Shove the data onto the streamSource
qalSourceQueueBuffers(streamSources[stream], 1, &buffer);
if(entityNum < 0)
{
// Volume
S_AL_Gain (streamSources[stream], volume * s_volume->value * s_alGain->value);
}
// Start stream
if(!streamPlaying[stream])
{
qalSourcePlay( streamSources[stream] );
streamPlaying[stream] = qtrue;
}
}
/*
=================
S_AL_StreamUpdate
=================
*/
static
void S_AL_StreamUpdate( int stream )
{
int numBuffers;
ALint state;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(streamSourceHandles[stream] == -1)
return;
// Un-queue any buffers
qalGetSourcei( streamSources[stream], AL_BUFFERS_PROCESSED, &numBuffers );
while( numBuffers-- )
{
ALuint buffer;
qalSourceUnqueueBuffers(streamSources[stream], 1, &buffer);
}
// Start the streamSource playing if necessary
qalGetSourcei( streamSources[stream], AL_BUFFERS_QUEUED, &numBuffers );
qalGetSourcei(streamSources[stream], AL_SOURCE_STATE, &state);
if(state == AL_STOPPED)
{
streamPlaying[stream] = qfalse;
// If there are no buffers queued up, release the streamSource
if( !numBuffers )
S_AL_FreeStreamChannel( stream );
}
if( !streamPlaying[stream] && numBuffers )
{
qalSourcePlay( streamSources[stream] );
streamPlaying[stream] = qtrue;
}
}
/*
=================
S_AL_StreamDie
=================
*/
static
void S_AL_StreamDie( int stream )
{
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(streamSourceHandles[stream] == -1)
return;
streamPlaying[stream] = qfalse;
qalSourceStop(streamSources[stream]);
S_AL_FreeStreamChannel(stream);
}
//===========================================================================
#define NUM_MUSIC_BUFFERS 4
#define MUSIC_BUFFER_SIZE 4096
static qboolean musicPlaying = qfalse;
static srcHandle_t musicSourceHandle = -1;
static ALuint musicSource;
static ALuint musicBuffers[NUM_MUSIC_BUFFERS];
static snd_stream_t *mus_stream;
static snd_stream_t *intro_stream;
static char s_backgroundLoop[MAX_QPATH];
static byte decode_buffer[MUSIC_BUFFER_SIZE];
/*
=================
S_AL_MusicSourceGet
=================
*/
static void S_AL_MusicSourceGet( void )
{
// Allocate a musicSource at high priority
musicSourceHandle = S_AL_SrcAlloc(SRCPRI_STREAM, -2, 0);
if(musicSourceHandle == -1)
return;
// Lock the musicSource so nobody else can use it, and get the raw musicSource
S_AL_SrcLock(musicSourceHandle);
musicSource = S_AL_SrcGet(musicSourceHandle);
// make sure that after unmuting the S_AL_Gain in S_Update() does not turn
// volume up prematurely for this source
srcList[musicSourceHandle].scaleGain = 0.0f;
// Set some musicSource parameters
qalSource3f(musicSource, AL_POSITION, 0.0, 0.0, 0.0);
qalSource3f(musicSource, AL_VELOCITY, 0.0, 0.0, 0.0);
qalSource3f(musicSource, AL_DIRECTION, 0.0, 0.0, 0.0);
qalSourcef (musicSource, AL_ROLLOFF_FACTOR, 0.0 );
qalSourcei (musicSource, AL_SOURCE_RELATIVE, AL_TRUE );
}
/*
=================
S_AL_MusicSourceFree
=================
*/
static void S_AL_MusicSourceFree( void )
{
// Release the output musicSource
S_AL_SrcUnlock(musicSourceHandle);
S_AL_SrcKill(musicSourceHandle);
musicSource = 0;
musicSourceHandle = -1;
}
/*
=================
S_AL_CloseMusicFiles
=================
*/
static void S_AL_CloseMusicFiles(void)
{
if(intro_stream)
{
S_CodecCloseStream(intro_stream);
intro_stream = NULL;
}
if(mus_stream)
{
S_CodecCloseStream(mus_stream);
mus_stream = NULL;
}
}
/*
=================
S_AL_StopBackgroundTrack
=================
*/
static
void S_AL_StopBackgroundTrack( void )
{
if(!musicPlaying)
return;
// Stop playing
qalSourceStop(musicSource);
// Detach any buffers
qalSourcei(musicSource, AL_BUFFER, 0);
// Delete the buffers
qalDeleteBuffers(NUM_MUSIC_BUFFERS, musicBuffers);
// Free the musicSource
S_AL_MusicSourceFree();
// Unload the stream
S_AL_CloseMusicFiles();
musicPlaying = qfalse;
}
/*
=================
S_AL_MusicProcess
=================
*/
static
void S_AL_MusicProcess(ALuint b)
{
ALenum error;
int l;
ALuint format;
snd_stream_t *curstream;
S_AL_ClearError( qfalse );
if(intro_stream)
curstream = intro_stream;
else
curstream = mus_stream;
if(!curstream)
return;
l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
// Run out data to read, start at the beginning again
if(l == 0)
{
S_CodecCloseStream(curstream);
// the intro stream just finished playing so we don't need to reopen
// the music stream.
if(intro_stream)
intro_stream = NULL;
else
mus_stream = S_CodecOpenStream(s_backgroundLoop);
curstream = mus_stream;
if(!curstream)
{
S_AL_StopBackgroundTrack();
return;
}
l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
}
format = S_AL_Format(curstream->info.width, curstream->info.channels);
if( l == 0 )
{
// We have no data to buffer, so buffer silence
byte dummyData[ 2 ] = { 0 };
qalBufferData( b, AL_FORMAT_MONO16, (void *)dummyData, 2, 22050 );
}
else
qalBufferData(b, format, decode_buffer, l, curstream->info.rate);
if( ( error = qalGetError( ) ) != AL_NO_ERROR )
{
S_AL_StopBackgroundTrack( );
Com_Printf( S_COLOR_RED "ERROR: while buffering data for music stream - %s\n",
S_AL_ErrorMsg( error ) );
return;
}
}
/*
=================
S_AL_StartBackgroundTrack
=================
*/
static
void S_AL_StartBackgroundTrack( const char *intro, const char *loop )
{
int i;
qboolean issame;
// Stop any existing music that might be playing
S_AL_StopBackgroundTrack();
if((!intro || !*intro) && (!loop || !*loop))
return;
// Allocate a musicSource
S_AL_MusicSourceGet();
if(musicSourceHandle == -1)
return;
if (!loop || !*loop)
{
loop = intro;
issame = qtrue;
}
else if(intro && *intro && !strcmp(intro, loop))
issame = qtrue;
else
issame = qfalse;
// Copy the loop over
Q_strncpyz( s_backgroundLoop, loop, sizeof( s_backgroundLoop ) );
if(!issame)
{
// Open the intro and don't mind whether it succeeds.
// The important part is the loop.
intro_stream = S_CodecOpenStream(intro);
}
else
intro_stream = NULL;
mus_stream = S_CodecOpenStream(s_backgroundLoop);
if(!mus_stream)
{
S_AL_CloseMusicFiles();
S_AL_MusicSourceFree();
return;
}
// Generate the musicBuffers
if (!S_AL_GenBuffers(NUM_MUSIC_BUFFERS, musicBuffers, "music"))
return;
// Queue the musicBuffers up
for(i = 0; i < NUM_MUSIC_BUFFERS; i++)
{
S_AL_MusicProcess(musicBuffers[i]);
}
qalSourceQueueBuffers(musicSource, NUM_MUSIC_BUFFERS, musicBuffers);
// Set the initial gain property
S_AL_Gain(musicSource, s_alGain->value * s_musicVolume->value);
// Start playing
qalSourcePlay(musicSource);
musicPlaying = qtrue;
}
/*
=================
S_AL_MusicUpdate
=================
*/
static
void S_AL_MusicUpdate( void )
{
int numBuffers;
ALint state;
if(!musicPlaying)
return;
qalGetSourcei( musicSource, AL_BUFFERS_PROCESSED, &numBuffers );
while( numBuffers-- )
{
ALuint b;
qalSourceUnqueueBuffers(musicSource, 1, &b);
S_AL_MusicProcess(b);
qalSourceQueueBuffers(musicSource, 1, &b);
}
// Hitches can cause OpenAL to be starved of buffers when streaming.
// If this happens, it will stop playback. This restarts the source if
// it is no longer playing, and if there are buffers available
qalGetSourcei( musicSource, AL_SOURCE_STATE, &state );
qalGetSourcei( musicSource, AL_BUFFERS_QUEUED, &numBuffers );
if( state == AL_STOPPED && numBuffers )
{
Com_DPrintf( S_COLOR_YELLOW "Restarted OpenAL music\n" );
qalSourcePlay(musicSource);
}
// Set the gain property
S_AL_Gain(musicSource, s_alGain->value * s_musicVolume->value);
}
//===========================================================================
// Local state variables
static ALCdevice *alDevice;
static ALCcontext *alContext;
#ifdef USE_VOIP
static ALCdevice *alCaptureDevice;
static cvar_t *s_alCapture;
#endif
#ifdef _WIN32
#define ALDRIVER_DEFAULT "OpenAL32.dll"
#elif defined(__APPLE__)
#define ALDRIVER_DEFAULT "/System/Library/Frameworks/OpenAL.framework/OpenAL"
#elif defined(__OpenBSD__)
#define ALDRIVER_DEFAULT "libopenal.so"
#else
#define ALDRIVER_DEFAULT "libopenal.so.1"
#endif
/*
=================
S_AL_StopAllSounds
=================
*/
static
void S_AL_StopAllSounds( void )
{
int i;
S_AL_SrcShutup();
S_AL_StopBackgroundTrack();
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamDie(i);
}
/*
=================
S_AL_Respatialize
=================
*/
static
void S_AL_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], int inwater )
{
float orientation[6];
vec3_t sorigin;
VectorCopy( origin, sorigin );
S_AL_SanitiseVector( sorigin );
S_AL_SanitiseVector( axis[ 0 ] );
S_AL_SanitiseVector( axis[ 1 ] );
S_AL_SanitiseVector( axis[ 2 ] );
orientation[0] = axis[0][0]; orientation[1] = axis[0][1]; orientation[2] = axis[0][2];
orientation[3] = axis[2][0]; orientation[4] = axis[2][1]; orientation[5] = axis[2][2];
lastListenerNumber = entityNum;
VectorCopy( sorigin, lastListenerOrigin );
// Set OpenAL listener paramaters
qalListenerfv(AL_POSITION, (ALfloat *)sorigin);
qalListenerfv(AL_VELOCITY, vec3_origin);
qalListenerfv(AL_ORIENTATION, orientation);
}
/*
=================
S_AL_Update
=================
*/
static
void S_AL_Update( void )
{
int i;
if(s_muted->modified)
{
// muted state changed. Let S_AL_Gain turn up all sources again.
for(i = 0; i < srcCount; i++)
{
if(srcList[i].isActive)
S_AL_Gain(srcList[i].alSource, srcList[i].scaleGain);
}
s_muted->modified = qfalse;
}
// Update SFX channels
S_AL_SrcUpdate();
// Update streams
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamUpdate(i);
S_AL_MusicUpdate();
// Doppler
if(s_doppler->modified)
{
s_alDopplerFactor->modified = qtrue;
s_doppler->modified = qfalse;
}
// Doppler parameters
if(s_alDopplerFactor->modified)
{
if(s_doppler->integer)
qalDopplerFactor(s_alDopplerFactor->value);
else
qalDopplerFactor(0.0f);
s_alDopplerFactor->modified = qfalse;
}
if(s_alDopplerSpeed->modified)
{
qalSpeedOfSound(s_alDopplerSpeed->value);
s_alDopplerSpeed->modified = qfalse;
}
// Clear the modified flags on the other cvars
s_alGain->modified = qfalse;
s_volume->modified = qfalse;
s_musicVolume->modified = qfalse;
s_alMinDistance->modified = qfalse;
s_alRolloff->modified = qfalse;
}
/*
=================
S_AL_DisableSounds
=================
*/
static
void S_AL_DisableSounds( void )
{
S_AL_StopAllSounds();
}
/*
=================
S_AL_BeginRegistration
=================
*/
static
void S_AL_BeginRegistration( void )
{
if(!numSfx)
S_AL_BufferInit();
}
/*
=================
S_AL_ClearSoundBuffer
=================
*/
static
void S_AL_ClearSoundBuffer( void )
{
}
/*
=================
S_AL_SoundList
=================
*/
static
void S_AL_SoundList( void )
{
}
#ifdef USE_VOIP
static
void S_AL_StartCapture( void )
{
if (alCaptureDevice != NULL)
qalcCaptureStart(alCaptureDevice);
}
static
int S_AL_AvailableCaptureSamples( void )
{
int retval = 0;
if (alCaptureDevice != NULL)
{
ALint samples = 0;
qalcGetIntegerv(alCaptureDevice, ALC_CAPTURE_SAMPLES, sizeof (samples), &samples);
retval = (int) samples;
}
return retval;
}
static
void S_AL_Capture( int samples, byte *data )
{
if (alCaptureDevice != NULL)
qalcCaptureSamples(alCaptureDevice, data, samples);
}
void S_AL_StopCapture( void )
{
if (alCaptureDevice != NULL)
qalcCaptureStop(alCaptureDevice);
}
void S_AL_MasterGain( float gain )
{
qalListenerf(AL_GAIN, gain);
}
#endif
/*
=================
S_AL_SoundInfo
=================
*/
static void S_AL_SoundInfo(void)
{
Com_Printf( "OpenAL info:\n" );
Com_Printf( " Vendor: %s\n", qalGetString( AL_VENDOR ) );
Com_Printf( " Version: %s\n", qalGetString( AL_VERSION ) );
Com_Printf( " Renderer: %s\n", qalGetString( AL_RENDERER ) );
Com_Printf( " AL Extensions: %s\n", qalGetString( AL_EXTENSIONS ) );
Com_Printf( " ALC Extensions: %s\n", qalcGetString( alDevice, ALC_EXTENSIONS ) );
if(enumeration_all_ext)
Com_Printf(" Device: %s\n", qalcGetString(alDevice, ALC_ALL_DEVICES_SPECIFIER));
else if(enumeration_ext)
Com_Printf(" Device: %s\n", qalcGetString(alDevice, ALC_DEVICE_SPECIFIER));
if(enumeration_all_ext || enumeration_ext)
Com_Printf(" Available Devices:\n%s", s_alAvailableDevices->string);
#ifdef USE_VOIP
if(capture_ext)
{
Com_Printf(" Input Device: %s\n", qalcGetString(alCaptureDevice, ALC_CAPTURE_DEVICE_SPECIFIER));
Com_Printf(" Available Input Devices:\n%s", s_alAvailableInputDevices->string);
}
#endif
}
/*
=================
S_AL_Shutdown
=================
*/
static
void S_AL_Shutdown( void )
{
// Shut down everything
int i;
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamDie(i);
S_AL_StopBackgroundTrack( );
S_AL_SrcShutdown( );
S_AL_BufferShutdown( );
qalcDestroyContext(alContext);
qalcCloseDevice(alDevice);
#ifdef USE_VOIP
if (alCaptureDevice != NULL) {
qalcCaptureStop(alCaptureDevice);
qalcCaptureCloseDevice(alCaptureDevice);
alCaptureDevice = NULL;
Com_Printf( "OpenAL capture device closed.\n" );
}
#endif
for (i = 0; i < MAX_RAW_STREAMS; i++) {
streamSourceHandles[i] = -1;
streamPlaying[i] = qfalse;
streamSources[i] = 0;
}
QAL_Shutdown();
}
#endif
/*
=================
S_AL_Init
=================
*/
qboolean S_AL_Init( soundInterface_t *si )
{
#ifdef USE_OPENAL
const char* device = NULL;
const char* inputdevice = NULL;
int i;
if( !si ) {
return qfalse;
}
for (i = 0; i < MAX_RAW_STREAMS; i++) {
streamSourceHandles[i] = -1;
streamPlaying[i] = qfalse;
streamSources[i] = 0;
streamNumBuffers[i] = 0;
streamBufIndex[i] = 0;
}
// New console variables
s_alPrecache = Cvar_Get( "s_alPrecache", "1", CVAR_ARCHIVE );
s_alGain = Cvar_Get( "s_alGain", "1.0", CVAR_ARCHIVE );
s_alSources = Cvar_Get( "s_alSources", "96", CVAR_ARCHIVE );
s_alDopplerFactor = Cvar_Get( "s_alDopplerFactor", "1.0", CVAR_ARCHIVE );
s_alDopplerSpeed = Cvar_Get( "s_alDopplerSpeed", "9000", CVAR_ARCHIVE );
s_alMinDistance = Cvar_Get( "s_alMinDistance", "120", CVAR_CHEAT );
s_alMaxDistance = Cvar_Get("s_alMaxDistance", "1024", CVAR_CHEAT);
s_alRolloff = Cvar_Get( "s_alRolloff", "2", CVAR_CHEAT);
s_alGraceDistance = Cvar_Get("s_alGraceDistance", "512", CVAR_CHEAT);
s_alDriver = Cvar_Get( "s_alDriver", ALDRIVER_DEFAULT, CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED );
s_alInputDevice = Cvar_Get( "s_alInputDevice", "", CVAR_ARCHIVE | CVAR_LATCH );
s_alDevice = Cvar_Get("s_alDevice", "", CVAR_ARCHIVE | CVAR_LATCH);
if ( COM_CompareExtension( s_alDriver->string, ".pk3" ) )
{
Com_Printf( "Rejecting DLL named \"%s\"", s_alDriver->string );
return qfalse;
}
// Load QAL
if( !QAL_Init( s_alDriver->string ) )
{
Com_Printf( "Failed to load library: \"%s\".\n", s_alDriver->string );
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) || !QAL_Init( ALDRIVER_DEFAULT ) ) {
return qfalse;
}
}
device = s_alDevice->string;
if(device && !*device)
device = NULL;
inputdevice = s_alInputDevice->string;
if(inputdevice && !*inputdevice)
inputdevice = NULL;
// Device enumeration support
enumeration_all_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT");
enumeration_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT");
if(enumeration_ext || enumeration_all_ext)
{
char devicenames[16384] = "";
const char *devicelist;
#ifdef _WIN32
const char *defaultdevice;
#endif
int curlen;
// get all available devices + the default device name.
if(enumeration_all_ext)
{
devicelist = qalcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_ALL_DEVICES_SPECIFIER);
#endif
}
else
{
// We don't have ALC_ENUMERATE_ALL_EXT but normal enumeration.
devicelist = qalcGetString(NULL, ALC_DEVICE_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
#endif
enumeration_ext = qtrue;
}
#ifdef _WIN32
// check whether the default device is generic hardware. If it is, change to
// Generic Software as that one works more reliably with various sound systems.
// If it's not, use OpenAL's default selection as we don't want to ignore
// native hardware acceleration.
if(!device && defaultdevice && !strcmp(defaultdevice, "Generic Hardware"))
device = "Generic Software";
#endif
// dump a list of available devices to a cvar for the user to see.
if(devicelist)
{
while((curlen = strlen(devicelist)))
{
Q_strcat(devicenames, sizeof(devicenames), devicelist);
Q_strcat(devicenames, sizeof(devicenames), "\n");
devicelist += curlen + 1;
}
}
s_alAvailableDevices = Cvar_Get("s_alAvailableDevices", devicenames, CVAR_ROM | CVAR_NORESTART);
}
alDevice = qalcOpenDevice(device);
if( !alDevice && device )
{
Com_Printf( "Failed to open OpenAL device '%s', trying default.\n", device );
alDevice = qalcOpenDevice(NULL);
}
if( !alDevice )
{
QAL_Shutdown( );
Com_Printf( "Failed to open OpenAL device.\n" );
return qfalse;
}
// Create OpenAL context
alContext = qalcCreateContext( alDevice, NULL );
if( !alContext )
{
QAL_Shutdown( );
qalcCloseDevice( alDevice );
Com_Printf( "Failed to create OpenAL context.\n" );
return qfalse;
}
qalcMakeContextCurrent( alContext );
// Initialize sources, buffers, music
S_AL_BufferInit( );
S_AL_SrcInit( );
// Set up OpenAL parameters (doppler, etc)
qalDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
qalDopplerFactor( s_alDopplerFactor->value );
qalSpeedOfSound( s_alDopplerSpeed->value );
#ifdef USE_VOIP
// !!! FIXME: some of these alcCaptureOpenDevice() values should be cvars.
// !!! FIXME: add support for capture device enumeration.
// !!! FIXME: add some better error reporting.
s_alCapture = Cvar_Get( "s_alCapture", "1", CVAR_ARCHIVE | CVAR_LATCH );
if (!s_alCapture->integer)
{
Com_Printf("OpenAL capture support disabled by user ('+set s_alCapture 1' to enable)\n");
}
#if USE_MUMBLE
else if (cl_useMumble->integer)
{
Com_Printf("OpenAL capture support disabled for Mumble support\n");
}
#endif
else
{
#ifdef __APPLE__
// !!! FIXME: Apple has a 1.1-compliant OpenAL, which includes
// !!! FIXME: capture support, but they don't list it in the
// !!! FIXME: extension string. We need to check the version string,
// !!! FIXME: then the extension string, but that's too much trouble,
// !!! FIXME: so we'll just check the function pointer for now.
if (qalcCaptureOpenDevice == NULL)
#else
if (!qalcIsExtensionPresent(NULL, "ALC_EXT_capture"))
#endif
{
Com_Printf("No ALC_EXT_capture support, can't record audio.\n");
}
else
{
char inputdevicenames[16384] = "";
const char *inputdevicelist;
const char *defaultinputdevice;
int curlen;
capture_ext = qtrue;
// get all available input devices + the default input device name.
inputdevicelist = qalcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER);
defaultinputdevice = qalcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
// dump a list of available devices to a cvar for the user to see.
if (inputdevicelist)
{
while((curlen = strlen(inputdevicelist)))
{
Q_strcat(inputdevicenames, sizeof(inputdevicenames), inputdevicelist);
Q_strcat(inputdevicenames, sizeof(inputdevicenames), "\n");
inputdevicelist += curlen + 1;
}
}
s_alAvailableInputDevices = Cvar_Get("s_alAvailableInputDevices", inputdevicenames, CVAR_ROM | CVAR_NORESTART);
Com_Printf("OpenAL default capture device is '%s'\n", defaultinputdevice ? defaultinputdevice : "none");
alCaptureDevice = qalcCaptureOpenDevice(inputdevice, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
if( !alCaptureDevice && inputdevice )
{
Com_Printf( "Failed to open OpenAL Input device '%s', trying default.\n", inputdevice );
alCaptureDevice = qalcCaptureOpenDevice(NULL, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
}
Com_Printf( "OpenAL capture device %s.\n",
(alCaptureDevice == NULL) ? "failed to open" : "opened");
}
}
#endif
si->Shutdown = S_AL_Shutdown;
si->StartSound = S_AL_StartSound;
si->StartLocalSound = S_AL_StartLocalSound;
si->StartBackgroundTrack = S_AL_StartBackgroundTrack;
si->StopBackgroundTrack = S_AL_StopBackgroundTrack;
si->RawSamples = S_AL_RawSamples;
si->StopAllSounds = S_AL_StopAllSounds;
si->ClearLoopingSounds = S_AL_ClearLoopingSounds;
si->AddLoopingSound = S_AL_AddLoopingSound;
si->AddRealLoopingSound = S_AL_AddRealLoopingSound;
si->StopLoopingSound = S_AL_StopLoopingSound;
si->Respatialize = S_AL_Respatialize;
si->UpdateEntityPosition = S_AL_UpdateEntityPosition;
si->Update = S_AL_Update;
si->DisableSounds = S_AL_DisableSounds;
si->BeginRegistration = S_AL_BeginRegistration;
si->RegisterSound = S_AL_RegisterSound;
si->ClearSoundBuffer = S_AL_ClearSoundBuffer;
si->SoundInfo = S_AL_SoundInfo;
si->SoundList = S_AL_SoundList;
#ifdef USE_VOIP
si->StartCapture = S_AL_StartCapture;
si->AvailableCaptureSamples = S_AL_AvailableCaptureSamples;
si->Capture = S_AL_Capture;
si->StopCapture = S_AL_StopCapture;
si->MasterGain = S_AL_MasterGain;
#endif
return qtrue;
#else
return qfalse;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3230_0 |
crossvul-cpp_data_good_221_0 | /*
* (C) 1997 Linus Torvalds
* (C) 1999 Andrea Arcangeli <andrea@suse.de> (dynamic inode allocation)
*/
#include <linux/export.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/backing-dev.h>
#include <linux/hash.h>
#include <linux/swap.h>
#include <linux/security.h>
#include <linux/cdev.h>
#include <linux/bootmem.h>
#include <linux/fsnotify.h>
#include <linux/mount.h>
#include <linux/posix_acl.h>
#include <linux/prefetch.h>
#include <linux/buffer_head.h> /* for inode_has_buffers */
#include <linux/ratelimit.h>
#include <linux/list_lru.h>
#include <linux/iversion.h>
#include <trace/events/writeback.h>
#include "internal.h"
/*
* Inode locking rules:
*
* inode->i_lock protects:
* inode->i_state, inode->i_hash, __iget()
* Inode LRU list locks protect:
* inode->i_sb->s_inode_lru, inode->i_lru
* inode->i_sb->s_inode_list_lock protects:
* inode->i_sb->s_inodes, inode->i_sb_list
* bdi->wb.list_lock protects:
* bdi->wb.b_{dirty,io,more_io,dirty_time}, inode->i_io_list
* inode_hash_lock protects:
* inode_hashtable, inode->i_hash
*
* Lock ordering:
*
* inode->i_sb->s_inode_list_lock
* inode->i_lock
* Inode LRU list locks
*
* bdi->wb.list_lock
* inode->i_lock
*
* inode_hash_lock
* inode->i_sb->s_inode_list_lock
* inode->i_lock
*
* iunique_lock
* inode_hash_lock
*/
static unsigned int i_hash_mask __read_mostly;
static unsigned int i_hash_shift __read_mostly;
static struct hlist_head *inode_hashtable __read_mostly;
static __cacheline_aligned_in_smp DEFINE_SPINLOCK(inode_hash_lock);
/*
* Empty aops. Can be used for the cases where the user does not
* define any of the address_space operations.
*/
const struct address_space_operations empty_aops = {
};
EXPORT_SYMBOL(empty_aops);
/*
* Statistics gathering..
*/
struct inodes_stat_t inodes_stat;
static DEFINE_PER_CPU(unsigned long, nr_inodes);
static DEFINE_PER_CPU(unsigned long, nr_unused);
static struct kmem_cache *inode_cachep __read_mostly;
static long get_nr_inodes(void)
{
int i;
long sum = 0;
for_each_possible_cpu(i)
sum += per_cpu(nr_inodes, i);
return sum < 0 ? 0 : sum;
}
static inline long get_nr_inodes_unused(void)
{
int i;
long sum = 0;
for_each_possible_cpu(i)
sum += per_cpu(nr_unused, i);
return sum < 0 ? 0 : sum;
}
long get_nr_dirty_inodes(void)
{
/* not actually dirty inodes, but a wild approximation */
long nr_dirty = get_nr_inodes() - get_nr_inodes_unused();
return nr_dirty > 0 ? nr_dirty : 0;
}
/*
* Handle nr_inode sysctl
*/
#ifdef CONFIG_SYSCTL
int proc_nr_inodes(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
inodes_stat.nr_inodes = get_nr_inodes();
inodes_stat.nr_unused = get_nr_inodes_unused();
return proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
}
#endif
static int no_open(struct inode *inode, struct file *file)
{
return -ENXIO;
}
/**
* inode_init_always - perform inode structure initialisation
* @sb: superblock inode belongs to
* @inode: inode to initialise
*
* These are initializations that need to be done on every inode
* allocation as the fields are not initialised by slab allocation.
*/
int inode_init_always(struct super_block *sb, struct inode *inode)
{
static const struct inode_operations empty_iops;
static const struct file_operations no_open_fops = {.open = no_open};
struct address_space *const mapping = &inode->i_data;
inode->i_sb = sb;
inode->i_blkbits = sb->s_blocksize_bits;
inode->i_flags = 0;
atomic_set(&inode->i_count, 1);
inode->i_op = &empty_iops;
inode->i_fop = &no_open_fops;
inode->__i_nlink = 1;
inode->i_opflags = 0;
if (sb->s_xattr)
inode->i_opflags |= IOP_XATTR;
i_uid_write(inode, 0);
i_gid_write(inode, 0);
atomic_set(&inode->i_writecount, 0);
inode->i_size = 0;
inode->i_write_hint = WRITE_LIFE_NOT_SET;
inode->i_blocks = 0;
inode->i_bytes = 0;
inode->i_generation = 0;
inode->i_pipe = NULL;
inode->i_bdev = NULL;
inode->i_cdev = NULL;
inode->i_link = NULL;
inode->i_dir_seq = 0;
inode->i_rdev = 0;
inode->dirtied_when = 0;
#ifdef CONFIG_CGROUP_WRITEBACK
inode->i_wb_frn_winner = 0;
inode->i_wb_frn_avg_time = 0;
inode->i_wb_frn_history = 0;
#endif
if (security_inode_alloc(inode))
goto out;
spin_lock_init(&inode->i_lock);
lockdep_set_class(&inode->i_lock, &sb->s_type->i_lock_key);
init_rwsem(&inode->i_rwsem);
lockdep_set_class(&inode->i_rwsem, &sb->s_type->i_mutex_key);
atomic_set(&inode->i_dio_count, 0);
mapping->a_ops = &empty_aops;
mapping->host = inode;
mapping->flags = 0;
mapping->wb_err = 0;
atomic_set(&mapping->i_mmap_writable, 0);
mapping_set_gfp_mask(mapping, GFP_HIGHUSER_MOVABLE);
mapping->private_data = NULL;
mapping->writeback_index = 0;
inode->i_private = NULL;
inode->i_mapping = mapping;
INIT_HLIST_HEAD(&inode->i_dentry); /* buggered by rcu freeing */
#ifdef CONFIG_FS_POSIX_ACL
inode->i_acl = inode->i_default_acl = ACL_NOT_CACHED;
#endif
#ifdef CONFIG_FSNOTIFY
inode->i_fsnotify_mask = 0;
#endif
inode->i_flctx = NULL;
this_cpu_inc(nr_inodes);
return 0;
out:
return -ENOMEM;
}
EXPORT_SYMBOL(inode_init_always);
static struct inode *alloc_inode(struct super_block *sb)
{
struct inode *inode;
if (sb->s_op->alloc_inode)
inode = sb->s_op->alloc_inode(sb);
else
inode = kmem_cache_alloc(inode_cachep, GFP_KERNEL);
if (!inode)
return NULL;
if (unlikely(inode_init_always(sb, inode))) {
if (inode->i_sb->s_op->destroy_inode)
inode->i_sb->s_op->destroy_inode(inode);
else
kmem_cache_free(inode_cachep, inode);
return NULL;
}
return inode;
}
void free_inode_nonrcu(struct inode *inode)
{
kmem_cache_free(inode_cachep, inode);
}
EXPORT_SYMBOL(free_inode_nonrcu);
void __destroy_inode(struct inode *inode)
{
BUG_ON(inode_has_buffers(inode));
inode_detach_wb(inode);
security_inode_free(inode);
fsnotify_inode_delete(inode);
locks_free_lock_context(inode);
if (!inode->i_nlink) {
WARN_ON(atomic_long_read(&inode->i_sb->s_remove_count) == 0);
atomic_long_dec(&inode->i_sb->s_remove_count);
}
#ifdef CONFIG_FS_POSIX_ACL
if (inode->i_acl && !is_uncached_acl(inode->i_acl))
posix_acl_release(inode->i_acl);
if (inode->i_default_acl && !is_uncached_acl(inode->i_default_acl))
posix_acl_release(inode->i_default_acl);
#endif
this_cpu_dec(nr_inodes);
}
EXPORT_SYMBOL(__destroy_inode);
static void i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(inode_cachep, inode);
}
static void destroy_inode(struct inode *inode)
{
BUG_ON(!list_empty(&inode->i_lru));
__destroy_inode(inode);
if (inode->i_sb->s_op->destroy_inode)
inode->i_sb->s_op->destroy_inode(inode);
else
call_rcu(&inode->i_rcu, i_callback);
}
/**
* drop_nlink - directly drop an inode's link count
* @inode: inode
*
* This is a low-level filesystem helper to replace any
* direct filesystem manipulation of i_nlink. In cases
* where we are attempting to track writes to the
* filesystem, a decrement to zero means an imminent
* write when the file is truncated and actually unlinked
* on the filesystem.
*/
void drop_nlink(struct inode *inode)
{
WARN_ON(inode->i_nlink == 0);
inode->__i_nlink--;
if (!inode->i_nlink)
atomic_long_inc(&inode->i_sb->s_remove_count);
}
EXPORT_SYMBOL(drop_nlink);
/**
* clear_nlink - directly zero an inode's link count
* @inode: inode
*
* This is a low-level filesystem helper to replace any
* direct filesystem manipulation of i_nlink. See
* drop_nlink() for why we care about i_nlink hitting zero.
*/
void clear_nlink(struct inode *inode)
{
if (inode->i_nlink) {
inode->__i_nlink = 0;
atomic_long_inc(&inode->i_sb->s_remove_count);
}
}
EXPORT_SYMBOL(clear_nlink);
/**
* set_nlink - directly set an inode's link count
* @inode: inode
* @nlink: new nlink (should be non-zero)
*
* This is a low-level filesystem helper to replace any
* direct filesystem manipulation of i_nlink.
*/
void set_nlink(struct inode *inode, unsigned int nlink)
{
if (!nlink) {
clear_nlink(inode);
} else {
/* Yes, some filesystems do change nlink from zero to one */
if (inode->i_nlink == 0)
atomic_long_dec(&inode->i_sb->s_remove_count);
inode->__i_nlink = nlink;
}
}
EXPORT_SYMBOL(set_nlink);
/**
* inc_nlink - directly increment an inode's link count
* @inode: inode
*
* This is a low-level filesystem helper to replace any
* direct filesystem manipulation of i_nlink. Currently,
* it is only here for parity with dec_nlink().
*/
void inc_nlink(struct inode *inode)
{
if (unlikely(inode->i_nlink == 0)) {
WARN_ON(!(inode->i_state & I_LINKABLE));
atomic_long_dec(&inode->i_sb->s_remove_count);
}
inode->__i_nlink++;
}
EXPORT_SYMBOL(inc_nlink);
static void __address_space_init_once(struct address_space *mapping)
{
INIT_RADIX_TREE(&mapping->i_pages, GFP_ATOMIC | __GFP_ACCOUNT);
init_rwsem(&mapping->i_mmap_rwsem);
INIT_LIST_HEAD(&mapping->private_list);
spin_lock_init(&mapping->private_lock);
mapping->i_mmap = RB_ROOT_CACHED;
}
void address_space_init_once(struct address_space *mapping)
{
memset(mapping, 0, sizeof(*mapping));
__address_space_init_once(mapping);
}
EXPORT_SYMBOL(address_space_init_once);
/*
* These are initializations that only need to be done
* once, because the fields are idempotent across use
* of the inode, so let the slab aware of that.
*/
void inode_init_once(struct inode *inode)
{
memset(inode, 0, sizeof(*inode));
INIT_HLIST_NODE(&inode->i_hash);
INIT_LIST_HEAD(&inode->i_devices);
INIT_LIST_HEAD(&inode->i_io_list);
INIT_LIST_HEAD(&inode->i_wb_list);
INIT_LIST_HEAD(&inode->i_lru);
__address_space_init_once(&inode->i_data);
i_size_ordered_init(inode);
}
EXPORT_SYMBOL(inode_init_once);
static void init_once(void *foo)
{
struct inode *inode = (struct inode *) foo;
inode_init_once(inode);
}
/*
* inode->i_lock must be held
*/
void __iget(struct inode *inode)
{
atomic_inc(&inode->i_count);
}
/*
* get additional reference to inode; caller must already hold one.
*/
void ihold(struct inode *inode)
{
WARN_ON(atomic_inc_return(&inode->i_count) < 2);
}
EXPORT_SYMBOL(ihold);
static void inode_lru_list_add(struct inode *inode)
{
if (list_lru_add(&inode->i_sb->s_inode_lru, &inode->i_lru))
this_cpu_inc(nr_unused);
else
inode->i_state |= I_REFERENCED;
}
/*
* Add inode to LRU if needed (inode is unused and clean).
*
* Needs inode->i_lock held.
*/
void inode_add_lru(struct inode *inode)
{
if (!(inode->i_state & (I_DIRTY_ALL | I_SYNC |
I_FREEING | I_WILL_FREE)) &&
!atomic_read(&inode->i_count) && inode->i_sb->s_flags & SB_ACTIVE)
inode_lru_list_add(inode);
}
static void inode_lru_list_del(struct inode *inode)
{
if (list_lru_del(&inode->i_sb->s_inode_lru, &inode->i_lru))
this_cpu_dec(nr_unused);
}
/**
* inode_sb_list_add - add inode to the superblock list of inodes
* @inode: inode to add
*/
void inode_sb_list_add(struct inode *inode)
{
spin_lock(&inode->i_sb->s_inode_list_lock);
list_add(&inode->i_sb_list, &inode->i_sb->s_inodes);
spin_unlock(&inode->i_sb->s_inode_list_lock);
}
EXPORT_SYMBOL_GPL(inode_sb_list_add);
static inline void inode_sb_list_del(struct inode *inode)
{
if (!list_empty(&inode->i_sb_list)) {
spin_lock(&inode->i_sb->s_inode_list_lock);
list_del_init(&inode->i_sb_list);
spin_unlock(&inode->i_sb->s_inode_list_lock);
}
}
static unsigned long hash(struct super_block *sb, unsigned long hashval)
{
unsigned long tmp;
tmp = (hashval * (unsigned long)sb) ^ (GOLDEN_RATIO_PRIME + hashval) /
L1_CACHE_BYTES;
tmp = tmp ^ ((tmp ^ GOLDEN_RATIO_PRIME) >> i_hash_shift);
return tmp & i_hash_mask;
}
/**
* __insert_inode_hash - hash an inode
* @inode: unhashed inode
* @hashval: unsigned long value used to locate this object in the
* inode_hashtable.
*
* Add an inode to the inode hash for this superblock.
*/
void __insert_inode_hash(struct inode *inode, unsigned long hashval)
{
struct hlist_head *b = inode_hashtable + hash(inode->i_sb, hashval);
spin_lock(&inode_hash_lock);
spin_lock(&inode->i_lock);
hlist_add_head(&inode->i_hash, b);
spin_unlock(&inode->i_lock);
spin_unlock(&inode_hash_lock);
}
EXPORT_SYMBOL(__insert_inode_hash);
/**
* __remove_inode_hash - remove an inode from the hash
* @inode: inode to unhash
*
* Remove an inode from the superblock.
*/
void __remove_inode_hash(struct inode *inode)
{
spin_lock(&inode_hash_lock);
spin_lock(&inode->i_lock);
hlist_del_init(&inode->i_hash);
spin_unlock(&inode->i_lock);
spin_unlock(&inode_hash_lock);
}
EXPORT_SYMBOL(__remove_inode_hash);
void clear_inode(struct inode *inode)
{
/*
* We have to cycle the i_pages lock here because reclaim can be in the
* process of removing the last page (in __delete_from_page_cache())
* and we must not free the mapping under it.
*/
xa_lock_irq(&inode->i_data.i_pages);
BUG_ON(inode->i_data.nrpages);
BUG_ON(inode->i_data.nrexceptional);
xa_unlock_irq(&inode->i_data.i_pages);
BUG_ON(!list_empty(&inode->i_data.private_list));
BUG_ON(!(inode->i_state & I_FREEING));
BUG_ON(inode->i_state & I_CLEAR);
BUG_ON(!list_empty(&inode->i_wb_list));
/* don't need i_lock here, no concurrent mods to i_state */
inode->i_state = I_FREEING | I_CLEAR;
}
EXPORT_SYMBOL(clear_inode);
/*
* Free the inode passed in, removing it from the lists it is still connected
* to. We remove any pages still attached to the inode and wait for any IO that
* is still in progress before finally destroying the inode.
*
* An inode must already be marked I_FREEING so that we avoid the inode being
* moved back onto lists if we race with other code that manipulates the lists
* (e.g. writeback_single_inode). The caller is responsible for setting this.
*
* An inode must already be removed from the LRU list before being evicted from
* the cache. This should occur atomically with setting the I_FREEING state
* flag, so no inodes here should ever be on the LRU when being evicted.
*/
static void evict(struct inode *inode)
{
const struct super_operations *op = inode->i_sb->s_op;
BUG_ON(!(inode->i_state & I_FREEING));
BUG_ON(!list_empty(&inode->i_lru));
if (!list_empty(&inode->i_io_list))
inode_io_list_del(inode);
inode_sb_list_del(inode);
/*
* Wait for flusher thread to be done with the inode so that filesystem
* does not start destroying it while writeback is still running. Since
* the inode has I_FREEING set, flusher thread won't start new work on
* the inode. We just have to wait for running writeback to finish.
*/
inode_wait_for_writeback(inode);
if (op->evict_inode) {
op->evict_inode(inode);
} else {
truncate_inode_pages_final(&inode->i_data);
clear_inode(inode);
}
if (S_ISBLK(inode->i_mode) && inode->i_bdev)
bd_forget(inode);
if (S_ISCHR(inode->i_mode) && inode->i_cdev)
cd_forget(inode);
remove_inode_hash(inode);
spin_lock(&inode->i_lock);
wake_up_bit(&inode->i_state, __I_NEW);
BUG_ON(inode->i_state != (I_FREEING | I_CLEAR));
spin_unlock(&inode->i_lock);
destroy_inode(inode);
}
/*
* dispose_list - dispose of the contents of a local list
* @head: the head of the list to free
*
* Dispose-list gets a local list with local inodes in it, so it doesn't
* need to worry about list corruption and SMP locks.
*/
static void dispose_list(struct list_head *head)
{
while (!list_empty(head)) {
struct inode *inode;
inode = list_first_entry(head, struct inode, i_lru);
list_del_init(&inode->i_lru);
evict(inode);
cond_resched();
}
}
/**
* evict_inodes - evict all evictable inodes for a superblock
* @sb: superblock to operate on
*
* Make sure that no inodes with zero refcount are retained. This is
* called by superblock shutdown after having SB_ACTIVE flag removed,
* so any inode reaching zero refcount during or after that call will
* be immediately evicted.
*/
void evict_inodes(struct super_block *sb)
{
struct inode *inode, *next;
LIST_HEAD(dispose);
again:
spin_lock(&sb->s_inode_list_lock);
list_for_each_entry_safe(inode, next, &sb->s_inodes, i_sb_list) {
if (atomic_read(&inode->i_count))
continue;
spin_lock(&inode->i_lock);
if (inode->i_state & (I_NEW | I_FREEING | I_WILL_FREE)) {
spin_unlock(&inode->i_lock);
continue;
}
inode->i_state |= I_FREEING;
inode_lru_list_del(inode);
spin_unlock(&inode->i_lock);
list_add(&inode->i_lru, &dispose);
/*
* We can have a ton of inodes to evict at unmount time given
* enough memory, check to see if we need to go to sleep for a
* bit so we don't livelock.
*/
if (need_resched()) {
spin_unlock(&sb->s_inode_list_lock);
cond_resched();
dispose_list(&dispose);
goto again;
}
}
spin_unlock(&sb->s_inode_list_lock);
dispose_list(&dispose);
}
EXPORT_SYMBOL_GPL(evict_inodes);
/**
* invalidate_inodes - attempt to free all inodes on a superblock
* @sb: superblock to operate on
* @kill_dirty: flag to guide handling of dirty inodes
*
* Attempts to free all inodes for a given superblock. If there were any
* busy inodes return a non-zero value, else zero.
* If @kill_dirty is set, discard dirty inodes too, otherwise treat
* them as busy.
*/
int invalidate_inodes(struct super_block *sb, bool kill_dirty)
{
int busy = 0;
struct inode *inode, *next;
LIST_HEAD(dispose);
spin_lock(&sb->s_inode_list_lock);
list_for_each_entry_safe(inode, next, &sb->s_inodes, i_sb_list) {
spin_lock(&inode->i_lock);
if (inode->i_state & (I_NEW | I_FREEING | I_WILL_FREE)) {
spin_unlock(&inode->i_lock);
continue;
}
if (inode->i_state & I_DIRTY_ALL && !kill_dirty) {
spin_unlock(&inode->i_lock);
busy = 1;
continue;
}
if (atomic_read(&inode->i_count)) {
spin_unlock(&inode->i_lock);
busy = 1;
continue;
}
inode->i_state |= I_FREEING;
inode_lru_list_del(inode);
spin_unlock(&inode->i_lock);
list_add(&inode->i_lru, &dispose);
}
spin_unlock(&sb->s_inode_list_lock);
dispose_list(&dispose);
return busy;
}
/*
* Isolate the inode from the LRU in preparation for freeing it.
*
* Any inodes which are pinned purely because of attached pagecache have their
* pagecache removed. If the inode has metadata buffers attached to
* mapping->private_list then try to remove them.
*
* If the inode has the I_REFERENCED flag set, then it means that it has been
* used recently - the flag is set in iput_final(). When we encounter such an
* inode, clear the flag and move it to the back of the LRU so it gets another
* pass through the LRU before it gets reclaimed. This is necessary because of
* the fact we are doing lazy LRU updates to minimise lock contention so the
* LRU does not have strict ordering. Hence we don't want to reclaim inodes
* with this flag set because they are the inodes that are out of order.
*/
static enum lru_status inode_lru_isolate(struct list_head *item,
struct list_lru_one *lru, spinlock_t *lru_lock, void *arg)
{
struct list_head *freeable = arg;
struct inode *inode = container_of(item, struct inode, i_lru);
/*
* we are inverting the lru lock/inode->i_lock here, so use a trylock.
* If we fail to get the lock, just skip it.
*/
if (!spin_trylock(&inode->i_lock))
return LRU_SKIP;
/*
* Referenced or dirty inodes are still in use. Give them another pass
* through the LRU as we canot reclaim them now.
*/
if (atomic_read(&inode->i_count) ||
(inode->i_state & ~I_REFERENCED)) {
list_lru_isolate(lru, &inode->i_lru);
spin_unlock(&inode->i_lock);
this_cpu_dec(nr_unused);
return LRU_REMOVED;
}
/* recently referenced inodes get one more pass */
if (inode->i_state & I_REFERENCED) {
inode->i_state &= ~I_REFERENCED;
spin_unlock(&inode->i_lock);
return LRU_ROTATE;
}
if (inode_has_buffers(inode) || inode->i_data.nrpages) {
__iget(inode);
spin_unlock(&inode->i_lock);
spin_unlock(lru_lock);
if (remove_inode_buffers(inode)) {
unsigned long reap;
reap = invalidate_mapping_pages(&inode->i_data, 0, -1);
if (current_is_kswapd())
__count_vm_events(KSWAPD_INODESTEAL, reap);
else
__count_vm_events(PGINODESTEAL, reap);
if (current->reclaim_state)
current->reclaim_state->reclaimed_slab += reap;
}
iput(inode);
spin_lock(lru_lock);
return LRU_RETRY;
}
WARN_ON(inode->i_state & I_NEW);
inode->i_state |= I_FREEING;
list_lru_isolate_move(lru, &inode->i_lru, freeable);
spin_unlock(&inode->i_lock);
this_cpu_dec(nr_unused);
return LRU_REMOVED;
}
/*
* Walk the superblock inode LRU for freeable inodes and attempt to free them.
* This is called from the superblock shrinker function with a number of inodes
* to trim from the LRU. Inodes to be freed are moved to a temporary list and
* then are freed outside inode_lock by dispose_list().
*/
long prune_icache_sb(struct super_block *sb, struct shrink_control *sc)
{
LIST_HEAD(freeable);
long freed;
freed = list_lru_shrink_walk(&sb->s_inode_lru, sc,
inode_lru_isolate, &freeable);
dispose_list(&freeable);
return freed;
}
static void __wait_on_freeing_inode(struct inode *inode);
/*
* Called with the inode lock held.
*/
static struct inode *find_inode(struct super_block *sb,
struct hlist_head *head,
int (*test)(struct inode *, void *),
void *data)
{
struct inode *inode = NULL;
repeat:
hlist_for_each_entry(inode, head, i_hash) {
if (inode->i_sb != sb)
continue;
if (!test(inode, data))
continue;
spin_lock(&inode->i_lock);
if (inode->i_state & (I_FREEING|I_WILL_FREE)) {
__wait_on_freeing_inode(inode);
goto repeat;
}
__iget(inode);
spin_unlock(&inode->i_lock);
return inode;
}
return NULL;
}
/*
* find_inode_fast is the fast path version of find_inode, see the comment at
* iget_locked for details.
*/
static struct inode *find_inode_fast(struct super_block *sb,
struct hlist_head *head, unsigned long ino)
{
struct inode *inode = NULL;
repeat:
hlist_for_each_entry(inode, head, i_hash) {
if (inode->i_ino != ino)
continue;
if (inode->i_sb != sb)
continue;
spin_lock(&inode->i_lock);
if (inode->i_state & (I_FREEING|I_WILL_FREE)) {
__wait_on_freeing_inode(inode);
goto repeat;
}
__iget(inode);
spin_unlock(&inode->i_lock);
return inode;
}
return NULL;
}
/*
* Each cpu owns a range of LAST_INO_BATCH numbers.
* 'shared_last_ino' is dirtied only once out of LAST_INO_BATCH allocations,
* to renew the exhausted range.
*
* This does not significantly increase overflow rate because every CPU can
* consume at most LAST_INO_BATCH-1 unused inode numbers. So there is
* NR_CPUS*(LAST_INO_BATCH-1) wastage. At 4096 and 1024, this is ~0.1% of the
* 2^32 range, and is a worst-case. Even a 50% wastage would only increase
* overflow rate by 2x, which does not seem too significant.
*
* On a 32bit, non LFS stat() call, glibc will generate an EOVERFLOW
* error if st_ino won't fit in target struct field. Use 32bit counter
* here to attempt to avoid that.
*/
#define LAST_INO_BATCH 1024
static DEFINE_PER_CPU(unsigned int, last_ino);
unsigned int get_next_ino(void)
{
unsigned int *p = &get_cpu_var(last_ino);
unsigned int res = *p;
#ifdef CONFIG_SMP
if (unlikely((res & (LAST_INO_BATCH-1)) == 0)) {
static atomic_t shared_last_ino;
int next = atomic_add_return(LAST_INO_BATCH, &shared_last_ino);
res = next - LAST_INO_BATCH;
}
#endif
res++;
/* get_next_ino should not provide a 0 inode number */
if (unlikely(!res))
res++;
*p = res;
put_cpu_var(last_ino);
return res;
}
EXPORT_SYMBOL(get_next_ino);
/**
* new_inode_pseudo - obtain an inode
* @sb: superblock
*
* Allocates a new inode for given superblock.
* Inode wont be chained in superblock s_inodes list
* This means :
* - fs can't be unmount
* - quotas, fsnotify, writeback can't work
*/
struct inode *new_inode_pseudo(struct super_block *sb)
{
struct inode *inode = alloc_inode(sb);
if (inode) {
spin_lock(&inode->i_lock);
inode->i_state = 0;
spin_unlock(&inode->i_lock);
INIT_LIST_HEAD(&inode->i_sb_list);
}
return inode;
}
/**
* new_inode - obtain an inode
* @sb: superblock
*
* Allocates a new inode for given superblock. The default gfp_mask
* for allocations related to inode->i_mapping is GFP_HIGHUSER_MOVABLE.
* If HIGHMEM pages are unsuitable or it is known that pages allocated
* for the page cache are not reclaimable or migratable,
* mapping_set_gfp_mask() must be called with suitable flags on the
* newly created inode's mapping
*
*/
struct inode *new_inode(struct super_block *sb)
{
struct inode *inode;
spin_lock_prefetch(&sb->s_inode_list_lock);
inode = new_inode_pseudo(sb);
if (inode)
inode_sb_list_add(inode);
return inode;
}
EXPORT_SYMBOL(new_inode);
#ifdef CONFIG_DEBUG_LOCK_ALLOC
void lockdep_annotate_inode_mutex_key(struct inode *inode)
{
if (S_ISDIR(inode->i_mode)) {
struct file_system_type *type = inode->i_sb->s_type;
/* Set new key only if filesystem hasn't already changed it */
if (lockdep_match_class(&inode->i_rwsem, &type->i_mutex_key)) {
/*
* ensure nobody is actually holding i_mutex
*/
// mutex_destroy(&inode->i_mutex);
init_rwsem(&inode->i_rwsem);
lockdep_set_class(&inode->i_rwsem,
&type->i_mutex_dir_key);
}
}
}
EXPORT_SYMBOL(lockdep_annotate_inode_mutex_key);
#endif
/**
* unlock_new_inode - clear the I_NEW state and wake up any waiters
* @inode: new inode to unlock
*
* Called when the inode is fully initialised to clear the new state of the
* inode and wake up anyone waiting for the inode to finish initialisation.
*/
void unlock_new_inode(struct inode *inode)
{
lockdep_annotate_inode_mutex_key(inode);
spin_lock(&inode->i_lock);
WARN_ON(!(inode->i_state & I_NEW));
inode->i_state &= ~I_NEW;
smp_mb();
wake_up_bit(&inode->i_state, __I_NEW);
spin_unlock(&inode->i_lock);
}
EXPORT_SYMBOL(unlock_new_inode);
/**
* lock_two_nondirectories - take two i_mutexes on non-directory objects
*
* Lock any non-NULL argument that is not a directory.
* Zero, one or two objects may be locked by this function.
*
* @inode1: first inode to lock
* @inode2: second inode to lock
*/
void lock_two_nondirectories(struct inode *inode1, struct inode *inode2)
{
if (inode1 > inode2)
swap(inode1, inode2);
if (inode1 && !S_ISDIR(inode1->i_mode))
inode_lock(inode1);
if (inode2 && !S_ISDIR(inode2->i_mode) && inode2 != inode1)
inode_lock_nested(inode2, I_MUTEX_NONDIR2);
}
EXPORT_SYMBOL(lock_two_nondirectories);
/**
* unlock_two_nondirectories - release locks from lock_two_nondirectories()
* @inode1: first inode to unlock
* @inode2: second inode to unlock
*/
void unlock_two_nondirectories(struct inode *inode1, struct inode *inode2)
{
if (inode1 && !S_ISDIR(inode1->i_mode))
inode_unlock(inode1);
if (inode2 && !S_ISDIR(inode2->i_mode) && inode2 != inode1)
inode_unlock(inode2);
}
EXPORT_SYMBOL(unlock_two_nondirectories);
/**
* inode_insert5 - obtain an inode from a mounted file system
* @inode: pre-allocated inode to use for insert to cache
* @hashval: hash value (usually inode number) to get
* @test: callback used for comparisons between inodes
* @set: callback used to initialize a new struct inode
* @data: opaque data pointer to pass to @test and @set
*
* Search for the inode specified by @hashval and @data in the inode cache,
* and if present it is return it with an increased reference count. This is
* a variant of iget5_locked() for callers that don't want to fail on memory
* allocation of inode.
*
* If the inode is not in cache, insert the pre-allocated inode to cache and
* return it locked, hashed, and with the I_NEW flag set. The file system gets
* to fill it in before unlocking it via unlock_new_inode().
*
* Note both @test and @set are called with the inode_hash_lock held, so can't
* sleep.
*/
struct inode *inode_insert5(struct inode *inode, unsigned long hashval,
int (*test)(struct inode *, void *),
int (*set)(struct inode *, void *), void *data)
{
struct hlist_head *head = inode_hashtable + hash(inode->i_sb, hashval);
struct inode *old;
again:
spin_lock(&inode_hash_lock);
old = find_inode(inode->i_sb, head, test, data);
if (unlikely(old)) {
/*
* Uhhuh, somebody else created the same inode under us.
* Use the old inode instead of the preallocated one.
*/
spin_unlock(&inode_hash_lock);
wait_on_inode(old);
if (unlikely(inode_unhashed(old))) {
iput(old);
goto again;
}
return old;
}
if (set && unlikely(set(inode, data))) {
inode = NULL;
goto unlock;
}
/*
* Return the locked inode with I_NEW set, the
* caller is responsible for filling in the contents
*/
spin_lock(&inode->i_lock);
inode->i_state |= I_NEW;
hlist_add_head(&inode->i_hash, head);
spin_unlock(&inode->i_lock);
unlock:
spin_unlock(&inode_hash_lock);
return inode;
}
EXPORT_SYMBOL(inode_insert5);
/**
* iget5_locked - obtain an inode from a mounted file system
* @sb: super block of file system
* @hashval: hash value (usually inode number) to get
* @test: callback used for comparisons between inodes
* @set: callback used to initialize a new struct inode
* @data: opaque data pointer to pass to @test and @set
*
* Search for the inode specified by @hashval and @data in the inode cache,
* and if present it is return it with an increased reference count. This is
* a generalized version of iget_locked() for file systems where the inode
* number is not sufficient for unique identification of an inode.
*
* If the inode is not in cache, allocate a new inode and return it locked,
* hashed, and with the I_NEW flag set. The file system gets to fill it in
* before unlocking it via unlock_new_inode().
*
* Note both @test and @set are called with the inode_hash_lock held, so can't
* sleep.
*/
struct inode *iget5_locked(struct super_block *sb, unsigned long hashval,
int (*test)(struct inode *, void *),
int (*set)(struct inode *, void *), void *data)
{
struct inode *inode = ilookup5(sb, hashval, test, data);
if (!inode) {
struct inode *new = new_inode(sb);
if (new) {
inode = inode_insert5(new, hashval, test, set, data);
if (unlikely(inode != new))
iput(new);
}
}
return inode;
}
EXPORT_SYMBOL(iget5_locked);
/**
* iget_locked - obtain an inode from a mounted file system
* @sb: super block of file system
* @ino: inode number to get
*
* Search for the inode specified by @ino in the inode cache and if present
* return it with an increased reference count. This is for file systems
* where the inode number is sufficient for unique identification of an inode.
*
* If the inode is not in cache, allocate a new inode and return it locked,
* hashed, and with the I_NEW flag set. The file system gets to fill it in
* before unlocking it via unlock_new_inode().
*/
struct inode *iget_locked(struct super_block *sb, unsigned long ino)
{
struct hlist_head *head = inode_hashtable + hash(sb, ino);
struct inode *inode;
again:
spin_lock(&inode_hash_lock);
inode = find_inode_fast(sb, head, ino);
spin_unlock(&inode_hash_lock);
if (inode) {
wait_on_inode(inode);
if (unlikely(inode_unhashed(inode))) {
iput(inode);
goto again;
}
return inode;
}
inode = alloc_inode(sb);
if (inode) {
struct inode *old;
spin_lock(&inode_hash_lock);
/* We released the lock, so.. */
old = find_inode_fast(sb, head, ino);
if (!old) {
inode->i_ino = ino;
spin_lock(&inode->i_lock);
inode->i_state = I_NEW;
hlist_add_head(&inode->i_hash, head);
spin_unlock(&inode->i_lock);
inode_sb_list_add(inode);
spin_unlock(&inode_hash_lock);
/* Return the locked inode with I_NEW set, the
* caller is responsible for filling in the contents
*/
return inode;
}
/*
* Uhhuh, somebody else created the same inode under
* us. Use the old inode instead of the one we just
* allocated.
*/
spin_unlock(&inode_hash_lock);
destroy_inode(inode);
inode = old;
wait_on_inode(inode);
if (unlikely(inode_unhashed(inode))) {
iput(inode);
goto again;
}
}
return inode;
}
EXPORT_SYMBOL(iget_locked);
/*
* search the inode cache for a matching inode number.
* If we find one, then the inode number we are trying to
* allocate is not unique and so we should not use it.
*
* Returns 1 if the inode number is unique, 0 if it is not.
*/
static int test_inode_iunique(struct super_block *sb, unsigned long ino)
{
struct hlist_head *b = inode_hashtable + hash(sb, ino);
struct inode *inode;
spin_lock(&inode_hash_lock);
hlist_for_each_entry(inode, b, i_hash) {
if (inode->i_ino == ino && inode->i_sb == sb) {
spin_unlock(&inode_hash_lock);
return 0;
}
}
spin_unlock(&inode_hash_lock);
return 1;
}
/**
* iunique - get a unique inode number
* @sb: superblock
* @max_reserved: highest reserved inode number
*
* Obtain an inode number that is unique on the system for a given
* superblock. This is used by file systems that have no natural
* permanent inode numbering system. An inode number is returned that
* is higher than the reserved limit but unique.
*
* BUGS:
* With a large number of inodes live on the file system this function
* currently becomes quite slow.
*/
ino_t iunique(struct super_block *sb, ino_t max_reserved)
{
/*
* On a 32bit, non LFS stat() call, glibc will generate an EOVERFLOW
* error if st_ino won't fit in target struct field. Use 32bit counter
* here to attempt to avoid that.
*/
static DEFINE_SPINLOCK(iunique_lock);
static unsigned int counter;
ino_t res;
spin_lock(&iunique_lock);
do {
if (counter <= max_reserved)
counter = max_reserved + 1;
res = counter++;
} while (!test_inode_iunique(sb, res));
spin_unlock(&iunique_lock);
return res;
}
EXPORT_SYMBOL(iunique);
struct inode *igrab(struct inode *inode)
{
spin_lock(&inode->i_lock);
if (!(inode->i_state & (I_FREEING|I_WILL_FREE))) {
__iget(inode);
spin_unlock(&inode->i_lock);
} else {
spin_unlock(&inode->i_lock);
/*
* Handle the case where s_op->clear_inode is not been
* called yet, and somebody is calling igrab
* while the inode is getting freed.
*/
inode = NULL;
}
return inode;
}
EXPORT_SYMBOL(igrab);
/**
* ilookup5_nowait - search for an inode in the inode cache
* @sb: super block of file system to search
* @hashval: hash value (usually inode number) to search for
* @test: callback used for comparisons between inodes
* @data: opaque data pointer to pass to @test
*
* Search for the inode specified by @hashval and @data in the inode cache.
* If the inode is in the cache, the inode is returned with an incremented
* reference count.
*
* Note: I_NEW is not waited upon so you have to be very careful what you do
* with the returned inode. You probably should be using ilookup5() instead.
*
* Note2: @test is called with the inode_hash_lock held, so can't sleep.
*/
struct inode *ilookup5_nowait(struct super_block *sb, unsigned long hashval,
int (*test)(struct inode *, void *), void *data)
{
struct hlist_head *head = inode_hashtable + hash(sb, hashval);
struct inode *inode;
spin_lock(&inode_hash_lock);
inode = find_inode(sb, head, test, data);
spin_unlock(&inode_hash_lock);
return inode;
}
EXPORT_SYMBOL(ilookup5_nowait);
/**
* ilookup5 - search for an inode in the inode cache
* @sb: super block of file system to search
* @hashval: hash value (usually inode number) to search for
* @test: callback used for comparisons between inodes
* @data: opaque data pointer to pass to @test
*
* Search for the inode specified by @hashval and @data in the inode cache,
* and if the inode is in the cache, return the inode with an incremented
* reference count. Waits on I_NEW before returning the inode.
* returned with an incremented reference count.
*
* This is a generalized version of ilookup() for file systems where the
* inode number is not sufficient for unique identification of an inode.
*
* Note: @test is called with the inode_hash_lock held, so can't sleep.
*/
struct inode *ilookup5(struct super_block *sb, unsigned long hashval,
int (*test)(struct inode *, void *), void *data)
{
struct inode *inode;
again:
inode = ilookup5_nowait(sb, hashval, test, data);
if (inode) {
wait_on_inode(inode);
if (unlikely(inode_unhashed(inode))) {
iput(inode);
goto again;
}
}
return inode;
}
EXPORT_SYMBOL(ilookup5);
/**
* ilookup - search for an inode in the inode cache
* @sb: super block of file system to search
* @ino: inode number to search for
*
* Search for the inode @ino in the inode cache, and if the inode is in the
* cache, the inode is returned with an incremented reference count.
*/
struct inode *ilookup(struct super_block *sb, unsigned long ino)
{
struct hlist_head *head = inode_hashtable + hash(sb, ino);
struct inode *inode;
again:
spin_lock(&inode_hash_lock);
inode = find_inode_fast(sb, head, ino);
spin_unlock(&inode_hash_lock);
if (inode) {
wait_on_inode(inode);
if (unlikely(inode_unhashed(inode))) {
iput(inode);
goto again;
}
}
return inode;
}
EXPORT_SYMBOL(ilookup);
/**
* find_inode_nowait - find an inode in the inode cache
* @sb: super block of file system to search
* @hashval: hash value (usually inode number) to search for
* @match: callback used for comparisons between inodes
* @data: opaque data pointer to pass to @match
*
* Search for the inode specified by @hashval and @data in the inode
* cache, where the helper function @match will return 0 if the inode
* does not match, 1 if the inode does match, and -1 if the search
* should be stopped. The @match function must be responsible for
* taking the i_lock spin_lock and checking i_state for an inode being
* freed or being initialized, and incrementing the reference count
* before returning 1. It also must not sleep, since it is called with
* the inode_hash_lock spinlock held.
*
* This is a even more generalized version of ilookup5() when the
* function must never block --- find_inode() can block in
* __wait_on_freeing_inode() --- or when the caller can not increment
* the reference count because the resulting iput() might cause an
* inode eviction. The tradeoff is that the @match funtion must be
* very carefully implemented.
*/
struct inode *find_inode_nowait(struct super_block *sb,
unsigned long hashval,
int (*match)(struct inode *, unsigned long,
void *),
void *data)
{
struct hlist_head *head = inode_hashtable + hash(sb, hashval);
struct inode *inode, *ret_inode = NULL;
int mval;
spin_lock(&inode_hash_lock);
hlist_for_each_entry(inode, head, i_hash) {
if (inode->i_sb != sb)
continue;
mval = match(inode, hashval, data);
if (mval == 0)
continue;
if (mval == 1)
ret_inode = inode;
goto out;
}
out:
spin_unlock(&inode_hash_lock);
return ret_inode;
}
EXPORT_SYMBOL(find_inode_nowait);
int insert_inode_locked(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
ino_t ino = inode->i_ino;
struct hlist_head *head = inode_hashtable + hash(sb, ino);
while (1) {
struct inode *old = NULL;
spin_lock(&inode_hash_lock);
hlist_for_each_entry(old, head, i_hash) {
if (old->i_ino != ino)
continue;
if (old->i_sb != sb)
continue;
spin_lock(&old->i_lock);
if (old->i_state & (I_FREEING|I_WILL_FREE)) {
spin_unlock(&old->i_lock);
continue;
}
break;
}
if (likely(!old)) {
spin_lock(&inode->i_lock);
inode->i_state |= I_NEW;
hlist_add_head(&inode->i_hash, head);
spin_unlock(&inode->i_lock);
spin_unlock(&inode_hash_lock);
return 0;
}
__iget(old);
spin_unlock(&old->i_lock);
spin_unlock(&inode_hash_lock);
wait_on_inode(old);
if (unlikely(!inode_unhashed(old))) {
iput(old);
return -EBUSY;
}
iput(old);
}
}
EXPORT_SYMBOL(insert_inode_locked);
int insert_inode_locked4(struct inode *inode, unsigned long hashval,
int (*test)(struct inode *, void *), void *data)
{
struct inode *old = inode_insert5(inode, hashval, test, NULL, data);
if (old != inode) {
iput(old);
return -EBUSY;
}
return 0;
}
EXPORT_SYMBOL(insert_inode_locked4);
int generic_delete_inode(struct inode *inode)
{
return 1;
}
EXPORT_SYMBOL(generic_delete_inode);
/*
* Called when we're dropping the last reference
* to an inode.
*
* Call the FS "drop_inode()" function, defaulting to
* the legacy UNIX filesystem behaviour. If it tells
* us to evict inode, do so. Otherwise, retain inode
* in cache if fs is alive, sync and evict if fs is
* shutting down.
*/
static void iput_final(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
const struct super_operations *op = inode->i_sb->s_op;
int drop;
WARN_ON(inode->i_state & I_NEW);
if (op->drop_inode)
drop = op->drop_inode(inode);
else
drop = generic_drop_inode(inode);
if (!drop && (sb->s_flags & SB_ACTIVE)) {
inode_add_lru(inode);
spin_unlock(&inode->i_lock);
return;
}
if (!drop) {
inode->i_state |= I_WILL_FREE;
spin_unlock(&inode->i_lock);
write_inode_now(inode, 1);
spin_lock(&inode->i_lock);
WARN_ON(inode->i_state & I_NEW);
inode->i_state &= ~I_WILL_FREE;
}
inode->i_state |= I_FREEING;
if (!list_empty(&inode->i_lru))
inode_lru_list_del(inode);
spin_unlock(&inode->i_lock);
evict(inode);
}
/**
* iput - put an inode
* @inode: inode to put
*
* Puts an inode, dropping its usage count. If the inode use count hits
* zero, the inode is then freed and may also be destroyed.
*
* Consequently, iput() can sleep.
*/
void iput(struct inode *inode)
{
if (!inode)
return;
BUG_ON(inode->i_state & I_CLEAR);
retry:
if (atomic_dec_and_lock(&inode->i_count, &inode->i_lock)) {
if (inode->i_nlink && (inode->i_state & I_DIRTY_TIME)) {
atomic_inc(&inode->i_count);
spin_unlock(&inode->i_lock);
trace_writeback_lazytime_iput(inode);
mark_inode_dirty_sync(inode);
goto retry;
}
iput_final(inode);
}
}
EXPORT_SYMBOL(iput);
/**
* bmap - find a block number in a file
* @inode: inode of file
* @block: block to find
*
* Returns the block number on the device holding the inode that
* is the disk block number for the block of the file requested.
* That is, asked for block 4 of inode 1 the function will return the
* disk block relative to the disk start that holds that block of the
* file.
*/
sector_t bmap(struct inode *inode, sector_t block)
{
sector_t res = 0;
if (inode->i_mapping->a_ops->bmap)
res = inode->i_mapping->a_ops->bmap(inode->i_mapping, block);
return res;
}
EXPORT_SYMBOL(bmap);
/*
* Update times in overlayed inode from underlying real inode
*/
static void update_ovl_inode_times(struct dentry *dentry, struct inode *inode,
bool rcu)
{
struct dentry *upperdentry;
/*
* Nothing to do if in rcu or if non-overlayfs
*/
if (rcu || likely(!(dentry->d_flags & DCACHE_OP_REAL)))
return;
upperdentry = d_real(dentry, NULL, 0, D_REAL_UPPER);
/*
* If file is on lower then we can't update atime, so no worries about
* stale mtime/ctime.
*/
if (upperdentry) {
struct inode *realinode = d_inode(upperdentry);
if ((!timespec64_equal(&inode->i_mtime, &realinode->i_mtime) ||
!timespec64_equal(&inode->i_ctime, &realinode->i_ctime))) {
inode->i_mtime = realinode->i_mtime;
inode->i_ctime = realinode->i_ctime;
}
}
}
/*
* With relative atime, only update atime if the previous atime is
* earlier than either the ctime or mtime or if at least a day has
* passed since the last atime update.
*/
static int relatime_need_update(const struct path *path, struct inode *inode,
struct timespec now, bool rcu)
{
if (!(path->mnt->mnt_flags & MNT_RELATIME))
return 1;
update_ovl_inode_times(path->dentry, inode, rcu);
/*
* Is mtime younger than atime? If yes, update atime:
*/
if (timespec64_compare(&inode->i_mtime, &inode->i_atime) >= 0)
return 1;
/*
* Is ctime younger than atime? If yes, update atime:
*/
if (timespec64_compare(&inode->i_ctime, &inode->i_atime) >= 0)
return 1;
/*
* Is the previous atime value older than a day? If yes,
* update atime:
*/
if ((long)(now.tv_sec - inode->i_atime.tv_sec) >= 24*60*60)
return 1;
/*
* Good, we can skip the atime update:
*/
return 0;
}
int generic_update_time(struct inode *inode, struct timespec64 *time, int flags)
{
int iflags = I_DIRTY_TIME;
bool dirty = false;
if (flags & S_ATIME)
inode->i_atime = *time;
if (flags & S_VERSION)
dirty = inode_maybe_inc_iversion(inode, false);
if (flags & S_CTIME)
inode->i_ctime = *time;
if (flags & S_MTIME)
inode->i_mtime = *time;
if ((flags & (S_ATIME | S_CTIME | S_MTIME)) &&
!(inode->i_sb->s_flags & SB_LAZYTIME))
dirty = true;
if (dirty)
iflags |= I_DIRTY_SYNC;
__mark_inode_dirty(inode, iflags);
return 0;
}
EXPORT_SYMBOL(generic_update_time);
/*
* This does the actual work of updating an inodes time or version. Must have
* had called mnt_want_write() before calling this.
*/
static int update_time(struct inode *inode, struct timespec64 *time, int flags)
{
int (*update_time)(struct inode *, struct timespec64 *, int);
update_time = inode->i_op->update_time ? inode->i_op->update_time :
generic_update_time;
return update_time(inode, time, flags);
}
/**
* touch_atime - update the access time
* @path: the &struct path to update
* @inode: inode to update
*
* Update the accessed time on an inode and mark it for writeback.
* This function automatically handles read only file systems and media,
* as well as the "noatime" flag and inode specific "noatime" markers.
*/
bool __atime_needs_update(const struct path *path, struct inode *inode,
bool rcu)
{
struct vfsmount *mnt = path->mnt;
struct timespec64 now;
if (inode->i_flags & S_NOATIME)
return false;
/* Atime updates will likely cause i_uid and i_gid to be written
* back improprely if their true value is unknown to the vfs.
*/
if (HAS_UNMAPPED_ID(inode))
return false;
if (IS_NOATIME(inode))
return false;
if ((inode->i_sb->s_flags & SB_NODIRATIME) && S_ISDIR(inode->i_mode))
return false;
if (mnt->mnt_flags & MNT_NOATIME)
return false;
if ((mnt->mnt_flags & MNT_NODIRATIME) && S_ISDIR(inode->i_mode))
return false;
now = current_time(inode);
if (!relatime_need_update(path, inode, timespec64_to_timespec(now), rcu))
return false;
if (timespec64_equal(&inode->i_atime, &now))
return false;
return true;
}
void touch_atime(const struct path *path)
{
struct vfsmount *mnt = path->mnt;
struct inode *inode = d_inode(path->dentry);
struct timespec64 now;
if (!__atime_needs_update(path, inode, false))
return;
if (!sb_start_write_trylock(inode->i_sb))
return;
if (__mnt_want_write(mnt) != 0)
goto skip_update;
/*
* File systems can error out when updating inodes if they need to
* allocate new space to modify an inode (such is the case for
* Btrfs), but since we touch atime while walking down the path we
* really don't care if we failed to update the atime of the file,
* so just ignore the return value.
* We may also fail on filesystems that have the ability to make parts
* of the fs read only, e.g. subvolumes in Btrfs.
*/
now = current_time(inode);
update_time(inode, &now, S_ATIME);
__mnt_drop_write(mnt);
skip_update:
sb_end_write(inode->i_sb);
}
EXPORT_SYMBOL(touch_atime);
/*
* The logic we want is
*
* if suid or (sgid and xgrp)
* remove privs
*/
int should_remove_suid(struct dentry *dentry)
{
umode_t mode = d_inode(dentry)->i_mode;
int kill = 0;
/* suid always must be killed */
if (unlikely(mode & S_ISUID))
kill = ATTR_KILL_SUID;
/*
* sgid without any exec bits is just a mandatory locking mark; leave
* it alone. If some exec bits are set, it's a real sgid; kill it.
*/
if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
kill |= ATTR_KILL_SGID;
if (unlikely(kill && !capable(CAP_FSETID) && S_ISREG(mode)))
return kill;
return 0;
}
EXPORT_SYMBOL(should_remove_suid);
/*
* Return mask of changes for notify_change() that need to be done as a
* response to write or truncate. Return 0 if nothing has to be changed.
* Negative value on error (change should be denied).
*/
int dentry_needs_remove_privs(struct dentry *dentry)
{
struct inode *inode = d_inode(dentry);
int mask = 0;
int ret;
if (IS_NOSEC(inode))
return 0;
mask = should_remove_suid(dentry);
ret = security_inode_need_killpriv(dentry);
if (ret < 0)
return ret;
if (ret)
mask |= ATTR_KILL_PRIV;
return mask;
}
static int __remove_privs(struct dentry *dentry, int kill)
{
struct iattr newattrs;
newattrs.ia_valid = ATTR_FORCE | kill;
/*
* Note we call this on write, so notify_change will not
* encounter any conflicting delegations:
*/
return notify_change(dentry, &newattrs, NULL);
}
/*
* Remove special file priviledges (suid, capabilities) when file is written
* to or truncated.
*/
int file_remove_privs(struct file *file)
{
struct dentry *dentry = file_dentry(file);
struct inode *inode = file_inode(file);
int kill;
int error = 0;
/* Fast path for nothing security related */
if (IS_NOSEC(inode))
return 0;
kill = dentry_needs_remove_privs(dentry);
if (kill < 0)
return kill;
if (kill)
error = __remove_privs(dentry, kill);
if (!error)
inode_has_no_xattr(inode);
return error;
}
EXPORT_SYMBOL(file_remove_privs);
/**
* file_update_time - update mtime and ctime time
* @file: file accessed
*
* Update the mtime and ctime members of an inode and mark the inode
* for writeback. Note that this function is meant exclusively for
* usage in the file write path of filesystems, and filesystems may
* choose to explicitly ignore update via this function with the
* S_NOCMTIME inode flag, e.g. for network filesystem where these
* timestamps are handled by the server. This can return an error for
* file systems who need to allocate space in order to update an inode.
*/
int file_update_time(struct file *file)
{
struct inode *inode = file_inode(file);
struct timespec64 now;
int sync_it = 0;
int ret;
/* First try to exhaust all avenues to not sync */
if (IS_NOCMTIME(inode))
return 0;
now = current_time(inode);
if (!timespec64_equal(&inode->i_mtime, &now))
sync_it = S_MTIME;
if (!timespec64_equal(&inode->i_ctime, &now))
sync_it |= S_CTIME;
if (IS_I_VERSION(inode) && inode_iversion_need_inc(inode))
sync_it |= S_VERSION;
if (!sync_it)
return 0;
/* Finally allowed to write? Takes lock. */
if (__mnt_want_write_file(file))
return 0;
ret = update_time(inode, &now, sync_it);
__mnt_drop_write_file(file);
return ret;
}
EXPORT_SYMBOL(file_update_time);
int inode_needs_sync(struct inode *inode)
{
if (IS_SYNC(inode))
return 1;
if (S_ISDIR(inode->i_mode) && IS_DIRSYNC(inode))
return 1;
return 0;
}
EXPORT_SYMBOL(inode_needs_sync);
/*
* If we try to find an inode in the inode hash while it is being
* deleted, we have to wait until the filesystem completes its
* deletion before reporting that it isn't found. This function waits
* until the deletion _might_ have completed. Callers are responsible
* to recheck inode state.
*
* It doesn't matter if I_NEW is not set initially, a call to
* wake_up_bit(&inode->i_state, __I_NEW) after removing from the hash list
* will DTRT.
*/
static void __wait_on_freeing_inode(struct inode *inode)
{
wait_queue_head_t *wq;
DEFINE_WAIT_BIT(wait, &inode->i_state, __I_NEW);
wq = bit_waitqueue(&inode->i_state, __I_NEW);
prepare_to_wait(wq, &wait.wq_entry, TASK_UNINTERRUPTIBLE);
spin_unlock(&inode->i_lock);
spin_unlock(&inode_hash_lock);
schedule();
finish_wait(wq, &wait.wq_entry);
spin_lock(&inode_hash_lock);
}
static __initdata unsigned long ihash_entries;
static int __init set_ihash_entries(char *str)
{
if (!str)
return 0;
ihash_entries = simple_strtoul(str, &str, 0);
return 1;
}
__setup("ihash_entries=", set_ihash_entries);
/*
* Initialize the waitqueues and inode hash table.
*/
void __init inode_init_early(void)
{
/* If hashes are distributed across NUMA nodes, defer
* hash allocation until vmalloc space is available.
*/
if (hashdist)
return;
inode_hashtable =
alloc_large_system_hash("Inode-cache",
sizeof(struct hlist_head),
ihash_entries,
14,
HASH_EARLY | HASH_ZERO,
&i_hash_shift,
&i_hash_mask,
0,
0);
}
void __init inode_init(void)
{
/* inode slab cache */
inode_cachep = kmem_cache_create("inode_cache",
sizeof(struct inode),
0,
(SLAB_RECLAIM_ACCOUNT|SLAB_PANIC|
SLAB_MEM_SPREAD|SLAB_ACCOUNT),
init_once);
/* Hash may have been set up in inode_init_early */
if (!hashdist)
return;
inode_hashtable =
alloc_large_system_hash("Inode-cache",
sizeof(struct hlist_head),
ihash_entries,
14,
HASH_ZERO,
&i_hash_shift,
&i_hash_mask,
0,
0);
}
void init_special_inode(struct inode *inode, umode_t mode, dev_t rdev)
{
inode->i_mode = mode;
if (S_ISCHR(mode)) {
inode->i_fop = &def_chr_fops;
inode->i_rdev = rdev;
} else if (S_ISBLK(mode)) {
inode->i_fop = &def_blk_fops;
inode->i_rdev = rdev;
} else if (S_ISFIFO(mode))
inode->i_fop = &pipefifo_fops;
else if (S_ISSOCK(mode))
; /* leave it no_open_fops */
else
printk(KERN_DEBUG "init_special_inode: bogus i_mode (%o) for"
" inode %s:%lu\n", mode, inode->i_sb->s_id,
inode->i_ino);
}
EXPORT_SYMBOL(init_special_inode);
/**
* inode_init_owner - Init uid,gid,mode for new inode according to posix standards
* @inode: New inode
* @dir: Directory inode
* @mode: mode of the new inode
*/
void inode_init_owner(struct inode *inode, const struct inode *dir,
umode_t mode)
{
inode->i_uid = current_fsuid();
if (dir && dir->i_mode & S_ISGID) {
inode->i_gid = dir->i_gid;
/* Directories are special, and always inherit S_ISGID */
if (S_ISDIR(mode))
mode |= S_ISGID;
else if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP) &&
!in_group_p(inode->i_gid) &&
!capable_wrt_inode_uidgid(dir, CAP_FSETID))
mode &= ~S_ISGID;
} else
inode->i_gid = current_fsgid();
inode->i_mode = mode;
}
EXPORT_SYMBOL(inode_init_owner);
/**
* inode_owner_or_capable - check current task permissions to inode
* @inode: inode being checked
*
* Return true if current either has CAP_FOWNER in a namespace with the
* inode owner uid mapped, or owns the file.
*/
bool inode_owner_or_capable(const struct inode *inode)
{
struct user_namespace *ns;
if (uid_eq(current_fsuid(), inode->i_uid))
return true;
ns = current_user_ns();
if (kuid_has_mapping(ns, inode->i_uid) && ns_capable(ns, CAP_FOWNER))
return true;
return false;
}
EXPORT_SYMBOL(inode_owner_or_capable);
/*
* Direct i/o helper functions
*/
static void __inode_dio_wait(struct inode *inode)
{
wait_queue_head_t *wq = bit_waitqueue(&inode->i_state, __I_DIO_WAKEUP);
DEFINE_WAIT_BIT(q, &inode->i_state, __I_DIO_WAKEUP);
do {
prepare_to_wait(wq, &q.wq_entry, TASK_UNINTERRUPTIBLE);
if (atomic_read(&inode->i_dio_count))
schedule();
} while (atomic_read(&inode->i_dio_count));
finish_wait(wq, &q.wq_entry);
}
/**
* inode_dio_wait - wait for outstanding DIO requests to finish
* @inode: inode to wait for
*
* Waits for all pending direct I/O requests to finish so that we can
* proceed with a truncate or equivalent operation.
*
* Must be called under a lock that serializes taking new references
* to i_dio_count, usually by inode->i_mutex.
*/
void inode_dio_wait(struct inode *inode)
{
if (atomic_read(&inode->i_dio_count))
__inode_dio_wait(inode);
}
EXPORT_SYMBOL(inode_dio_wait);
/*
* inode_set_flags - atomically set some inode flags
*
* Note: the caller should be holding i_mutex, or else be sure that
* they have exclusive access to the inode structure (i.e., while the
* inode is being instantiated). The reason for the cmpxchg() loop
* --- which wouldn't be necessary if all code paths which modify
* i_flags actually followed this rule, is that there is at least one
* code path which doesn't today so we use cmpxchg() out of an abundance
* of caution.
*
* In the long run, i_mutex is overkill, and we should probably look
* at using the i_lock spinlock to protect i_flags, and then make sure
* it is so documented in include/linux/fs.h and that all code follows
* the locking convention!!
*/
void inode_set_flags(struct inode *inode, unsigned int flags,
unsigned int mask)
{
unsigned int old_flags, new_flags;
WARN_ON_ONCE(flags & ~mask);
do {
old_flags = READ_ONCE(inode->i_flags);
new_flags = (old_flags & ~mask) | flags;
} while (unlikely(cmpxchg(&inode->i_flags, old_flags,
new_flags) != old_flags));
}
EXPORT_SYMBOL(inode_set_flags);
void inode_nohighmem(struct inode *inode)
{
mapping_set_gfp_mask(inode->i_mapping, GFP_USER);
}
EXPORT_SYMBOL(inode_nohighmem);
/**
* timespec64_trunc - Truncate timespec64 to a granularity
* @t: Timespec64
* @gran: Granularity in ns.
*
* Truncate a timespec64 to a granularity. Always rounds down. gran must
* not be 0 nor greater than a second (NSEC_PER_SEC, or 10^9 ns).
*/
struct timespec64 timespec64_trunc(struct timespec64 t, unsigned gran)
{
/* Avoid division in the common cases 1 ns and 1 s. */
if (gran == 1) {
/* nothing */
} else if (gran == NSEC_PER_SEC) {
t.tv_nsec = 0;
} else if (gran > 1 && gran < NSEC_PER_SEC) {
t.tv_nsec -= t.tv_nsec % gran;
} else {
WARN(1, "illegal file time granularity: %u", gran);
}
return t;
}
EXPORT_SYMBOL(timespec64_trunc);
/**
* current_time - Return FS time
* @inode: inode.
*
* Return the current time truncated to the time granularity supported by
* the fs.
*
* Note that inode and inode->sb cannot be NULL.
* Otherwise, the function warns and returns time without truncation.
*/
struct timespec64 current_time(struct inode *inode)
{
struct timespec64 now = current_kernel_time64();
if (unlikely(!inode->i_sb)) {
WARN(1, "current_time() called with uninitialized super_block in the inode");
return now;
}
return timespec64_trunc(now, inode->i_sb->s_time_gran);
}
EXPORT_SYMBOL(current_time);
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_221_0 |
crossvul-cpp_data_bad_3231_0 | /*
===========================================================================
Return to Castle Wolfenstein multiplayer GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (RTCW MP Source Code).
RTCW MP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW MP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW MP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
// console.c
#include "client.h"
int g_console_field_width = 78;
#define COLNSOLE_COLOR COLOR_WHITE //COLOR_BLACK
#define NUM_CON_TIMES 4
//#define CON_TEXTSIZE 32768
#define CON_TEXTSIZE 65536 // (SA) DM want's more console...
typedef struct {
qboolean initialized;
short text[CON_TEXTSIZE];
int current; // line where next message will be printed
int x; // offset in current line for next print
int display; // bottom of console displays this line
int linewidth; // characters across screen
int totallines; // total lines in console scrollback
float xadjust; // for wide aspect screens
float displayFrac; // aproaches finalFrac at scr_conspeed
float finalFrac; // 0.0 to 1.0 lines of console to display
int vislines; // in scanlines
int times[NUM_CON_TIMES]; // cls.realtime time the line was generated
// for transparent notify lines
vec4_t color;
} console_t;
console_t con;
cvar_t *con_debug;
cvar_t *con_conspeed;
cvar_t *con_notifytime;
// DHM - Nerve :: Must hold CTRL + SHIFT + ~ to get console
cvar_t *con_restricted;
#define DEFAULT_CONSOLE_WIDTH 78
/*
================
Con_ToggleConsole_f
================
*/
void Con_ToggleConsole_f( void ) {
// Can't toggle the console when it's the only thing available
if ( clc.state == CA_DISCONNECTED && Key_GetCatcher( ) == KEYCATCH_CONSOLE ) {
CL_StartDemoLoop();
return;
}
if ( con_restricted->integer && ( !keys[K_CTRL].down || !keys[K_SHIFT].down ) ) {
return;
}
Field_Clear( &g_consoleField );
g_consoleField.widthInChars = g_console_field_width;
Con_ClearNotify();
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_CONSOLE );
}
/*
===================
Con_ToggleMenu_f
===================
*/
void Con_ToggleMenu_f( void ) {
CL_KeyEvent( K_ESCAPE, qtrue, Sys_Milliseconds() );
CL_KeyEvent( K_ESCAPE, qfalse, Sys_Milliseconds() );
}
/*
================
Con_MessageMode_f
================
*/
void Con_MessageMode_f( void ) {
chat_playerNum = -1;
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode2_f
================
*/
void Con_MessageMode2_f( void ) {
chat_playerNum = -1;
chat_team = qtrue;
Field_Clear( &chatField );
chatField.widthInChars = 25;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode3_f
================
*/
void Con_MessageMode3_f( void ) {
chat_playerNum = VM_Call( cgvm, CG_CROSSHAIR_PLAYER );
if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) {
chat_playerNum = -1;
return;
}
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode4_f
================
*/
void Con_MessageMode4_f( void ) {
chat_playerNum = VM_Call( cgvm, CG_LAST_ATTACKER );
if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) {
chat_playerNum = -1;
return;
}
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
// NERVE - SMF
/*
================
Con_StartLimboMode_f
================
*/
void Con_StartLimboMode_f( void ) {
chat_limbo = qtrue;
}
/*
================
Con_StopLimboMode_f
================
*/
void Con_StopLimboMode_f( void ) {
chat_limbo = qfalse;
}
// -NERVE - SMF
/*
================
Con_Clear_f
================
*/
void Con_Clear_f( void ) {
int i;
for ( i = 0 ; i < CON_TEXTSIZE ; i++ ) {
con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
}
Con_Bottom(); // go to end
}
/*
================
Con_Dump_f
Save the console contents out to a file
================
*/
void Con_Dump_f( void ) {
int l, x, i;
short *line;
fileHandle_t f;
int bufferlen;
char *buffer;
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: condump <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".txt" );
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf ("ERROR: couldn't open %s.\n", filename);
return;
}
Com_Printf ("Dumped console text to %s.\n", filename );
// skip empty lines
for ( l = con.current - con.totallines + 1 ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( x = 0 ; x < con.linewidth ; x++ )
if ( ( line[x] & 0xff ) != ' ' ) {
break;
}
if ( x != con.linewidth ) {
break;
}
}
#ifdef _WIN32
bufferlen = con.linewidth + 3 * sizeof ( char );
#else
bufferlen = con.linewidth + 2 * sizeof ( char );
#endif
buffer = Hunk_AllocateTempMemory( bufferlen );
// write the remaining lines
buffer[bufferlen-1] = 0;
for ( ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( i = 0; i < con.linewidth; i++ )
buffer[i] = line[i] & 0xff;
for ( x = con.linewidth - 1 ; x >= 0 ; x-- )
{
if ( buffer[x] == ' ' ) {
buffer[x] = 0;
} else {
break;
}
}
#ifdef _WIN32
Q_strcat(buffer, bufferlen, "\r\n");
#else
Q_strcat(buffer, bufferlen, "\n");
#endif
FS_Write( buffer, strlen( buffer ), f );
}
Hunk_FreeTempMemory( buffer );
FS_FCloseFile( f );
}
/*
================
Con_ClearNotify
================
*/
void Con_ClearNotify( void ) {
int i;
for ( i = 0 ; i < NUM_CON_TIMES ; i++ ) {
con.times[i] = 0;
}
}
/*
================
Con_CheckResize
If the line width has changed, reformat the buffer.
================
*/
void Con_CheckResize( void ) {
int i, j, width, oldwidth, oldtotallines, numlines, numchars;
short tbuf[CON_TEXTSIZE];
width = ( SCREEN_WIDTH / SMALLCHAR_WIDTH ) - 2;
if ( width == con.linewidth ) {
return;
}
if ( width < 1 ) { // video hasn't been initialized yet
width = DEFAULT_CONSOLE_WIDTH;
con.linewidth = width;
con.totallines = CON_TEXTSIZE / con.linewidth;
for ( i = 0; i < CON_TEXTSIZE; i++ )
con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
} else
{
oldwidth = con.linewidth;
con.linewidth = width;
oldtotallines = con.totallines;
con.totallines = CON_TEXTSIZE / con.linewidth;
numlines = oldtotallines;
if ( con.totallines < numlines ) {
numlines = con.totallines;
}
numchars = oldwidth;
if ( con.linewidth < numchars ) {
numchars = con.linewidth;
}
memcpy( tbuf, con.text, CON_TEXTSIZE * sizeof( short ) );
for ( i = 0; i < CON_TEXTSIZE; i++ )
con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
for ( i = 0 ; i < numlines ; i++ )
{
for ( j = 0 ; j < numchars ; j++ )
{
con.text[( con.totallines - 1 - i ) * con.linewidth + j] =
tbuf[( ( con.current - i + oldtotallines ) %
oldtotallines ) * oldwidth + j];
}
}
Con_ClearNotify();
}
con.current = con.totallines - 1;
con.display = con.current;
}
/*
==================
Cmd_CompleteTxtName
==================
*/
void Cmd_CompleteTxtName( char *args, int argNum ) {
if( argNum == 2 ) {
Field_CompleteFilename( "", "txt", qfalse, qtrue );
}
}
/*
================
Con_Init
================
*/
void Con_Init( void ) {
int i;
con_notifytime = Cvar_Get( "con_notifytime", "7", 0 ); // JPW NERVE increased per id req for obits
con_conspeed = Cvar_Get( "scr_conspeed", "3", 0 );
con_debug = Cvar_Get( "con_debug", "0", CVAR_ARCHIVE ); //----(SA) added
con_restricted = Cvar_Get( "con_restricted", "0", CVAR_INIT ); // DHM - Nerve
Field_Clear( &g_consoleField );
g_consoleField.widthInChars = g_console_field_width;
for ( i = 0 ; i < COMMAND_HISTORY ; i++ ) {
Field_Clear( &historyEditLines[i] );
historyEditLines[i].widthInChars = g_console_field_width;
}
CL_LoadConsoleHistory( );
Cmd_AddCommand( "toggleconsole", Con_ToggleConsole_f );
Cmd_AddCommand ("togglemenu", Con_ToggleMenu_f);
Cmd_AddCommand( "messagemode", Con_MessageMode_f );
Cmd_AddCommand( "messagemode2", Con_MessageMode2_f );
Cmd_AddCommand( "messagemode3", Con_MessageMode3_f );
Cmd_AddCommand( "messagemode4", Con_MessageMode4_f );
Cmd_AddCommand( "startLimboMode", Con_StartLimboMode_f ); // NERVE - SMF
Cmd_AddCommand( "stopLimboMode", Con_StopLimboMode_f ); // NERVE - SMF
Cmd_AddCommand( "clear", Con_Clear_f );
Cmd_AddCommand( "condump", Con_Dump_f );
Cmd_SetCommandCompletionFunc( "condump", Cmd_CompleteTxtName );
}
/*
================
Con_Shutdown
================
*/
void Con_Shutdown(void)
{
Cmd_RemoveCommand("toggleconsole");
Cmd_RemoveCommand("togglemenu");
Cmd_RemoveCommand("messagemode");
Cmd_RemoveCommand("messagemode2");
Cmd_RemoveCommand("messagemode3");
Cmd_RemoveCommand("messagemode4");
Cmd_RemoveCommand("startLimboMode");
Cmd_RemoveCommand("stopLimboMode");
Cmd_RemoveCommand("clear");
Cmd_RemoveCommand("condump");
}
/*
===============
Con_Linefeed
===============
*/
void Con_Linefeed( qboolean skipnotify ) {
int i;
// mark time for transparent overlay
if ( con.current >= 0 ) {
if ( skipnotify ) {
con.times[con.current % NUM_CON_TIMES] = 0;
} else {
con.times[con.current % NUM_CON_TIMES] = cls.realtime;
}
}
con.x = 0;
if ( con.display == con.current ) {
con.display++;
}
con.current++;
for ( i = 0; i < con.linewidth; i++ )
con.text[( con.current % con.totallines ) * con.linewidth + i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
}
/*
================
CL_ConsolePrint
Handles cursor positioning, line wrapping, etc
All console printing must go through this in order to be logged to disk
If no console is visible, the text will appear at the top of the game window
================
*/
void CL_ConsolePrint( char *txt ) {
int y, l;
unsigned char c;
unsigned short color;
qboolean skipnotify = qfalse; // NERVE - SMF
int prev; // NERVE - SMF
// NERVE - SMF - work around for text that shows up in console but not in notify
if ( !Q_strncmp( txt, "[skipnotify]", 12 ) ) {
skipnotify = qtrue;
txt += 12;
}
// for some demos we don't want to ever show anything on the console
if ( cl_noprint && cl_noprint->integer ) {
return;
}
if ( !con.initialized ) {
con.color[0] =
con.color[1] =
con.color[2] =
con.color[3] = 1.0f;
con.linewidth = -1;
Con_CheckResize();
con.initialized = qtrue;
}
color = ColorIndex( COLNSOLE_COLOR );
while ( (c = *((unsigned char *) txt)) != 0 ) {
if ( Q_IsColorString( txt ) ) {
color = ColorIndex( *( txt + 1 ) );
txt += 2;
continue;
}
// count word length
for ( l = 0 ; l < con.linewidth ; l++ ) {
if ( txt[l] <= ' ' ) {
break;
}
}
// word wrap
if ( l != con.linewidth && ( con.x + l >= con.linewidth ) ) {
Con_Linefeed( skipnotify );
}
txt++;
switch ( c )
{
case '\n':
Con_Linefeed( skipnotify );
break;
case '\r':
con.x = 0;
break;
default: // display character and advance
y = con.current % con.totallines;
con.text[y * con.linewidth + con.x] = ( color << 8 ) | c;
con.x++;
if(con.x >= con.linewidth)
Con_Linefeed( skipnotify );
break;
}
}
// mark time for transparent overlay
if ( con.current >= 0 ) {
// NERVE - SMF
if ( skipnotify ) {
prev = con.current % NUM_CON_TIMES - 1;
if ( prev < 0 ) {
prev = NUM_CON_TIMES - 1;
}
con.times[prev] = 0;
} else {
// -NERVE - SMF
con.times[con.current % NUM_CON_TIMES] = cls.realtime;
}
}
}
/*
==============================================================================
DRAWING
==============================================================================
*/
/*
================
Con_DrawInput
Draw the editline after a ] prompt
================
*/
void Con_DrawInput( void ) {
int y;
if ( clc.state != CA_DISCONNECTED && !(Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ) {
return;
}
y = con.vislines - ( SMALLCHAR_HEIGHT * 2 );
re.SetColor( con.color );
SCR_DrawSmallChar( con.xadjust + 1 * SMALLCHAR_WIDTH, y, ']' );
Field_Draw( &g_consoleField, con.xadjust + 2 * SMALLCHAR_WIDTH, y,
SCREEN_WIDTH - 3 * SMALLCHAR_WIDTH, qtrue, qtrue );
}
/*
================
Con_DrawNotify
Draws the last few lines of output transparently over the game top
================
*/
void Con_DrawNotify( void ) {
int x, v;
short *text;
int i;
int time;
int skip;
int currentColor;
// NERVE - SMF - we dont want draw notify in limbo mode
if ( Cvar_VariableIntegerValue( "ui_limboMode" ) ) {
return;
}
currentColor = 7;
re.SetColor( g_color_table[currentColor] );
v = 0;
for ( i = con.current - NUM_CON_TIMES + 1 ; i <= con.current ; i++ )
{
if ( i < 0 ) {
continue;
}
time = con.times[i % NUM_CON_TIMES];
if ( time == 0 ) {
continue;
}
time = cls.realtime - time;
if ( time > con_notifytime->value * 1000 ) {
continue;
}
text = con.text + ( i % con.totallines ) * con.linewidth;
if (cl.snap.ps.pm_type != PM_INTERMISSION && Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME) ) {
continue;
}
for ( x = 0 ; x < con.linewidth ; x++ ) {
if ( ( text[x] & 0xff ) == ' ' ) {
continue;
}
if ( ColorIndexForNumber( text[x] >> 8 ) != currentColor ) {
currentColor = ColorIndexForNumber( text[x] >> 8 );
re.SetColor( g_color_table[currentColor] );
}
SCR_DrawSmallChar( cl_conXOffset->integer + con.xadjust + ( x + 1 ) * SMALLCHAR_WIDTH, v, text[x] & 0xff );
}
v += SMALLCHAR_HEIGHT;
}
re.SetColor( NULL );
if (Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME) ) {
return;
}
// draw the chat line
if ( Key_GetCatcher( ) & KEYCATCH_MESSAGE ) {
if ( chat_team ) {
char buf[128];
CL_TranslateString( "say_team:", buf );
SCR_DrawBigString( 8, v, buf, 1.0f, qfalse );
skip = strlen( buf ) + 2;
} else
{
char buf[128];
CL_TranslateString( "say:", buf );
SCR_DrawBigString( 8, v, buf, 1.0f, qfalse );
skip = strlen( buf ) + 1;
}
Field_BigDraw( &chatField, skip * BIGCHAR_WIDTH, v, SCREEN_WIDTH - ( skip + 1 ) * BIGCHAR_WIDTH, qtrue, qtrue );
}
}
/*
================
Con_DrawSolidConsole
Draws the console with the solid background
================
*/
void Con_DrawSolidConsole( float frac ) {
int i, x, y;
int rows;
short *text;
int row;
int lines;
int currentColor;
vec4_t color;
lines = cls.glconfig.vidHeight * frac;
if ( lines <= 0 ) {
return;
}
if ( lines > cls.glconfig.vidHeight ) {
lines = cls.glconfig.vidHeight;
}
// on wide screens, we will center the text
con.xadjust = 0;
SCR_AdjustFrom640( &con.xadjust, NULL, NULL, NULL );
// draw the background
y = frac * SCREEN_HEIGHT;
if ( y < 1 ) {
y = 0;
} else {
SCR_DrawPic( 0, 0, SCREEN_WIDTH, y, cls.consoleShader );
if ( frac >= 0.5f ) {
color[0] = color[1] = color[2] = frac * 2.0f;
color[3] = 1.0f;
re.SetColor( color );
// draw the logo
SCR_DrawPic( 192, 70, 256, 128, cls.consoleShader2 );
re.SetColor( NULL );
}
}
color[0] = 0;
color[1] = 0;
color[2] = 0;
color[3] = 0.6f;
SCR_FillRect( 0, y, SCREEN_WIDTH, 2, color );
// draw the version number
re.SetColor( g_color_table[ColorIndex( COLNSOLE_COLOR )] );
i = strlen( Q3_VERSION );
for ( x = 0 ; x < i ; x++ ) {
SCR_DrawSmallChar( cls.glconfig.vidWidth - ( i - x + 1 ) * SMALLCHAR_WIDTH, lines - SMALLCHAR_HEIGHT, Q3_VERSION[x] );
}
// draw the text
con.vislines = lines;
rows = ( lines - SMALLCHAR_HEIGHT ) / SMALLCHAR_HEIGHT; // rows of text to draw
y = lines - ( SMALLCHAR_HEIGHT * 3 );
// draw from the bottom up
if ( con.display != con.current ) {
// draw arrows to show the buffer is backscrolled
re.SetColor( g_color_table[ColorIndex( COLOR_WHITE )] );
for ( x = 0 ; x < con.linewidth ; x += 4 )
SCR_DrawSmallChar( con.xadjust + ( x + 1 ) * SMALLCHAR_WIDTH, y, '^' );
y -= SMALLCHAR_HEIGHT;
rows--;
}
row = con.display;
if ( con.x == 0 ) {
row--;
}
currentColor = 7;
re.SetColor( g_color_table[currentColor] );
for ( i = 0 ; i < rows ; i++, y -= SMALLCHAR_HEIGHT, row-- )
{
if ( row < 0 ) {
break;
}
if ( con.current - row >= con.totallines ) {
// past scrollback wrap point
continue;
}
text = con.text + ( row % con.totallines ) * con.linewidth;
for ( x = 0 ; x < con.linewidth ; x++ ) {
if ( ( text[x] & 0xff ) == ' ' ) {
continue;
}
if ( ColorIndexForNumber( text[x] >> 8 ) != currentColor ) {
currentColor = ColorIndexForNumber( text[x] >> 8 );
re.SetColor( g_color_table[currentColor] );
}
SCR_DrawSmallChar( con.xadjust + ( x + 1 ) * SMALLCHAR_WIDTH, y, text[x] & 0xff );
}
}
// draw the input prompt, user text, and cursor if desired
Con_DrawInput();
re.SetColor( NULL );
}
/*
==================
Con_DrawConsole
==================
*/
void Con_DrawConsole( void ) {
// check for console width changes from a vid mode change
Con_CheckResize();
// if disconnected, render console full screen
if ( clc.state == CA_DISCONNECTED ) {
if ( !( Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME)) ) {
Con_DrawSolidConsole( 1.0 );
return;
}
}
if ( con.displayFrac ) {
Con_DrawSolidConsole( con.displayFrac );
} else {
// draw notify lines
if ( clc.state == CA_ACTIVE ) {
Con_DrawNotify();
}
}
}
//================================================================
/*
==================
Con_RunConsole
Scroll it up or down
==================
*/
void Con_RunConsole( void ) {
// decide on the destination height of the console
if ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) {
con.finalFrac = 0.5; // half screen
} else {
con.finalFrac = 0; // none visible
}
// scroll towards the destination height
if ( con.finalFrac < con.displayFrac ) {
con.displayFrac -= con_conspeed->value * cls.realFrametime * 0.001;
if ( con.finalFrac > con.displayFrac ) {
con.displayFrac = con.finalFrac;
}
} else if ( con.finalFrac > con.displayFrac ) {
con.displayFrac += con_conspeed->value * cls.realFrametime * 0.001;
if ( con.finalFrac < con.displayFrac ) {
con.displayFrac = con.finalFrac;
}
}
}
void Con_PageUp( void ) {
con.display -= 2;
if ( con.current - con.display >= con.totallines ) {
con.display = con.current - con.totallines + 1;
}
}
void Con_PageDown( void ) {
con.display += 2;
if ( con.display > con.current ) {
con.display = con.current;
}
}
void Con_Top( void ) {
con.display = con.totallines;
if ( con.current - con.display >= con.totallines ) {
con.display = con.current - con.totallines + 1;
}
}
void Con_Bottom( void ) {
con.display = con.current;
}
void Con_Close( void ) {
if ( !com_cl_running->integer ) {
return;
}
Field_Clear( &g_consoleField );
Con_ClearNotify();
Key_SetCatcher( Key_GetCatcher( ) & ~KEYCATCH_CONSOLE );
con.finalFrac = 0; // none visible
con.displayFrac = 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3231_0 |
crossvul-cpp_data_good_3151_1 | /*
* Copyright (C) 2014-2016 Firejail Authors
*
* This file is part of firejail 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "firejail.h"
#include <sys/mount.h>
#include <linux/limits.h>
#include <glob.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <grp.h>
static void skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
// zsh
if (arg_zsh) {
// copy skel files
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat
fprintf(stderr, "Error: invalid %s file\n", fname);
exit(1);
}
if (stat("/etc/skel/.zshrc", &s) == 0) {
copy_file_as_user("/etc/skel/.zshrc", fname, u, g, 0644); // regular user
fs_logger("clone /etc/skel/.zshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
// csh
else if (arg_csh) {
// copy skel files
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat
fprintf(stderr, "Error: invalid %s file\n", fname);
exit(1);
}
if (stat("/etc/skel/.cshrc", &s) == 0) {
copy_file_as_user("/etc/skel/.cshrc", fname, u, g, 0644); // regular user
fs_logger("clone /etc/skel/.cshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
// bash etc.
else {
// copy skel files
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat
fprintf(stderr, "Error: invalid %s file\n", fname);
exit(1);
}
if (stat("/etc/skel/.bashrc", &s) == 0) {
copy_file_as_user("/etc/skel/.bashrc", fname, u, g, 0644); // regular user
fs_logger("clone /etc/skel/.bashrc");
}
free(fname);
}
}
static int store_xauthority(void) {
// put a copy of .Xauthority in XAUTHORITY_FILE
fs_build_mnt_dir();
char *src;
char *dest = RUN_XAUTHORITY_FILE;
// create an empty file as root, and change ownership to user
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0600);
fclose(fp);
}
if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Warning: invalid .Xauthority file\n");
return 0;
}
copy_file_as_user(src, dest, getuid(), getgid(), 0600); // regular user
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
static int store_asoundrc(void) {
// put a copy of .Xauthority in XAUTHORITY_FILE
fs_build_mnt_dir();
char *src;
char *dest = RUN_ASOUNDRC_FILE;
// create an empty file as root, and change ownership to user
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0644);
fclose(fp);
}
if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
// make sure the real path of the file is inside the home directory
/* coverity[toctou] */
char* rp = realpath(src, NULL);
if (!rp) {
fprintf(stderr, "Error: Cannot access %s\n", src);
exit(1);
}
if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n");
exit(1);
}
free(rp);
}
copy_file_as_user(src, dest, getuid(), getgid(), 0644); // regular user
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
static void copy_xauthority(void) {
// copy XAUTHORITY_FILE in the new home directory
char *src = RUN_XAUTHORITY_FILE ;
char *dest;
if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
// if destination is a symbolic link, exit the sandbox!!!
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); // regular user
fs_logger2("clone", dest);
// delete the temporary file
unlink(src);
}
static void copy_asoundrc(void) {
// copy XAUTHORITY_FILE in the new home directory
char *src = RUN_ASOUNDRC_FILE ;
char *dest;
if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
// if destination is a symbolic link, exit the sandbox!!!
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); // regular user
fs_logger2("clone", dest);
// delete the temporary file
unlink(src);
}
// private mode (--private=homedir):
// mount homedir on top of /home/user,
// tmpfs on top of /root in nonroot mode,
// set skel files,
// restore .Xauthority
void fs_private_homedir(void) {
char *homedir = cfg.homedir;
char *private_homedir = cfg.home_private;
assert(homedir);
assert(private_homedir);
int xflag = store_xauthority();
int aflag = store_asoundrc();
uid_t u = getuid();
gid_t g = getgid();
struct stat s;
if (stat(homedir, &s) == -1) {
fprintf(stderr, "Error: cannot find user home directory\n");
exit(1);
}
// mount bind private_homedir on top of homedir
if (arg_debug)
printf("Mount-bind %s on top of %s\n", private_homedir, homedir);
if (mount(private_homedir, homedir, NULL, MS_BIND|MS_REC, NULL) < 0)
errExit("mount bind");
fs_logger3("mount-bind", private_homedir, cfg.homedir);
// preserve mode and ownership
// if (chown(homedir, s.st_uid, s.st_gid) == -1)
// errExit("mount-bind chown");
// if (chmod(homedir, s.st_mode) == -1)
// errExit("mount-bind chmod");
if (u != 0) {
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting home directory");
fs_logger("mount tmpfs on /root");
}
else {
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
fs_logger("mount tmpfs on /home");
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
// private mode (--private):
// mount tmpfs over /home/user,
// tmpfs on top of /root in nonroot mode,
// set skel files,
// restore .Xauthority
void fs_private(void) {
char *homedir = cfg.homedir;
assert(homedir);
uid_t u = getuid();
gid_t g = getgid();
int xflag = store_xauthority();
int aflag = store_asoundrc();
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
fs_logger("mount tmpfs on /home");
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting root directory");
fs_logger("mount tmpfs on /root");
if (u != 0) {
// create /home/user
if (arg_debug)
printf("Create a new user directory\n");
if (mkdir(homedir, S_IRWXU) == -1) {
if (mkpath_as_root(homedir) == -1)
errExit("mkpath");
if (mkdir(homedir, S_IRWXU) == -1)
errExit("mkdir");
}
if (chown(homedir, u, g) < 0)
errExit("chown");
fs_logger2("mkdir", homedir);
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
// check new private home directory (--private= option) - exit if it fails
void fs_check_private_dir(void) {
invalid_filename(cfg.home_private);
// Expand the home directory
char *tmp = expand_home(cfg.home_private, cfg.homedir);
cfg.home_private = realpath(tmp, NULL);
free(tmp);
if (!cfg.home_private
|| !is_dir(cfg.home_private)
|| is_link(cfg.home_private)
|| strstr(cfg.home_private, "..")) {
fprintf(stderr, "Error: invalid private directory\n");
exit(1);
}
// check home directory and chroot home directory have the same owner
struct stat s2;
int rv = stat(cfg.home_private, &s2);
if (rv < 0) {
fprintf(stderr, "Error: cannot find %s directory\n", cfg.home_private);
exit(1);
}
struct stat s1;
rv = stat(cfg.homedir, &s1);
if (rv < 0) {
fprintf(stderr, "Error: cannot find %s directory, full path name required\n", cfg.homedir);
exit(1);
}
if (s1.st_uid != s2.st_uid) {
printf("Error: --private directory should be owned by the current user\n");
exit(1);
}
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3151_1 |
crossvul-cpp_data_good_3231_3 | /*
===========================================================================
Return to Castle Wolfenstein single player GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein single player GPL Source Code (RTCW SP Source Code).
RTCW SP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW SP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
// common.c -- misc functions used in client and server
#include "q_shared.h"
#include "qcommon.h"
#include <setjmp.h>
#ifndef _WIN32
#include <netinet/in.h>
#include <sys/stat.h> // umask
#else
#include <winsock.h>
#endif
int demo_protocols[] =
{ 59, 58, 57, 0 };
#define MAXPRINTMSG 4096
#define MAX_NUM_ARGVS 50
#define MIN_DEDICATED_COMHUNKMEGS 1
#define MIN_COMHUNKMEGS 128
#define DEF_COMHUNKMEGS 256
#define DEF_COMZONEMEGS 32
#define DEF_COMHUNKMEGS_S XSTRING(DEF_COMHUNKMEGS)
#define DEF_COMZONEMEGS_S XSTRING(DEF_COMZONEMEGS)
int com_argc;
char *com_argv[MAX_NUM_ARGVS + 1];
jmp_buf abortframe; // an ERR_DROP occured, exit the entire frame
FILE *debuglogfile;
static fileHandle_t pipefile;
static fileHandle_t logfile;
fileHandle_t com_journalFile; // events are written here
fileHandle_t com_journalDataFile; // config files are written here
cvar_t *com_speeds;
cvar_t *com_developer;
cvar_t *com_dedicated;
cvar_t *com_timescale;
cvar_t *com_fixedtime;
cvar_t *com_journal;
cvar_t *com_maxfps;
cvar_t *com_altivec;
cvar_t *com_timedemo;
cvar_t *com_sv_running;
cvar_t *com_cl_running;
cvar_t *com_logfile; // 1 = buffer log, 2 = flush after each print
cvar_t *com_pipefile;
cvar_t *com_showtrace;
cvar_t *com_version;
cvar_t *com_blood;
cvar_t *com_buildScript; // for automated data building scripts
#ifdef CINEMATICS_INTRO
cvar_t *com_introPlayed;
#endif
cvar_t *cl_paused;
cvar_t *sv_paused;
cvar_t *cl_packetdelay;
cvar_t *sv_packetdelay;
cvar_t *com_cameraMode;
cvar_t *com_recommendedSet;
cvar_t *com_ansiColor;
cvar_t *com_unfocused;
cvar_t *com_maxfpsUnfocused;
cvar_t *com_minimized;
cvar_t *com_maxfpsMinimized;
cvar_t *com_abnormalExit;
cvar_t *com_standalone;
cvar_t *com_gamename;
cvar_t *com_protocol;
#ifdef LEGACY_PROTOCOL
cvar_t *com_legacyprotocol;
#endif
cvar_t *com_basegame;
cvar_t *com_homepath;
cvar_t *com_busyWait;
#if idx64
int (*Q_VMftol)(void);
#elif id386
long (QDECL *Q_ftol)(float f);
int (QDECL *Q_VMftol)(void);
void (QDECL *Q_SnapVector)(vec3_t vec);
#endif
// Rafael Notebook
cvar_t *cl_notebook;
cvar_t *com_hunkused; // Ridah
// com_speeds times
int time_game;
int time_frontend; // renderer frontend time
int time_backend; // renderer backend time
int com_frameTime;
int com_frameNumber;
qboolean com_errorEntered = qfalse;
qboolean com_fullyInitialized = qfalse;
qboolean com_gameRestarting = qfalse;
qboolean com_gameClientRestarting = qfalse;
char com_errorMessage[MAXPRINTMSG];
void Com_WriteConfig_f( void );
void CIN_CloseAllVideos( void );
//============================================================================
static char *rd_buffer;
static int rd_buffersize;
static void ( *rd_flush )( char *buffer );
void Com_BeginRedirect( char *buffer, int buffersize, void ( *flush )( char *) ) {
if ( !buffer || !buffersize || !flush ) {
return;
}
rd_buffer = buffer;
rd_buffersize = buffersize;
rd_flush = flush;
*rd_buffer = 0;
}
void Com_EndRedirect( void ) {
if ( rd_flush ) {
rd_flush( rd_buffer );
}
rd_buffer = NULL;
rd_buffersize = 0;
rd_flush = NULL;
}
/*
=============
Com_Printf
Both client and server can use this, and it will output
to the apropriate place.
A raw string should NEVER be passed as fmt, because of "%f" type crashers.
=============
*/
void QDECL Com_Printf( const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
static qboolean opening_qconsole = qfalse;
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof (msg), fmt, argptr );
va_end( argptr );
if ( rd_buffer ) {
if ( ( strlen( msg ) + strlen( rd_buffer ) ) > ( rd_buffersize - 1 ) ) {
rd_flush( rd_buffer );
*rd_buffer = 0;
}
Q_strcat( rd_buffer, rd_buffersize, msg );
// show_bug.cgi?id=51
// only flush the rcon buffer when it's necessary, avoid fragmenting
//rd_flush(rd_buffer);
//*rd_buffer = 0;
return;
}
#ifndef DEDICATED
CL_ConsolePrint( msg );
#endif
// echo to dedicated console and early console
Sys_Print( msg );
// logfile
if ( com_logfile && com_logfile->integer ) {
// TTimo: only open the qconsole.log if the filesystem is in an initialized state
// also, avoid recursing in the qconsole.log opening (i.e. if fs_debug is on)
if ( !logfile && FS_Initialized() && !opening_qconsole ) {
struct tm *newtime;
time_t aclock;
opening_qconsole = qtrue;
time( &aclock );
newtime = localtime( &aclock );
logfile = FS_FOpenFileWrite( "rtcwconsole.log" ); //----(SA) changed name for Wolf
if(logfile)
{
Com_Printf( "logfile opened on %s\n", asctime( newtime ) );
if ( com_logfile->integer > 1 )
{
// force it to not buffer so we get valid
// data even if we are crashing
FS_ForceFlush(logfile);
}
}
else
{
Com_Printf("Opening rtcwconsole.log failed!\n");
Cvar_SetValue("logfile", 0);
}
opening_qconsole = qfalse;
}
if ( logfile && FS_Initialized() ) {
FS_Write( msg, strlen( msg ), logfile );
}
}
}
/*
================
Com_DPrintf
A Com_Printf that only shows up if the "developer" cvar is set
================
*/
void QDECL Com_DPrintf( const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
if ( !com_developer || !com_developer->integer ) {
return; // don't confuse non-developers with techie stuff...
}
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof ( msg ), fmt, argptr );
va_end( argptr );
Com_Printf( "%s", msg );
}
/*
=============
Com_Error
Both client and server can use this, and it will
do the appropriate thing.
=============
*/
void QDECL Com_Error( int code, const char *fmt, ... ) {
va_list argptr;
static int lastErrorTime;
static int errorCount;
int currentTime;
qboolean restartClient;
if(com_errorEntered)
Sys_Error("recursive error after: %s", com_errorMessage);
com_errorEntered = qtrue;
Cvar_Set("com_errorCode", va("%i", code));
// when we are running automated scripts, make sure we
// know if anything failed
if ( com_buildScript && com_buildScript->integer ) {
// ERR_ENDGAME is not really an error, don't die if building a script
if ( code != ERR_ENDGAME ) {
code = ERR_FATAL;
}
}
// if we are getting a solid stream of ERR_DROP, do an ERR_FATAL
currentTime = Sys_Milliseconds();
if ( currentTime - lastErrorTime < 100 ) {
if ( ++errorCount > 3 ) {
code = ERR_FATAL;
}
} else {
errorCount = 0;
}
lastErrorTime = currentTime;
va_start( argptr,fmt );
Q_vsnprintf (com_errorMessage, sizeof(com_errorMessage),fmt,argptr);
va_end( argptr );
if ( code != ERR_DISCONNECT && code != ERR_NEED_CD && code != ERR_ENDGAME ) {
Cvar_Set( "com_errorMessage", com_errorMessage );
}
restartClient = com_gameClientRestarting && !( com_cl_running && com_cl_running->integer );
com_gameRestarting = qfalse;
com_gameClientRestarting = qfalse;
if (code == ERR_DISCONNECT || code == ERR_SERVERDISCONNECT) {
VM_Forced_Unload_Start();
SV_Shutdown( "Server disconnected" );
if ( restartClient ) {
CL_Init();
}
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
// make sure we can get at our local stuff
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else if ( code == ERR_ENDGAME ) { //----(SA) added
VM_Forced_Unload_Start();
SV_Shutdown( "endgame" );
if ( restartClient ) {
CL_Init();
}
if ( com_cl_running && com_cl_running->integer ) {
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
#ifndef DEDICATED
CL_EndgameMenu();
#endif
}
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else if (code == ERR_DROP) {
Com_Printf( "********************\nERROR: %s\n********************\n", com_errorMessage );
VM_Forced_Unload_Start();
SV_Shutdown (va("Server crashed: %s", com_errorMessage));
if ( restartClient ) {
CL_Init();
}
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else if ( code == ERR_NEED_CD ) {
VM_Forced_Unload_Start();
SV_Shutdown( "Server didn't have CD" );
if ( restartClient ) {
CL_Init();
}
if ( com_cl_running && com_cl_running->integer ) {
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
CL_CDDialog();
} else {
Com_Printf( "Server didn't have CD\n" );
VM_Forced_Unload_Done();
}
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else {
VM_Forced_Unload_Start();
CL_Shutdown(va("Client fatal crashed: %s", com_errorMessage), qtrue, qtrue);
SV_Shutdown(va("Server fatal crashed: %s", com_errorMessage));
VM_Forced_Unload_Done();
}
Com_Shutdown();
Sys_Error( "%s", com_errorMessage );
}
/*
=============
Com_Quit_f
Both client and server can use this, and it will
do the apropriate things.
=============
*/
void Com_Quit_f( void ) {
// don't try to shutdown if we are in a recursive error
char *p = Cmd_Args( );
if ( !com_errorEntered ) {
// Some VMs might execute "quit" command directly,
// which would trigger an unload of active VM error.
// Sys_Quit will kill this process anyways, so
// a corrupt call stack makes no difference
VM_Forced_Unload_Start();
SV_Shutdown(p[0] ? p : "Server quit");
CL_Shutdown(p[0] ? p : "Client quit", qtrue, qtrue);
VM_Forced_Unload_Done();
Com_Shutdown();
FS_Shutdown( qtrue );
}
Sys_Quit();
}
/*
============================================================================
COMMAND LINE FUNCTIONS
+ characters seperate the commandLine string into multiple console
command lines.
All of these are valid:
quake3 +set test blah +map test
quake3 set test blah+map test
quake3 set test blah + map test
============================================================================
*/
#define MAX_CONSOLE_LINES 32
int com_numConsoleLines;
char *com_consoleLines[MAX_CONSOLE_LINES];
/*
==================
Com_ParseCommandLine
Break it up into multiple console lines
==================
*/
void Com_ParseCommandLine( char *commandLine ) {
com_consoleLines[0] = commandLine;
com_numConsoleLines = 1;
while ( *commandLine ) {
// look for a + separating character
// if commandLine came from a file, we might have real line seperators
if ( *commandLine == '+' || *commandLine == '\n' ) {
if ( com_numConsoleLines == MAX_CONSOLE_LINES ) {
return;
}
com_consoleLines[com_numConsoleLines] = commandLine + 1;
com_numConsoleLines++;
*commandLine = 0;
}
commandLine++;
}
}
/*
===================
Com_SafeMode
Check for "safe" on the command line, which will
skip loading of wolfconfig.cfg
===================
*/
qboolean Com_SafeMode( void ) {
int i;
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
Cmd_TokenizeString( com_consoleLines[i] );
if ( !Q_stricmp( Cmd_Argv( 0 ), "safe" )
|| !Q_stricmp( Cmd_Argv( 0 ), "cvar_restart" ) ) {
com_consoleLines[i][0] = 0;
return qtrue;
}
}
return qfalse;
}
/*
===============
Com_StartupVariable
Searches for command line parameters that are set commands.
If match is not NULL, only that cvar will be looked for.
That is necessary because cddir and basedir need to be set
before the filesystem is started, but all other sets should
be after execing the config and default.
===============
*/
void Com_StartupVariable( const char *match ) {
int i;
char *s;
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
Cmd_TokenizeString( com_consoleLines[i] );
if ( strcmp( Cmd_Argv( 0 ), "set" ) ) {
continue;
}
s = Cmd_Argv( 1 );
if(!match || !strcmp(s, match))
{
if(Cvar_Flags(s) == CVAR_NONEXISTENT)
Cvar_Get(s, Cmd_ArgsFrom(2), CVAR_USER_CREATED);
else
Cvar_Set2(s, Cmd_ArgsFrom(2), qfalse);
}
}
}
/*
=================
Com_AddStartupCommands
Adds command line parameters as script statements
Commands are seperated by + signs
Returns qtrue if any late commands were added, which
will keep the demoloop from immediately starting
=================
*/
qboolean Com_AddStartupCommands( void ) {
int i;
qboolean added;
added = qfalse;
// quote every token, so args with semicolons can work
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
if ( !com_consoleLines[i] || !com_consoleLines[i][0] ) {
continue;
}
// set commands already added with Com_StartupVariable
if ( !Q_stricmpn( com_consoleLines[i], "set ", 4 ) ) {
continue;
}
added = qtrue;
Cbuf_AddText( com_consoleLines[i] );
Cbuf_AddText( "\n" );
}
return added;
}
//============================================================================
void Info_Print( const char *s ) {
char key[BIG_INFO_KEY];
char value[BIG_INFO_VALUE];
char *o;
int l;
if ( *s == '\\' ) {
s++;
}
while ( *s )
{
o = key;
while ( *s && *s != '\\' )
*o++ = *s++;
l = o - key;
if ( l < 20 ) {
memset( o, ' ', 20 - l );
key[20] = 0;
} else {
*o = 0;
}
Com_Printf( "%s ", key );
if ( !*s ) {
Com_Printf( "MISSING VALUE\n" );
return;
}
o = value;
s++;
while ( *s && *s != '\\' )
*o++ = *s++;
*o = 0;
if ( *s ) {
s++;
}
Com_Printf( "%s\n", value );
}
}
/*
============
Com_StringContains
============
*/
char *Com_StringContains( char *str1, char *str2, int casesensitive ) {
int len, i, j;
len = strlen( str1 ) - strlen( str2 );
for ( i = 0; i <= len; i++, str1++ ) {
for ( j = 0; str2[j]; j++ ) {
if ( casesensitive ) {
if ( str1[j] != str2[j] ) {
break;
}
} else {
if ( toupper( str1[j] ) != toupper( str2[j] ) ) {
break;
}
}
}
if ( !str2[j] ) {
return str1;
}
}
return NULL;
}
/*
============
Com_Filter
============
*/
int Com_Filter( char *filter, char *name, int casesensitive ) {
char buf[MAX_TOKEN_CHARS];
char *ptr;
int i, found;
while ( *filter ) {
if ( *filter == '*' ) {
filter++;
for ( i = 0; *filter; i++ ) {
if ( *filter == '*' || *filter == '?' ) {
break;
}
buf[i] = *filter;
filter++;
}
buf[i] = '\0';
if ( strlen( buf ) ) {
ptr = Com_StringContains( name, buf, casesensitive );
if ( !ptr ) {
return qfalse;
}
name = ptr + strlen( buf );
}
} else if ( *filter == '?' ) {
filter++;
name++;
} else if ( *filter == '[' && *( filter + 1 ) == '[' ) {
filter++;
} else if ( *filter == '[' ) {
filter++;
found = qfalse;
while ( *filter && !found ) {
if ( *filter == ']' && *( filter + 1 ) != ']' ) {
break;
}
if ( *( filter + 1 ) == '-' && *( filter + 2 ) && ( *( filter + 2 ) != ']' || *( filter + 3 ) == ']' ) ) {
if ( casesensitive ) {
if ( *name >= *filter && *name <= *( filter + 2 ) ) {
found = qtrue;
}
} else {
if ( toupper( *name ) >= toupper( *filter ) &&
toupper( *name ) <= toupper( *( filter + 2 ) ) ) {
found = qtrue;
}
}
filter += 3;
} else {
if ( casesensitive ) {
if ( *filter == *name ) {
found = qtrue;
}
} else {
if ( toupper( *filter ) == toupper( *name ) ) {
found = qtrue;
}
}
filter++;
}
}
if ( !found ) {
return qfalse;
}
while ( *filter ) {
if ( *filter == ']' && *( filter + 1 ) != ']' ) {
break;
}
filter++;
}
filter++;
name++;
} else {
if ( casesensitive ) {
if ( *filter != *name ) {
return qfalse;
}
} else {
if ( toupper( *filter ) != toupper( *name ) ) {
return qfalse;
}
}
filter++;
name++;
}
}
return qtrue;
}
/*
============
Com_FilterPath
============
*/
int Com_FilterPath( char *filter, char *name, int casesensitive ) {
int i;
char new_filter[MAX_QPATH];
char new_name[MAX_QPATH];
for ( i = 0; i < MAX_QPATH - 1 && filter[i]; i++ ) {
if ( filter[i] == '\\' || filter[i] == ':' ) {
new_filter[i] = '/';
} else {
new_filter[i] = filter[i];
}
}
new_filter[i] = '\0';
for ( i = 0; i < MAX_QPATH - 1 && name[i]; i++ ) {
if ( name[i] == '\\' || name[i] == ':' ) {
new_name[i] = '/';
} else {
new_name[i] = name[i];
}
}
new_name[i] = '\0';
return Com_Filter( new_filter, new_name, casesensitive );
}
/*
================
Com_RealTime
================
*/
int Com_RealTime( qtime_t *qtime ) {
time_t t;
struct tm *tms;
t = time( NULL );
if ( !qtime ) {
return t;
}
tms = localtime( &t );
if ( tms ) {
qtime->tm_sec = tms->tm_sec;
qtime->tm_min = tms->tm_min;
qtime->tm_hour = tms->tm_hour;
qtime->tm_mday = tms->tm_mday;
qtime->tm_mon = tms->tm_mon;
qtime->tm_year = tms->tm_year;
qtime->tm_wday = tms->tm_wday;
qtime->tm_yday = tms->tm_yday;
qtime->tm_isdst = tms->tm_isdst;
}
return t;
}
/*
==============================================================================
ZONE MEMORY ALLOCATION
==============================================================================
The old zone is gone, mallocs replaced it. To keep the widespread code changes down to a bare minimum
Z_Malloc and Z_Free still work.
*/
/*
========================
Z_Free
========================
*/
void Z_Free( void *ptr ) {
free( ptr );
}
/*
================
Z_Malloc
================
*/
void *Z_Malloc( int size ) {
void *buf = malloc( size );
Com_Memset( buf, 0, size );
return buf;
}
#if 0
/*
================
Z_TagMalloc
================
*/
void *Z_TagMalloc( int size, int tag ) {
if ( tag != TAG_RENDERER ) {
assert( 0 );
}
if ( g_numTaggedAllocs < MAX_TAG_ALLOCS ) {
void *ptr = Z_Malloc( size );
g_taggedAllocations[g_numTaggedAllocs++] = ptr;
return ptr;
} else {
Com_Error( ERR_FATAL, "Z_TagMalloc: out of tagged allocation space\n" );
}
return NULL;
}
/*
================
Z_FreeTags
================
*/
void Z_FreeTags( int tag ) {
int i;
if ( tag != TAG_RENDERER ) {
assert( 0 );
}
for ( i = 0; i < g_numTaggedAllocs; i++ ) {
free( g_taggedAllocations[i] );
}
g_numTaggedAllocs = 0;
}
#endif
/*
========================
CopyString
NOTE: never write over the memory CopyString returns because
memory from a memstatic_t might be returned
========================
*/
char *CopyString( const char *in ) {
char *out;
out = Z_Malloc( strlen( in ) + 1 );
strcpy( out, in );
return out;
}
/*
==============================================================================
Goals:
reproducable without history effects -- no out of memory errors on weird map to map changes
allow restarting of the client without fragmentation
minimize total pages in use at run time
minimize total pages needed during load time
Single block of memory with stack allocators coming from both ends towards the middle.
One side is designated the temporary memory allocator.
Temporary memory can be allocated and freed in any order.
A highwater mark is kept of the most in use at any time.
When there is no temporary memory allocated, the permanent and temp sides
can be switched, allowing the already touched temp memory to be used for
permanent storage.
Temp memory must never be allocated on two ends at once, or fragmentation
could occur.
If we have any in-use temp memory, additional temp allocations must come from
that side.
If not, we can choose to make either side the new temp side and push future
permanent allocations to the other side. Permanent allocations should be
kept on the side that has the current greatest wasted highwater mark.
==============================================================================
*/
#define HUNK_MAGIC 0x89537892
#define HUNK_FREE_MAGIC 0x89537893
typedef struct {
int magic;
int size;
} hunkHeader_t;
typedef struct {
int mark;
int permanent;
int temp;
int tempHighwater;
} hunkUsed_t;
typedef struct hunkblock_s {
int size;
byte printed;
struct hunkblock_s *next;
char *label;
char *file;
int line;
} hunkblock_t;
static hunkblock_t *hunkblocks;
static hunkUsed_t hunk_low, hunk_high;
static hunkUsed_t *hunk_permanent, *hunk_temp;
static byte *s_hunkData = NULL;
static int s_hunkTotal;
static int s_zoneTotal;
//static int s_smallZoneTotal; // TTimo: unused
/*
=================
Com_Meminfo_f
=================
*/
void Com_Meminfo_f( void ) {
int unused;
Com_Printf( "%8i bytes total hunk\n", s_hunkTotal );
Com_Printf( "%8i bytes total zone\n", s_zoneTotal );
Com_Printf( "\n" );
Com_Printf( "%8i low mark\n", hunk_low.mark );
Com_Printf( "%8i low permanent\n", hunk_low.permanent );
if ( hunk_low.temp != hunk_low.permanent ) {
Com_Printf( "%8i low temp\n", hunk_low.temp );
}
Com_Printf( "%8i low tempHighwater\n", hunk_low.tempHighwater );
Com_Printf( "\n" );
Com_Printf( "%8i high mark\n", hunk_high.mark );
Com_Printf( "%8i high permanent\n", hunk_high.permanent );
if ( hunk_high.temp != hunk_high.permanent ) {
Com_Printf( "%8i high temp\n", hunk_high.temp );
}
Com_Printf( "%8i high tempHighwater\n", hunk_high.tempHighwater );
Com_Printf( "\n" );
Com_Printf( "%8i total hunk in use\n", hunk_low.permanent + hunk_high.permanent );
unused = 0;
if ( hunk_low.tempHighwater > hunk_low.permanent ) {
unused += hunk_low.tempHighwater - hunk_low.permanent;
}
if ( hunk_high.tempHighwater > hunk_high.permanent ) {
unused += hunk_high.tempHighwater - hunk_high.permanent;
}
Com_Printf( "%8i unused highwater\n", unused );
Com_Printf( "\n" );
//Com_Printf( " %i number of tagged renderer allocations\n", g_numTaggedAllocs);
}
/*
===============
Com_TouchMemory
Touch all known used data to make sure it is paged in
===============
*/
void Com_TouchMemory( void ) {
int start, end;
int i, j;
int sum;
start = Sys_Milliseconds();
sum = 0;
j = hunk_low.permanent >> 2;
for ( i = 0 ; i < j ; i += 64 ) { // only need to touch each page
sum += ( (int *)s_hunkData )[i];
}
i = ( s_hunkTotal - hunk_high.permanent ) >> 2;
j = hunk_high.permanent >> 2;
for ( ; i < j ; i += 64 ) { // only need to touch each page
sum += ( (int *)s_hunkData )[i];
}
end = Sys_Milliseconds();
Com_Printf( "Com_TouchMemory: %i msec\n", end - start );
}
void Com_InitZoneMemory( void ) {
//memset(g_taggedAllocations, 0, sizeof(g_taggedAllocations));
//g_numTaggedAllocs = 0;
}
/*
=================
Hunk_Log
=================
*/
void Hunk_Log( void ) {
hunkblock_t *block;
char buf[4096];
int size, numBlocks;
if ( !logfile || !FS_Initialized() ) {
return;
}
size = 0;
numBlocks = 0;
Com_sprintf( buf, sizeof( buf ), "\r\n================\r\nHunk log\r\n================\r\n" );
FS_Write( buf, strlen( buf ), logfile );
for ( block = hunkblocks ; block; block = block->next ) {
#ifdef HUNK_DEBUG
Com_sprintf( buf, sizeof( buf ), "size = %8d: %s, line: %d (%s)\r\n", block->size, block->file, block->line, block->label );
FS_Write( buf, strlen( buf ), logfile );
#endif
size += block->size;
numBlocks++;
}
Com_sprintf( buf, sizeof( buf ), "%d Hunk memory\r\n", size );
FS_Write( buf, strlen( buf ), logfile );
Com_sprintf( buf, sizeof( buf ), "%d hunk blocks\r\n", numBlocks );
FS_Write( buf, strlen( buf ), logfile );
}
/*
=================
Hunk_SmallLog
=================
*/
void Hunk_SmallLog( void ) {
hunkblock_t *block, *block2;
char buf[4096];
int size, locsize, numBlocks;
if ( !logfile || !FS_Initialized() ) {
return;
}
for ( block = hunkblocks ; block; block = block->next ) {
block->printed = qfalse;
}
size = 0;
numBlocks = 0;
Com_sprintf( buf, sizeof( buf ), "\r\n================\r\nHunk Small log\r\n================\r\n" );
FS_Write( buf, strlen( buf ), logfile );
for ( block = hunkblocks; block; block = block->next ) {
if ( block->printed ) {
continue;
}
locsize = block->size;
for ( block2 = block->next; block2; block2 = block2->next ) {
if ( block->line != block2->line ) {
continue;
}
if ( Q_stricmp( block->file, block2->file ) ) {
continue;
}
size += block2->size;
locsize += block2->size;
block2->printed = qtrue;
}
#ifdef HUNK_DEBUG
Com_sprintf( buf, sizeof( buf ), "size = %8d: %s, line: %d (%s)\r\n", locsize, block->file, block->line, block->label );
FS_Write( buf, strlen( buf ), logfile );
#endif
size += block->size;
numBlocks++;
}
Com_sprintf( buf, sizeof( buf ), "%d Hunk memory\r\n", size );
FS_Write( buf, strlen( buf ), logfile );
Com_sprintf( buf, sizeof( buf ), "%d hunk blocks\r\n", numBlocks );
FS_Write( buf, strlen( buf ), logfile );
}
/*
=================
Com_InitHunkMemory
=================
*/
void Com_InitHunkMemory( void ) {
cvar_t *cv;
int nMinAlloc;
char *pMsg = NULL;
// make sure the file system has allocated and "not" freed any temp blocks
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( FS_LoadStack() != 0 ) {
Com_Error( ERR_FATAL, "Hunk initialization failed. File system load stack not zero" );
}
// allocate the stack based hunk allocator
cv = Cvar_Get( "com_hunkMegs", DEF_COMHUNKMEGS_S, CVAR_LATCH | CVAR_ARCHIVE );
// if we are not dedicated min allocation is 56, otherwise min is 1
if ( com_dedicated && com_dedicated->integer ) {
nMinAlloc = MIN_DEDICATED_COMHUNKMEGS;
pMsg = "Minimum com_hunkMegs for a dedicated server is %i, allocating %i megs.\n";
} else {
nMinAlloc = MIN_COMHUNKMEGS;
pMsg = "Minimum com_hunkMegs is %i, allocating %i megs.\n";
}
if ( cv->integer < nMinAlloc ) {
s_hunkTotal = 1024 * 1024 * nMinAlloc;
Com_Printf( pMsg, nMinAlloc, s_hunkTotal / ( 1024 * 1024 ) );
} else {
s_hunkTotal = cv->integer * 1024 * 1024;
}
s_hunkData = malloc( s_hunkTotal + 31 );
if ( !s_hunkData ) {
Com_Error( ERR_FATAL, "Hunk data failed to allocate %i megs", s_hunkTotal / ( 1024 * 1024 ) );
}
// cacheline align
s_hunkData = (byte *) ( ( (intptr_t)s_hunkData + 31 ) & ~31 );
Hunk_Clear();
Cmd_AddCommand( "meminfo", Com_Meminfo_f );
#ifdef HUNK_DEBUG
Cmd_AddCommand( "hunklog", Hunk_Log );
Cmd_AddCommand( "hunksmalllog", Hunk_SmallLog );
#endif
}
/*
====================
Hunk_MemoryRemaining
====================
*/
int Hunk_MemoryRemaining( void ) {
int low, high;
low = hunk_low.permanent > hunk_low.temp ? hunk_low.permanent : hunk_low.temp;
high = hunk_high.permanent > hunk_high.temp ? hunk_high.permanent : hunk_high.temp;
return s_hunkTotal - ( low + high );
}
/*
===================
Hunk_SetMark
The server calls this after the level and game VM have been loaded
===================
*/
void Hunk_SetMark( void ) {
hunk_low.mark = hunk_low.permanent;
hunk_high.mark = hunk_high.permanent;
}
/*
=================
Hunk_ClearToMark
The client calls this before starting a vid_restart or snd_restart
=================
*/
void Hunk_ClearToMark( void ) {
hunk_low.permanent = hunk_low.temp = hunk_low.mark;
hunk_high.permanent = hunk_high.temp = hunk_high.mark;
}
/*
=================
Hunk_CheckMark
=================
*/
qboolean Hunk_CheckMark( void ) {
if ( hunk_low.mark || hunk_high.mark ) {
return qtrue;
}
return qfalse;
}
void CL_ShutdownCGame( void );
void CL_ShutdownUI( void );
void SV_ShutdownGameProgs( void );
/*
=================
Hunk_Clear
The server calls this before shutting down or loading a new map
=================
*/
void Hunk_Clear( void ) {
#ifndef DEDICATED
CL_ShutdownCGame();
CL_ShutdownUI();
#endif
SV_ShutdownGameProgs();
#ifndef DEDICATED
CIN_CloseAllVideos();
#endif
hunk_low.mark = 0;
hunk_low.permanent = 0;
hunk_low.temp = 0;
hunk_low.tempHighwater = 0;
hunk_high.mark = 0;
hunk_high.permanent = 0;
hunk_high.temp = 0;
hunk_high.tempHighwater = 0;
hunk_permanent = &hunk_low;
hunk_temp = &hunk_high;
Cvar_Set( "com_hunkused", va( "%i", hunk_low.permanent + hunk_high.permanent ) );
Com_Printf( "Hunk_Clear: reset the hunk ok\n" );
VM_Clear(); // (SA) FIXME:TODO: was commented out in wolf
#ifdef HUNK_DEBUG
hunkblocks = NULL;
#endif
}
static void Hunk_SwapBanks( void ) {
hunkUsed_t *swap;
// can't swap banks if there is any temp already allocated
if ( hunk_temp->temp != hunk_temp->permanent ) {
return;
}
// if we have a larger highwater mark on this side, start making
// our permanent allocations here and use the other side for temp
if ( hunk_temp->tempHighwater - hunk_temp->permanent >
hunk_permanent->tempHighwater - hunk_permanent->permanent ) {
swap = hunk_temp;
hunk_temp = hunk_permanent;
hunk_permanent = swap;
}
}
/*
=================
Hunk_Alloc
Allocate permanent (until the hunk is cleared) memory
=================
*/
#ifdef HUNK_DEBUG
void *Hunk_AllocDebug( int size, ha_pref preference, char *label, char *file, int line ) {
#else
void *Hunk_Alloc( int size, ha_pref preference ) {
#endif
void *buf;
if ( s_hunkData == NULL ) {
Com_Error( ERR_FATAL, "Hunk_Alloc: Hunk memory system not initialized" );
}
Hunk_SwapBanks();
#ifdef HUNK_DEBUG
size += sizeof( hunkblock_t );
#endif
// round to cacheline
size = ( size + 31 ) & ~31;
if ( hunk_low.temp + hunk_high.temp + size > s_hunkTotal ) {
#ifdef HUNK_DEBUG
Hunk_Log();
Hunk_SmallLog();
Com_Error(ERR_DROP, "Hunk_Alloc failed on %i: %s, line: %d (%s)", size, file, line, label);
#else
Com_Error(ERR_DROP, "Hunk_Alloc failed on %i", size);
#endif
}
if ( hunk_permanent == &hunk_low ) {
buf = ( void * )( s_hunkData + hunk_permanent->permanent );
hunk_permanent->permanent += size;
} else {
hunk_permanent->permanent += size;
buf = ( void * )( s_hunkData + s_hunkTotal - hunk_permanent->permanent );
}
hunk_permanent->temp = hunk_permanent->permanent;
memset( buf, 0, size );
#ifdef HUNK_DEBUG
{
hunkblock_t *block;
block = (hunkblock_t *) buf;
block->size = size - sizeof( hunkblock_t );
block->file = file;
block->label = label;
block->line = line;
block->next = hunkblocks;
hunkblocks = block;
buf = ( (byte *) buf ) + sizeof( hunkblock_t );
}
#endif
// Ridah, update the com_hunkused cvar in increments, so we don't update it too often, since this cvar call isn't very efficent
if ( ( hunk_low.permanent + hunk_high.permanent ) > com_hunkused->integer + 10000 ) {
Cvar_Set( "com_hunkused", va( "%i", hunk_low.permanent + hunk_high.permanent ) );
}
return buf;
}
/*
=================
Hunk_AllocateTempMemory
This is used by the file loading system.
Multiple files can be loaded in temporary memory.
When the files-in-use count reaches zero, all temp memory will be deleted
=================
*/
void *Hunk_AllocateTempMemory( int size ) {
void *buf;
hunkHeader_t *hdr;
// return a Z_Malloc'd block if the hunk has not been initialized
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( s_hunkData == NULL ) {
return Z_Malloc( size );
}
Hunk_SwapBanks();
size = PAD(size, sizeof(intptr_t)) + sizeof( hunkHeader_t );
if ( hunk_temp->temp + hunk_permanent->permanent + size > s_hunkTotal ) {
Com_Error( ERR_DROP, "Hunk_AllocateTempMemory: failed on %i", size );
}
if ( hunk_temp == &hunk_low ) {
buf = ( void * )( s_hunkData + hunk_temp->temp );
hunk_temp->temp += size;
} else {
hunk_temp->temp += size;
buf = ( void * )( s_hunkData + s_hunkTotal - hunk_temp->temp );
}
if ( hunk_temp->temp > hunk_temp->tempHighwater ) {
hunk_temp->tempHighwater = hunk_temp->temp;
}
hdr = (hunkHeader_t *)buf;
buf = ( void * )( hdr + 1 );
hdr->magic = HUNK_MAGIC;
hdr->size = size;
// don't bother clearing, because we are going to load a file over it
return buf;
}
/*
==================
Hunk_FreeTempMemory
==================
*/
void Hunk_FreeTempMemory( void *buf ) {
hunkHeader_t *hdr;
// free with Z_Free if the hunk has not been initialized
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( s_hunkData == NULL ) {
Z_Free( buf );
return;
}
hdr = ( (hunkHeader_t *)buf ) - 1;
if ( hdr->magic != HUNK_MAGIC ) {
Com_Error( ERR_FATAL, "Hunk_FreeTempMemory: bad magic" );
}
hdr->magic = HUNK_FREE_MAGIC;
// this only works if the files are freed in stack order,
// otherwise the memory will stay around until Hunk_ClearTempMemory
if ( hunk_temp == &hunk_low ) {
if ( hdr == ( void * )( s_hunkData + hunk_temp->temp - hdr->size ) ) {
hunk_temp->temp -= hdr->size;
} else {
Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
}
} else {
if ( hdr == ( void * )( s_hunkData + s_hunkTotal - hunk_temp->temp ) ) {
hunk_temp->temp -= hdr->size;
} else {
Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
}
}
}
/*
=================
Hunk_ClearTempMemory
The temp space is no longer needed. If we have left more
touched but unused memory on this side, have future
permanent allocs use this side.
=================
*/
void Hunk_ClearTempMemory( void ) {
if ( s_hunkData != NULL ) {
hunk_temp->temp = hunk_temp->permanent;
}
}
/*
===================================================================
EVENTS AND JOURNALING
In addition to these events, .cfg files are also copied to the
journaled file
===================================================================
*/
#define MAX_PUSHED_EVENTS 1024
static int com_pushedEventsHead = 0;
static int com_pushedEventsTail = 0;
static sysEvent_t com_pushedEvents[MAX_PUSHED_EVENTS];
/*
=================
Com_InitJournaling
=================
*/
void Com_InitJournaling( void ) {
Com_StartupVariable( "journal" );
com_journal = Cvar_Get( "journal", "0", CVAR_INIT );
if ( !com_journal->integer ) {
return;
}
if ( com_journal->integer == 1 ) {
Com_Printf( "Journaling events\n" );
com_journalFile = FS_FOpenFileWrite( "journal.dat" );
com_journalDataFile = FS_FOpenFileWrite( "journaldata.dat" );
} else if ( com_journal->integer == 2 ) {
Com_Printf( "Replaying journaled events\n" );
FS_FOpenFileRead( "journal.dat", &com_journalFile, qtrue );
FS_FOpenFileRead( "journaldata.dat", &com_journalDataFile, qtrue );
}
if ( !com_journalFile || !com_journalDataFile ) {
Cvar_Set( "com_journal", "0" );
com_journalFile = 0;
com_journalDataFile = 0;
Com_Printf( "Couldn't open journal files\n" );
}
}
/*
========================================================================
EVENT LOOP
========================================================================
*/
#define MAX_QUEUED_EVENTS 256
#define MASK_QUEUED_EVENTS ( MAX_QUEUED_EVENTS - 1 )
static sysEvent_t eventQueue[ MAX_QUEUED_EVENTS ];
static int eventHead = 0;
static int eventTail = 0;
/*
================
Com_QueueEvent
A time of 0 will get the current time
Ptr should either be null, or point to a block of data that can
be freed by the game later.
================
*/
void Com_QueueEvent( int time, sysEventType_t type, int value, int value2, int ptrLength, void *ptr )
{
sysEvent_t *ev;
ev = &eventQueue[ eventHead & MASK_QUEUED_EVENTS ];
if ( eventHead - eventTail >= MAX_QUEUED_EVENTS )
{
Com_Printf("Com_QueueEvent: overflow\n");
// we are discarding an event, but don't leak memory
if ( ev->evPtr )
{
Z_Free( ev->evPtr );
}
eventTail++;
}
eventHead++;
if ( time == 0 )
{
time = Sys_Milliseconds();
}
ev->evTime = time;
ev->evType = type;
ev->evValue = value;
ev->evValue2 = value2;
ev->evPtrLength = ptrLength;
ev->evPtr = ptr;
}
/*
================
Com_GetSystemEvent
================
*/
sysEvent_t Com_GetSystemEvent( void )
{
sysEvent_t ev;
char *s;
// return if we have data
if ( eventHead > eventTail )
{
eventTail++;
return eventQueue[ ( eventTail - 1 ) & MASK_QUEUED_EVENTS ];
}
// check for console commands
s = Sys_ConsoleInput();
if ( s )
{
char *b;
int len;
len = strlen( s ) + 1;
b = Z_Malloc( len );
strcpy( b, s );
Com_QueueEvent( 0, SE_CONSOLE, 0, 0, len, b );
}
// return if we have data
if ( eventHead > eventTail )
{
eventTail++;
return eventQueue[ ( eventTail - 1 ) & MASK_QUEUED_EVENTS ];
}
// create an empty event to return
memset( &ev, 0, sizeof( ev ) );
ev.evTime = Sys_Milliseconds();
return ev;
}
/*
=================
Com_GetRealEvent
=================
*/
sysEvent_t Com_GetRealEvent( void ) {
int r;
sysEvent_t ev;
// either get an event from the system or the journal file
if ( com_journal->integer == 2 ) {
r = FS_Read( &ev, sizeof( ev ), com_journalFile );
if ( r != sizeof( ev ) ) {
Com_Error( ERR_FATAL, "Error reading from journal file" );
}
if ( ev.evPtrLength ) {
ev.evPtr = Z_Malloc( ev.evPtrLength );
r = FS_Read( ev.evPtr, ev.evPtrLength, com_journalFile );
if ( r != ev.evPtrLength ) {
Com_Error( ERR_FATAL, "Error reading from journal file" );
}
}
} else {
ev = Com_GetSystemEvent();
// write the journal value out if needed
if ( com_journal->integer == 1 ) {
r = FS_Write( &ev, sizeof( ev ), com_journalFile );
if ( r != sizeof( ev ) ) {
Com_Error( ERR_FATAL, "Error writing to journal file" );
}
if ( ev.evPtrLength ) {
r = FS_Write( ev.evPtr, ev.evPtrLength, com_journalFile );
if ( r != ev.evPtrLength ) {
Com_Error( ERR_FATAL, "Error writing to journal file" );
}
}
}
}
return ev;
}
/*
=================
Com_InitPushEvent
=================
*/
// bk001129 - added
void Com_InitPushEvent( void ) {
// clear the static buffer array
// this requires SE_NONE to be accepted as a valid but NOP event
memset( com_pushedEvents, 0, sizeof( com_pushedEvents ) );
// reset counters while we are at it
// beware: GetEvent might still return an SE_NONE from the buffer
com_pushedEventsHead = 0;
com_pushedEventsTail = 0;
}
/*
=================
Com_PushEvent
=================
*/
void Com_PushEvent( sysEvent_t *event ) {
sysEvent_t *ev;
static int printedWarning = 0;
ev = &com_pushedEvents[ com_pushedEventsHead & ( MAX_PUSHED_EVENTS - 1 ) ];
if ( com_pushedEventsHead - com_pushedEventsTail >= MAX_PUSHED_EVENTS ) {
// don't print the warning constantly, or it can give time for more...
if ( !printedWarning ) {
printedWarning = qtrue;
Com_Printf( "WARNING: Com_PushEvent overflow\n" );
}
if ( ev->evPtr ) {
Z_Free( ev->evPtr );
}
com_pushedEventsTail++;
} else {
printedWarning = qfalse;
}
*ev = *event;
com_pushedEventsHead++;
}
/*
=================
Com_GetEvent
=================
*/
sysEvent_t Com_GetEvent( void ) {
if ( com_pushedEventsHead > com_pushedEventsTail ) {
com_pushedEventsTail++;
return com_pushedEvents[ ( com_pushedEventsTail - 1 ) & ( MAX_PUSHED_EVENTS - 1 ) ];
}
return Com_GetRealEvent();
}
/*
=================
Com_RunAndTimeServerPacket
=================
*/
void Com_RunAndTimeServerPacket( netadr_t *evFrom, msg_t *buf ) {
int t1, t2, msec;
t1 = 0;
if ( com_speeds->integer ) {
t1 = Sys_Milliseconds();
}
SV_PacketEvent( *evFrom, buf );
if ( com_speeds->integer ) {
t2 = Sys_Milliseconds();
msec = t2 - t1;
if ( com_speeds->integer == 3 ) {
Com_Printf( "SV_PacketEvent time: %i\n", msec );
}
}
}
/*
=================
Com_EventLoop
Returns last event time
=================
*/
int Com_EventLoop( void ) {
sysEvent_t ev;
netadr_t evFrom;
byte bufData[MAX_MSGLEN];
msg_t buf;
MSG_Init( &buf, bufData, sizeof( bufData ) );
while ( 1 ) {
ev = Com_GetEvent();
// if no more events are available
if ( ev.evType == SE_NONE ) {
// manually send packet events for the loopback channel
while ( NET_GetLoopPacket( NS_CLIENT, &evFrom, &buf ) ) {
CL_PacketEvent( evFrom, &buf );
}
while ( NET_GetLoopPacket( NS_SERVER, &evFrom, &buf ) ) {
// if the server just shut down, flush the events
if ( com_sv_running->integer ) {
Com_RunAndTimeServerPacket( &evFrom, &buf );
}
}
return ev.evTime;
}
switch ( ev.evType ) {
case SE_KEY:
CL_KeyEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_CHAR:
CL_CharEvent( ev.evValue );
break;
case SE_MOUSE:
CL_MouseEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_JOYSTICK_AXIS:
CL_JoystickEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_CONSOLE:
Cbuf_AddText( (char *)ev.evPtr );
Cbuf_AddText( "\n" );
break;
default:
Com_Error( ERR_FATAL, "Com_EventLoop: bad event type %i", ev.evType );
break;
}
// free any block data
if ( ev.evPtr ) {
Z_Free( ev.evPtr );
}
}
return 0; // never reached
}
/*
================
Com_Milliseconds
Can be used for profiling, but will be journaled accurately
================
*/
int Com_Milliseconds( void ) {
sysEvent_t ev;
// get events and push them until we get a null event with the current time
do {
ev = Com_GetRealEvent();
if ( ev.evType != SE_NONE ) {
Com_PushEvent( &ev );
}
} while ( ev.evType != SE_NONE );
return ev.evTime;
}
//============================================================================
/*
=============
Com_Error_f
Just throw a fatal error to
test error shutdown procedures
=============
*/
static void __attribute__((__noreturn__)) Com_Error_f (void) {
if ( Cmd_Argc() > 1 ) {
Com_Error( ERR_DROP, "Testing drop error" );
} else {
Com_Error( ERR_FATAL, "Testing fatal error" );
}
}
/*
=============
Com_Freeze_f
Just freeze in place for a given number of seconds to test
error recovery
=============
*/
static void Com_Freeze_f( void ) {
float s;
int start, now;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "freeze <seconds>\n" );
return;
}
s = atof( Cmd_Argv( 1 ) );
start = Com_Milliseconds();
while ( 1 ) {
now = Com_Milliseconds();
if ( ( now - start ) * 0.001 > s ) {
break;
}
}
}
/*
=================
Com_Crash_f
A way to force a bus error for development reasons
=================
*/
static void Com_Crash_f( void ) {
* ( volatile int * ) 0 = 0x12345678;
}
/*
==================
Com_Setenv_f
For controlling environment variables
==================
*/
void Com_Setenv_f(void)
{
int argc = Cmd_Argc();
char *arg1 = Cmd_Argv(1);
if(argc > 2)
{
char *arg2 = Cmd_ArgsFrom(2);
Sys_SetEnv(arg1, arg2);
}
else if(argc == 2)
{
char *env = getenv(arg1);
if(env)
Com_Printf("%s=%s\n", arg1, env);
else
Com_Printf("%s undefined\n", arg1);
}
}
/*
==================
Com_ExecuteCfg
For controlling environment variables
==================
*/
void Com_ExecuteCfg(void)
{
Cbuf_ExecuteText(EXEC_NOW, "exec default.cfg\n");
if ( FS_ReadFile( "language.cfg", NULL ) > 0 ) {
Cbuf_ExecuteText(EXEC_APPEND, "exec language.cfg\n");
} else if ( FS_ReadFile( "Language.cfg", NULL ) > 0 ) {
Cbuf_ExecuteText(EXEC_APPEND, "exec Language.cfg\n");
}
Cbuf_Execute(); // Always execute after exec to prevent text buffer overflowing
if(!Com_SafeMode())
{
// skip the wolfconfig.cfg and autoexec.cfg if "safe" is on the command line
Cbuf_ExecuteText(EXEC_NOW, "exec " Q3CONFIG_CFG "\n");
Cbuf_Execute();
Cbuf_ExecuteText(EXEC_NOW, "exec autoexec.cfg\n");
Cbuf_Execute();
}
}
/*
==================
Com_GameRestart
Change to a new mod properly with cleaning up cvars before switching.
==================
*/
void Com_GameRestart(int checksumFeed, qboolean disconnect)
{
// make sure no recursion can be triggered
if(!com_gameRestarting && com_fullyInitialized)
{
com_gameRestarting = qtrue;
com_gameClientRestarting = com_cl_running->integer;
// Kill server if we have one
if(com_sv_running->integer)
SV_Shutdown("Game directory changed");
if(com_gameClientRestarting)
{
if(disconnect)
CL_Disconnect(qfalse);
CL_Shutdown("Game directory changed", disconnect, qfalse);
}
FS_Restart(checksumFeed);
// Clean out any user and VM created cvars
Cvar_Restart(qtrue);
Com_ExecuteCfg();
if(disconnect)
{
// We don't want to change any network settings if gamedir
// change was triggered by a connect to server because the
// new network settings might make the connection fail.
NET_Restart_f();
}
if(com_gameClientRestarting)
{
CL_Init();
CL_StartHunkUsers(qfalse);
}
com_gameRestarting = qfalse;
com_gameClientRestarting = qfalse;
}
}
/*
==================
Com_GameRestart_f
Expose possibility to change current running mod to the user
==================
*/
void Com_GameRestart_f(void)
{
if(!FS_FilenameCompare(Cmd_Argv(1), com_basegame->string))
{
// This is the standard base game. Servers and clients should
// use "" and not the standard basegame name because this messes
// up pak file negotiation and lots of other stuff
Cvar_Set("fs_game", "");
}
else
Cvar_Set("fs_game", Cmd_Argv(1));
Com_GameRestart(0, qtrue);
}
#ifndef STANDALONE
qboolean CL_CDKeyValidate( const char *key, const char *checksum );
// TTimo: centralizing the cl_cdkey stuff after I discovered a buffer overflow problem with the dedicated server version
// not sure it's necessary to have different defaults for regular and dedicated, but I don't want to take the risk
#ifndef DEDICATED
char cl_cdkey[34] = " ";
#else
char cl_cdkey[34] = "123456789";
#endif
/*
=================
Com_ReadCDKey
=================
*/
void Com_ReadCDKey( const char *filename ) {
fileHandle_t f;
char buffer[33];
char fbuffer[MAX_OSPATH];
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename);
FS_SV_FOpenFileRead( fbuffer, &f );
if ( !f ) {
Q_strncpyz( cl_cdkey, " ", 17 );
return;
}
Com_Memset( buffer, 0, sizeof( buffer ) );
FS_Read( buffer, 16, f );
FS_FCloseFile( f );
if ( CL_CDKeyValidate( buffer, NULL ) ) {
Q_strncpyz( cl_cdkey, buffer, 17 );
} else {
Q_strncpyz( cl_cdkey, " ", 17 );
}
}
/*
=================
Com_AppendCDKey
=================
*/
void Com_AppendCDKey( const char *filename ) {
fileHandle_t f;
char buffer[33];
char fbuffer[MAX_OSPATH];
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename);
FS_SV_FOpenFileRead( fbuffer, &f );
if ( !f ) {
Q_strncpyz( &cl_cdkey[16], " ", 17 );
return;
}
Com_Memset( buffer, 0, sizeof( buffer ) );
FS_Read( buffer, 16, f );
FS_FCloseFile( f );
if ( CL_CDKeyValidate( buffer, NULL ) ) {
strcat( &cl_cdkey[16], buffer );
} else {
Q_strncpyz( &cl_cdkey[16], " ", 17 );
}
}
#ifndef DEDICATED
/*
=================
Com_WriteCDKey
=================
*/
static void Com_WriteCDKey( const char *filename, const char *ikey ) {
fileHandle_t f;
char fbuffer[MAX_OSPATH];
char key[17];
#ifndef _WIN32
mode_t savedumask;
#endif
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename);
Q_strncpyz( key, ikey, 17 );
if ( !CL_CDKeyValidate( key, NULL ) ) {
return;
}
#ifndef _WIN32
savedumask = umask(0077);
#endif
f = FS_SV_FOpenFileWrite( fbuffer );
if ( !f ) {
Com_Printf ("Couldn't write CD key to %s.\n", fbuffer );
goto out;
}
FS_Write( key, 16, f );
FS_Printf( f, "\n// generated by RTCW, do not modify\r\n" );
FS_Printf( f, "// Do not give this file to ANYONE.\r\n" );
#ifdef __APPLE__ // TTimo
FS_Printf( f, "// Aspyr will NOT ask you to send this file to them.\r\n" );
#else
FS_Printf( f, "// id Software and Activision will NOT ask you to send this file to them.\r\n" );
#endif
FS_FCloseFile( f );
out:
#ifndef _WIN32
umask(savedumask);
#else
;
#endif
}
#endif
#endif // STANDALONE
static void Com_DetectAltivec(void)
{
// Only detect if user hasn't forcibly disabled it.
if (com_altivec->integer) {
static qboolean altivec = qfalse;
static qboolean detected = qfalse;
if (!detected) {
altivec = ( Sys_GetProcessorFeatures( ) & CF_ALTIVEC );
detected = qtrue;
}
if (!altivec) {
Cvar_Set( "com_altivec", "0" ); // we don't have it! Disable support!
}
}
}
void Com_SetRecommended( qboolean vidrestart ) {
cvar_t *cv;
qboolean goodVideo;
qboolean goodCPU;
qboolean lowMemory;
// will use this for recommended settings as well.. do i outside the lower check so it gets done even with command line stuff
cv = Cvar_Get( "r_highQualityVideo", "1", CVAR_ARCHIVE );
goodVideo = ( cv && cv->integer );
goodCPU = Sys_GetHighQualityCPU();
lowMemory = Sys_LowPhysicalMemory();
if ( goodVideo && goodCPU ) {
Com_Printf( "Found high quality video and CPU\n" );
Cbuf_AddText( "exec highVidhighCPU.cfg\n" );
} else if ( goodVideo && !goodCPU ) {
Cbuf_AddText( "exec highVidlowCPU.cfg\n" );
Com_Printf( "Found high quality video and low quality CPU\n" );
} else if ( !goodVideo && goodCPU ) {
Cbuf_AddText( "exec lowVidhighCPU.cfg\n" );
Com_Printf( "Found low quality video and high quality CPU\n" );
} else {
Cbuf_AddText( "exec lowVidlowCPU.cfg\n" );
Com_Printf( "Found low quality video and low quality CPU\n" );
}
// (SA) set the cvar so the menu will reflect this on first run
Cvar_Set( "ui_glCustom", "999" ); // 'recommended'
if ( lowMemory ) {
Com_Printf( "Found minimum memory requirement\n" );
Cvar_Set( "s_khz", "11" );
if ( !goodVideo ) {
Cvar_Set( "r_lowMemTextureSize", "256" );
Cvar_Set( "r_lowMemTextureThreshold", "40.0" );
}
}
if ( vidrestart ) {
Cbuf_AddText( "vid_restart\n" );
}
}
/*
=================
Com_DetectSSE
Find out whether we have SSE support for Q_ftol function
=================
*/
#if id386 || idx64
static void Com_DetectSSE(void)
{
#if !idx64
cpuFeatures_t feat;
feat = Sys_GetProcessorFeatures();
if(feat & CF_SSE)
{
if(feat & CF_SSE2)
Q_SnapVector = qsnapvectorsse;
else
Q_SnapVector = qsnapvectorx87;
Q_ftol = qftolsse;
#endif
Q_VMftol = qvmftolsse;
Com_Printf("SSE instruction set enabled\n");
#if !idx64
}
else
{
Q_ftol = qftolx87;
Q_VMftol = qvmftolx87;
Q_SnapVector = qsnapvectorx87;
Com_Printf("SSE instruction set not available\n");
}
#endif
}
#else
#define Com_DetectSSE()
#endif
/*
=================
Com_InitRand
Seed the random number generator, if possible with an OS supplied random seed.
=================
*/
static void Com_InitRand(void)
{
unsigned int seed;
if(Sys_RandomBytes((byte *) &seed, sizeof(seed)))
srand(seed);
else
srand(time(NULL));
}
/*
=================
Com_Init
=================
*/
void Com_Init( char *commandLine ) {
char *s;
int qport;
Com_Printf( "%s %s %s\n", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
if ( setjmp( abortframe ) ) {
Sys_Error( "Error during initialization" );
}
// Clear queues
Com_Memset( &eventQueue[ 0 ], 0, MAX_QUEUED_EVENTS * sizeof( sysEvent_t ) );
// initialize the weak pseudo-random number generator for use later.
Com_InitRand();
// do this before anything else decides to push events
Com_InitPushEvent();
Cvar_Init();
// prepare enough of the subsystems to handle
// cvar and command buffer management
Com_ParseCommandLine( commandLine );
// Swap_Init();
Cbuf_Init();
Com_DetectSSE();
// override anything from the config files with command line args
Com_StartupVariable( NULL );
Com_InitZoneMemory();
Cmd_Init ();
// get the developer cvar set as early as possible
com_developer = Cvar_Get("developer", "0", CVAR_TEMP);
// done early so bind command exists
CL_InitKeyCommands();
com_standalone = Cvar_Get("com_standalone", "0", CVAR_ROM);
com_basegame = Cvar_Get("com_basegame", BASEGAME, CVAR_INIT);
com_homepath = Cvar_Get("com_homepath", "", CVAR_INIT);
if(!com_basegame->string[0])
Cvar_ForceReset("com_basegame");
FS_InitFilesystem();
Com_InitJournaling();
// Add some commands here already so users can use them from config files
Cmd_AddCommand ("setenv", Com_Setenv_f);
if (com_developer && com_developer->integer)
{
Cmd_AddCommand ("error", Com_Error_f);
Cmd_AddCommand ("crash", Com_Crash_f);
Cmd_AddCommand ("freeze", Com_Freeze_f);
}
Cmd_AddCommand ("quit", Com_Quit_f);
Cmd_AddCommand ("changeVectors", MSG_ReportChangeVectors_f );
Cmd_AddCommand ("writeconfig", Com_WriteConfig_f );
Cmd_SetCommandCompletionFunc( "writeconfig", Cmd_CompleteCfgName );
Cmd_AddCommand("game_restart", Com_GameRestart_f);
Com_ExecuteCfg();
// override anything from the config files with command line args
Com_StartupVariable( NULL );
// get dedicated here for proper hunk megs initialization
#ifdef DEDICATED
com_dedicated = Cvar_Get ("dedicated", "1", CVAR_INIT);
Cvar_CheckRange( com_dedicated, 1, 2, qtrue );
#else
com_dedicated = Cvar_Get( "dedicated", "0", CVAR_LATCH );
Cvar_CheckRange( com_dedicated, 0, 2, qtrue );
#endif
// allocate the stack based hunk allocator
Com_InitHunkMemory();
// if any archived cvars are modified after this, we will trigger a writing
// of the config file
cvar_modifiedFlags &= ~CVAR_ARCHIVE;
//
// init commands and vars
//
com_altivec = Cvar_Get ("com_altivec", "1", CVAR_ARCHIVE);
com_maxfps = Cvar_Get( "com_maxfps", "76", CVAR_ARCHIVE );
com_blood = Cvar_Get( "com_blood", "1", CVAR_ARCHIVE );
com_logfile = Cvar_Get( "logfile", "0", CVAR_TEMP );
com_timescale = Cvar_Get( "timescale", "1", CVAR_CHEAT | CVAR_SYSTEMINFO );
com_fixedtime = Cvar_Get( "fixedtime", "0", CVAR_CHEAT );
com_showtrace = Cvar_Get( "com_showtrace", "0", CVAR_CHEAT );
com_speeds = Cvar_Get( "com_speeds", "0", 0 );
com_timedemo = Cvar_Get( "timedemo", "0", CVAR_CHEAT );
com_cameraMode = Cvar_Get( "com_cameraMode", "0", CVAR_CHEAT );
cl_paused = Cvar_Get( "cl_paused", "0", CVAR_ROM );
sv_paused = Cvar_Get( "sv_paused", "0", CVAR_ROM );
cl_packetdelay = Cvar_Get ("cl_packetdelay", "0", CVAR_CHEAT);
sv_packetdelay = Cvar_Get ("sv_packetdelay", "0", CVAR_CHEAT);
com_sv_running = Cvar_Get( "sv_running", "0", CVAR_ROM );
com_cl_running = Cvar_Get( "cl_running", "0", CVAR_ROM );
com_buildScript = Cvar_Get( "com_buildScript", "0", 0 );
com_ansiColor = Cvar_Get( "com_ansiColor", "0", CVAR_ARCHIVE );
com_unfocused = Cvar_Get( "com_unfocused", "0", CVAR_ROM );
com_maxfpsUnfocused = Cvar_Get( "com_maxfpsUnfocused", "0", CVAR_ARCHIVE );
com_minimized = Cvar_Get( "com_minimized", "0", CVAR_ROM );
com_maxfpsMinimized = Cvar_Get( "com_maxfpsMinimized", "0", CVAR_ARCHIVE );
com_abnormalExit = Cvar_Get( "com_abnormalExit", "0", CVAR_ROM );
com_busyWait = Cvar_Get("com_busyWait", "0", CVAR_ARCHIVE);
Cvar_Get("com_errorMessage", "", CVAR_ROM | CVAR_NORESTART);
#ifdef CINEMATICS_INTRO
com_introPlayed = Cvar_Get( "com_introplayed", "0", CVAR_ARCHIVE );
#endif
com_recommendedSet = Cvar_Get( "com_recommendedSet", "0", CVAR_ARCHIVE );
Cvar_Get( "savegame_loading", "0", CVAR_ROM );
s = va("%s %s %s", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
com_version = Cvar_Get ("version", s, CVAR_ROM | CVAR_SERVERINFO );
com_gamename = Cvar_Get("com_gamename", GAMENAME_FOR_MASTER, CVAR_SERVERINFO | CVAR_INIT);
com_protocol = Cvar_Get("com_protocol", va("%i", PROTOCOL_VERSION), CVAR_SERVERINFO | CVAR_INIT);
#ifdef LEGACY_PROTOCOL
com_legacyprotocol = Cvar_Get("com_legacyprotocol", va("%i", PROTOCOL_LEGACY_VERSION), CVAR_INIT);
// Keep for compatibility with old mods / mods that haven't updated yet.
if(com_legacyprotocol->integer > 0)
Cvar_Get("protocol", com_legacyprotocol->string, CVAR_ROM);
else
#endif
Cvar_Get("protocol", com_protocol->string, CVAR_ROM);
com_hunkused = Cvar_Get( "com_hunkused", "0", 0 );
Sys_Init();
Sys_InitPIDFile( FS_GetCurrentGameDir() );
// Pick a random port value
Com_RandomBytes( (byte*)&qport, sizeof(int) );
Netchan_Init( qport & 0xffff );
VM_Init();
SV_Init();
com_dedicated->modified = qfalse;
#ifndef DEDICATED
CL_Init();
#endif
// set com_frameTime so that if a map is started on the
// command line it will still be able to count on com_frameTime
// being random enough for a serverid
com_frameTime = Com_Milliseconds();
// add + commands from command line
if ( !Com_AddStartupCommands() ) {
// if the user didn't give any commands, run default action
}
// start in full screen ui mode
Cvar_Set( "r_uiFullScreen", "1" );
CL_StartHunkUsers( qfalse );
if ( !com_recommendedSet->integer ) {
Com_SetRecommended( qtrue );
Cvar_Set( "com_recommendedSet", "1" );
}
if ( !com_dedicated->integer ) {
#ifdef CINEMATICS_LOGO
//Cbuf_AddText ("cinematic " CINEMATICS_LOGO "\n");
#endif
#ifdef CINEMATICS_INTRO
if ( !com_introPlayed->integer ) {
//Cvar_Set( com_introPlayed->name, "1" ); //----(SA) force this to get played every time (but leave cvar for override)
Cbuf_AddText( "cinematic " CINEMATICS_INTRO " 3\n" );
//Cvar_Set( "nextmap", "cinematic " CINEMATICS_INTRO );
}
#endif
}
com_fullyInitialized = qtrue;
// always set the cvar, but only print the info if it makes sense.
Com_DetectAltivec();
#if idppc
Com_Printf ("Altivec support is %s\n", com_altivec->integer ? "enabled" : "disabled");
#endif
com_pipefile = Cvar_Get( "com_pipefile", "", CVAR_ARCHIVE|CVAR_LATCH );
if( com_pipefile->string[0] )
{
pipefile = FS_FCreateOpenPipeFile( com_pipefile->string );
}
Com_Printf ("--- Common Initialization Complete ---\n");
}
/*
===============
Com_ReadFromPipe
Read whatever is in com_pipefile, if anything, and execute it
===============
*/
void Com_ReadFromPipe( void )
{
static char buf[MAX_STRING_CHARS];
static int accu = 0;
int read;
if( !pipefile )
return;
while( ( read = FS_Read( buf + accu, sizeof( buf ) - accu - 1, pipefile ) ) > 0 )
{
char *brk = NULL;
int i;
for( i = accu; i < accu + read; ++i )
{
if( buf[ i ] == '\0' )
buf[ i ] = '\n';
if( buf[ i ] == '\n' || buf[ i ] == '\r' )
brk = &buf[ i + 1 ];
}
buf[ accu + read ] = '\0';
accu += read;
if( brk )
{
char tmp = *brk;
*brk = '\0';
Cbuf_ExecuteText( EXEC_APPEND, buf );
*brk = tmp;
accu -= brk - buf;
memmove( buf, brk, accu + 1 );
}
else if( accu >= sizeof( buf ) - 1 ) // full
{
Cbuf_ExecuteText( EXEC_APPEND, buf );
accu = 0;
}
}
}
//==================================================================
void Com_WriteConfigToFile( const char *filename ) {
fileHandle_t f;
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf( "Couldn't write %s.\n", filename );
return;
}
FS_Printf( f, "// generated by RTCW, do not modify\n" );
Key_WriteBindings( f );
Cvar_WriteVariables( f );
FS_FCloseFile( f );
}
/*
===============
Com_WriteConfiguration
Writes key bindings and archived cvars to config file if modified
===============
*/
void Com_WriteConfiguration( void ) {
#if !defined(DEDICATED) && !defined(STANDALONE)
cvar_t *fs;
#endif
// if we are quiting without fully initializing, make sure
// we don't write out anything
if ( !com_fullyInitialized ) {
return;
}
if ( !( cvar_modifiedFlags & CVAR_ARCHIVE ) ) {
return;
}
cvar_modifiedFlags &= ~CVAR_ARCHIVE;
Com_WriteConfigToFile( Q3CONFIG_CFG );
// not needed for dedicated or standalone
#if !defined(DEDICATED) && !defined(STANDALONE)
fs = Cvar_Get( "fs_game", "", CVAR_INIT | CVAR_SYSTEMINFO );
if(!com_standalone->integer)
{
if (UI_usesUniqueCDKey() && fs && fs->string[0] != 0) {
Com_WriteCDKey( fs->string, &cl_cdkey[16] );
} else {
Com_WriteCDKey( BASEGAME, cl_cdkey );
}
}
#endif
}
/*
===============
Com_WriteConfig_f
Write the config file to a specific name
===============
*/
void Com_WriteConfig_f( void ) {
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: writeconfig <filename>\n" );
return;
}
if (!COM_CompareExtension(filename, ".cfg"))
{
Com_Printf("Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n");
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
Com_Printf( "Writing %s.\n", filename );
Com_WriteConfigToFile( filename );
}
/*
================
Com_ModifyMsec
================
*/
int Com_ModifyMsec( int msec ) {
int clampTime;
//
// modify time for debugging values
//
if ( com_fixedtime->integer ) {
msec = com_fixedtime->integer;
} else if ( com_timescale->value ) {
msec *= com_timescale->value;
// } else if (com_cameraMode->integer) {
// msec *= com_timescale->value;
}
// don't let it scale below 1 msec
if ( msec < 1 && com_timescale->value ) {
msec = 1;
}
if ( com_dedicated->integer ) {
// dedicated servers don't want to clamp for a much longer
// period, because it would mess up all the client's views
// of time.
if (com_sv_running->integer && msec > 500)
Com_Printf( "Hitch warning: %i msec frame time\n", msec );
clampTime = 5000;
} else
if ( !com_sv_running->integer ) {
// clients of remote servers do not want to clamp time, because
// it would skew their view of the server's time temporarily
clampTime = 5000;
} else {
// for local single player gaming
// we may want to clamp the time to prevent players from
// flying off edges when something hitches.
clampTime = 200;
}
if ( msec > clampTime ) {
msec = clampTime;
}
return msec;
}
/*
=================
Com_TimeVal
=================
*/
int Com_TimeVal(int minMsec)
{
int timeVal;
timeVal = Sys_Milliseconds() - com_frameTime;
if(timeVal >= minMsec)
timeVal = 0;
else
timeVal = minMsec - timeVal;
return timeVal;
}
/*
=================
Com_Frame
=================
*/
void Com_Frame( void ) {
int msec, minMsec;
int timeVal, timeValSV;
static int lastTime = 0, bias = 0;
int timeBeforeFirstEvents;
int timeBeforeServer;
int timeBeforeEvents;
int timeBeforeClient;
int timeAfter;
if ( setjmp( abortframe ) ) {
return; // an ERR_DROP was thrown
}
timeBeforeFirstEvents = 0;
timeBeforeServer = 0;
timeBeforeEvents = 0;
timeBeforeClient = 0;
timeAfter = 0;
// write config file if anything changed
Com_WriteConfiguration();
//
// main event loop
//
if ( com_speeds->integer ) {
timeBeforeFirstEvents = Sys_Milliseconds();
}
// Figure out how much time we have
if(!com_timedemo->integer)
{
if(com_dedicated->integer)
minMsec = SV_FrameMsec();
else
{
if(com_minimized->integer && com_maxfpsMinimized->integer > 0)
minMsec = 1000 / com_maxfpsMinimized->integer;
else if(com_unfocused->integer && com_maxfpsUnfocused->integer > 0)
minMsec = 1000 / com_maxfpsUnfocused->integer;
else if(com_maxfps->integer > 0)
minMsec = 1000 / com_maxfps->integer;
else
minMsec = 1;
timeVal = com_frameTime - lastTime;
bias += timeVal - minMsec;
if(bias > minMsec)
bias = minMsec;
// Adjust minMsec if previous frame took too long to render so
// that framerate is stable at the requested value.
minMsec -= bias;
}
}
else
minMsec = 1;
do
{
if(com_sv_running->integer)
{
timeValSV = SV_SendQueuedPackets();
timeVal = Com_TimeVal(minMsec);
if(timeValSV < timeVal)
timeVal = timeValSV;
}
else
timeVal = Com_TimeVal(minMsec);
if(com_busyWait->integer || timeVal < 1)
NET_Sleep(0);
else
NET_Sleep(timeVal - 1);
} while(Com_TimeVal(minMsec));
lastTime = com_frameTime;
com_frameTime = Com_EventLoop();
msec = com_frameTime - lastTime;
Cbuf_Execute();
if (com_altivec->modified)
{
Com_DetectAltivec();
com_altivec->modified = qfalse;
}
// mess with msec if needed
msec = Com_ModifyMsec(msec);
//
// server side
//
if ( com_speeds->integer ) {
timeBeforeServer = Sys_Milliseconds();
}
SV_Frame( msec );
// if "dedicated" has been modified, start up
// or shut down the client system.
// Do this after the server may have started,
// but before the client tries to auto-connect
if ( com_dedicated->modified ) {
// get the latched value
Cvar_Get( "dedicated", "0", 0 );
com_dedicated->modified = qfalse;
if ( !com_dedicated->integer ) {
SV_Shutdown( "dedicated set to 0" );
CL_FlushMemory();
}
}
#ifndef DEDICATED
//
// client system
//
//
// run event loop a second time to get server to client packets
// without a frame of latency
//
if ( com_speeds->integer ) {
timeBeforeEvents = Sys_Milliseconds ();
}
Com_EventLoop();
Cbuf_Execute ();
//
// client side
//
if ( com_speeds->integer ) {
timeBeforeClient = Sys_Milliseconds ();
}
CL_Frame( msec );
if ( com_speeds->integer ) {
timeAfter = Sys_Milliseconds ();
}
#else
if ( com_speeds->integer ) {
timeAfter = Sys_Milliseconds ();
timeBeforeEvents = timeAfter;
timeBeforeClient = timeAfter;
}
#endif
NET_FlushPacketQueue();
//
// report timing information
//
if ( com_speeds->integer ) {
int all, sv, ev, cl;
all = timeAfter - timeBeforeServer;
sv = timeBeforeEvents - timeBeforeServer;
ev = timeBeforeServer - timeBeforeFirstEvents + timeBeforeClient - timeBeforeEvents;
cl = timeAfter - timeBeforeClient;
sv -= time_game;
cl -= time_frontend + time_backend;
Com_Printf( "frame:%i all:%3i sv:%3i ev:%3i cl:%3i gm:%3i rf:%3i bk:%3i\n",
com_frameNumber, all, sv, ev, cl, time_game, time_frontend, time_backend );
}
//
// trace optimization tracking
//
if ( com_showtrace->integer ) {
extern int c_traces, c_brush_traces, c_patch_traces;
extern int c_pointcontents;
Com_Printf( "%4i traces (%ib %ip) %4i points\n", c_traces,
c_brush_traces, c_patch_traces, c_pointcontents );
c_traces = 0;
c_brush_traces = 0;
c_patch_traces = 0;
c_pointcontents = 0;
}
Com_ReadFromPipe( );
com_frameNumber++;
}
/*
=================
Com_Shutdown
=================
*/
void Com_Shutdown( void ) {
// write config file if anything changed
Com_WriteConfiguration();
if ( logfile ) {
FS_FCloseFile( logfile );
logfile = 0;
}
if ( com_journalFile ) {
FS_FCloseFile( com_journalFile );
com_journalFile = 0;
}
if( pipefile ) {
FS_FCloseFile( pipefile );
FS_HomeRemove( com_pipefile->string );
}
}
/*
===========================================
command line completion
===========================================
*/
/*
==================
Field_Clear
==================
*/
void Field_Clear( field_t *edit ) {
memset( edit->buffer, 0, MAX_EDIT_LINE );
edit->cursor = 0;
edit->scroll = 0;
}
static const char *completionString;
static char shortestMatch[MAX_TOKEN_CHARS];
static int matchCount;
// field we are working on, passed to Field_AutoComplete(&g_consoleCommand for instance)
static field_t *completionField;
/*
===============
FindMatches
===============
*/
static void FindMatches( const char *s ) {
int i;
if ( Q_stricmpn( s, completionString, strlen( completionString ) ) ) {
return;
}
matchCount++;
if ( matchCount == 1 ) {
Q_strncpyz( shortestMatch, s, sizeof( shortestMatch ) );
return;
}
// cut shortestMatch to the amount common with s
for ( i = 0 ; shortestMatch[i] ; i++ ) {
if ( i >= strlen( s ) ) {
shortestMatch[i] = 0;
break;
}
if ( tolower( shortestMatch[i] ) != tolower( s[i] ) ) {
shortestMatch[i] = 0;
}
}
}
/*
===============
PrintMatches
===============
*/
static void PrintMatches( const char *s ) {
if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
Com_Printf( " %s\n", s );
}
}
/*
===============
PrintCvarMatches
===============
*/
static void PrintCvarMatches( const char *s ) {
char value[ TRUNCATE_LENGTH ];
if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
Com_TruncateLongString( value, Cvar_VariableString( s ) );
Com_Printf( " %s = \"%s\"\n", s, value );
}
}
/*
===============
Field_FindFirstSeparator
===============
*/
static char *Field_FindFirstSeparator( char *s )
{
int i;
for( i = 0; i < strlen( s ); i++ )
{
if( s[ i ] == ';' )
return &s[ i ];
}
return NULL;
}
/*
===============
Field_Complete
===============
*/
static qboolean Field_Complete( void )
{
int completionOffset;
if( matchCount == 0 )
return qtrue;
completionOffset = strlen( completionField->buffer ) - strlen( completionString );
Q_strncpyz( &completionField->buffer[ completionOffset ], shortestMatch,
sizeof( completionField->buffer ) - completionOffset );
completionField->cursor = strlen( completionField->buffer );
if( matchCount == 1 )
{
Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " );
completionField->cursor++;
return qtrue;
}
Com_Printf( "]%s\n", completionField->buffer );
return qfalse;
}
#ifndef DEDICATED
/*
===============
Field_CompleteKeyname
===============
*/
void Field_CompleteKeyname( void )
{
matchCount = 0;
shortestMatch[ 0 ] = 0;
Key_KeynameCompletion( FindMatches );
if( !Field_Complete( ) )
Key_KeynameCompletion( PrintMatches );
}
#endif
/*
===============
Field_CompleteFilename
===============
*/
void Field_CompleteFilename( const char *dir,
const char *ext, qboolean stripExt, qboolean allowNonPureFilesOnDisk )
{
matchCount = 0;
shortestMatch[ 0 ] = 0;
FS_FilenameCompletion( dir, ext, stripExt, FindMatches, allowNonPureFilesOnDisk );
if( !Field_Complete( ) )
FS_FilenameCompletion( dir, ext, stripExt, PrintMatches, allowNonPureFilesOnDisk );
}
/*
===============
Field_CompleteCommand
===============
*/
void Field_CompleteCommand( char *cmd,
qboolean doCommands, qboolean doCvars )
{
int completionArgument = 0;
// Skip leading whitespace and quotes
cmd = Com_SkipCharset( cmd, " \"" );
Cmd_TokenizeStringIgnoreQuotes( cmd );
completionArgument = Cmd_Argc( );
// If there is trailing whitespace on the cmd
if( *( cmd + strlen( cmd ) - 1 ) == ' ' )
{
completionString = "";
completionArgument++;
}
else
completionString = Cmd_Argv( completionArgument - 1 );
#ifndef DEDICATED
// Unconditionally add a '\' to the start of the buffer
if( completionField->buffer[ 0 ] &&
completionField->buffer[ 0 ] != '\\' )
{
if( completionField->buffer[ 0 ] != '/' )
{
// Buffer is full, refuse to complete
if( strlen( completionField->buffer ) + 1 >=
sizeof( completionField->buffer ) )
return;
memmove( &completionField->buffer[ 1 ],
&completionField->buffer[ 0 ],
strlen( completionField->buffer ) + 1 );
completionField->cursor++;
}
completionField->buffer[ 0 ] = '\\';
}
#endif
if( completionArgument > 1 )
{
const char *baseCmd = Cmd_Argv( 0 );
char *p;
#ifndef DEDICATED
// This should always be true
if( baseCmd[ 0 ] == '\\' || baseCmd[ 0 ] == '/' )
baseCmd++;
#endif
if( ( p = Field_FindFirstSeparator( cmd ) ) )
Field_CompleteCommand( p + 1, qtrue, qtrue ); // Compound command
else
Cmd_CompleteArgument( baseCmd, cmd, completionArgument );
}
else
{
if( completionString[0] == '\\' || completionString[0] == '/' )
completionString++;
matchCount = 0;
shortestMatch[ 0 ] = 0;
if( strlen( completionString ) == 0 )
return;
if( doCommands )
Cmd_CommandCompletion( FindMatches );
if( doCvars )
Cvar_CommandCompletion( FindMatches );
if( !Field_Complete( ) )
{
// run through again, printing matches
if( doCommands )
Cmd_CommandCompletion( PrintMatches );
if( doCvars )
Cvar_CommandCompletion( PrintCvarMatches );
}
}
}
/*
===============
Field_AutoComplete
Perform Tab expansion
===============
*/
void Field_AutoComplete( field_t *field )
{
completionField = field;
Field_CompleteCommand( completionField->buffer, qtrue, qtrue );
}
/*
==================
Com_RandomBytes
fills string array with len random bytes, peferably from the OS randomizer
==================
*/
void Com_RandomBytes( byte *string, int len )
{
int i;
if( Sys_RandomBytes( string, len ) )
return;
Com_Printf( "Com_RandomBytes: using weak randomization\n" );
for( i = 0; i < len; i++ )
string[i] = (unsigned char)( rand() % 256 );
}
/*
==================
Com_IsVoipTarget
Returns non-zero if given clientNum is enabled in voipTargets, zero otherwise.
If clientNum is negative return if any bit is set.
==================
*/
qboolean Com_IsVoipTarget(uint8_t *voipTargets, int voipTargetsSize, int clientNum)
{
int index;
if(clientNum < 0)
{
for(index = 0; index < voipTargetsSize; index++)
{
if(voipTargets[index])
return qtrue;
}
return qfalse;
}
index = clientNum >> 3;
if(index < voipTargetsSize)
return (voipTargets[index] & (1 << (clientNum & 0x07)));
return qfalse;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3231_3 |
crossvul-cpp_data_bad_3233_5 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include <signal.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/types.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#ifndef DEDICATED
#ifdef USE_LOCAL_HEADERS
# include "SDL.h"
# include "SDL_cpuinfo.h"
#else
# include <SDL.h>
# include <SDL_cpuinfo.h>
#endif
#endif
#include "sys_local.h"
#include "sys_loadlib.h"
#include "../qcommon/q_shared.h"
#include "../qcommon/qcommon.h"
static char binaryPath[ MAX_OSPATH ] = { 0 };
static char installPath[ MAX_OSPATH ] = { 0 };
/*
=================
Sys_SetBinaryPath
=================
*/
void Sys_SetBinaryPath(const char *path)
{
Q_strncpyz(binaryPath, path, sizeof(binaryPath));
}
/*
=================
Sys_BinaryPath
=================
*/
char *Sys_BinaryPath(void)
{
return binaryPath;
}
/*
=================
Sys_SetDefaultInstallPath
=================
*/
void Sys_SetDefaultInstallPath(const char *path)
{
Q_strncpyz(installPath, path, sizeof(installPath));
}
/*
=================
Sys_DefaultInstallPath
=================
*/
char *Sys_DefaultInstallPath(void)
{
if (*installPath)
return installPath;
else
return Sys_Cwd();
}
/*
=================
Sys_DefaultAppPath
=================
*/
char *Sys_DefaultAppPath(void)
{
return Sys_BinaryPath();
}
/*
=================
Sys_In_Restart_f
Restart the input subsystem
=================
*/
void Sys_In_Restart_f( void )
{
IN_Restart( );
}
/*
=================
Sys_ConsoleInput
Handle new console input
=================
*/
char *Sys_ConsoleInput(void)
{
return CON_Input( );
}
/*
==================
Sys_GetClipboardData
==================
*/
char *Sys_GetClipboardData(void)
{
#ifdef DEDICATED
return NULL;
#else
char *data = NULL;
char *cliptext;
if ( ( cliptext = SDL_GetClipboardText() ) != NULL ) {
if ( cliptext[0] != '\0' ) {
size_t bufsize = strlen( cliptext ) + 1;
data = Z_Malloc( bufsize );
Q_strncpyz( data, cliptext, bufsize );
// find first listed char and set to '\0'
strtok( data, "\n\r\b" );
}
SDL_free( cliptext );
}
return data;
#endif
}
#ifdef DEDICATED
# define PID_FILENAME "iowolfsp_server.pid"
#else
# define PID_FILENAME "iowolfsp.pid"
#endif
/*
=================
Sys_PIDFileName
=================
*/
static char *Sys_PIDFileName( const char *gamedir )
{
const char *homePath = Cvar_VariableString( "fs_homepath" );
if( *homePath != '\0' )
return va( "%s/%s/%s", homePath, gamedir, PID_FILENAME );
return NULL;
}
/*
=================
Sys_RemovePIDFile
=================
*/
void Sys_RemovePIDFile( const char *gamedir )
{
char *pidFile = Sys_PIDFileName( gamedir );
if( pidFile != NULL )
remove( pidFile );
}
/*
=================
Sys_WritePIDFile
Return qtrue if there is an existing stale PID file
=================
*/
static qboolean Sys_WritePIDFile( const char *gamedir )
{
char *pidFile = Sys_PIDFileName( gamedir );
FILE *f;
qboolean stale = qfalse;
if( pidFile == NULL )
return qfalse;
// First, check if the pid file is already there
if( ( f = fopen( pidFile, "r" ) ) != NULL )
{
char pidBuffer[ 64 ] = { 0 };
int pid;
pid = fread( pidBuffer, sizeof( char ), sizeof( pidBuffer ) - 1, f );
fclose( f );
if(pid > 0)
{
pid = atoi( pidBuffer );
if( !Sys_PIDIsRunning( pid ) )
stale = qtrue;
}
else
stale = qtrue;
}
if( FS_CreatePath( pidFile ) ) {
return 0;
}
if( ( f = fopen( pidFile, "w" ) ) != NULL )
{
fprintf( f, "%d", Sys_PID( ) );
fclose( f );
}
else
Com_Printf( S_COLOR_YELLOW "Couldn't write %s.\n", pidFile );
return stale;
}
/*
=================
Sys_InitPIDFile
=================
*/
void Sys_InitPIDFile( const char *gamedir ) {
if( Sys_WritePIDFile( gamedir ) ) {
#ifndef DEDICATED
char message[1024];
char modName[MAX_OSPATH];
FS_GetModDescription( gamedir, modName, sizeof ( modName ) );
Q_CleanStr( modName );
Com_sprintf( message, sizeof (message), "The last time %s ran, "
"it didn't exit properly. This may be due to inappropriate video "
"settings. Would you like to start with \"safe\" video settings?", modName );
if( Sys_Dialog( DT_YES_NO, message, "Abnormal Exit" ) == DR_YES ) {
Cvar_Set( "com_abnormalExit", "1" );
}
#endif
}
}
/*
=================
Sys_Exit
Single exit point (regular exit or in case of error)
=================
*/
static __attribute__ ((noreturn)) void Sys_Exit( int exitCode )
{
CON_Shutdown( );
#ifndef DEDICATED
SDL_Quit( );
#endif
if( exitCode < 2 && com_fullyInitialized )
{
// Normal exit
Sys_RemovePIDFile( FS_GetCurrentGameDir() );
}
NET_Shutdown( );
Sys_PlatformExit( );
exit( exitCode );
}
/*
=================
Sys_Quit
=================
*/
void Sys_Quit( void )
{
Sys_Exit( 0 );
}
/*
=================
Sys_GetProcessorFeatures
=================
*/
cpuFeatures_t Sys_GetProcessorFeatures( void )
{
cpuFeatures_t features = 0;
#ifndef DEDICATED
if( SDL_HasRDTSC( ) ) features |= CF_RDTSC;
if( SDL_Has3DNow( ) ) features |= CF_3DNOW;
if( SDL_HasMMX( ) ) features |= CF_MMX;
if( SDL_HasSSE( ) ) features |= CF_SSE;
if( SDL_HasSSE2( ) ) features |= CF_SSE2;
if( SDL_HasAltiVec( ) ) features |= CF_ALTIVEC;
#endif
return features;
}
/*
=================
Sys_Init
=================
*/
void Sys_Init(void)
{
Cmd_AddCommand( "in_restart", Sys_In_Restart_f );
Cvar_Set( "arch", OS_STRING " " ARCH_STRING );
Cvar_Set( "username", Sys_GetCurrentUser( ) );
}
/*
=================
Sys_AnsiColorPrint
Transform Q3 colour codes to ANSI escape sequences
=================
*/
void Sys_AnsiColorPrint( const char *msg )
{
static char buffer[ MAXPRINTMSG ];
int length = 0;
static int q3ToAnsi[ 8 ] =
{
30, // COLOR_BLACK
31, // COLOR_RED
32, // COLOR_GREEN
33, // COLOR_YELLOW
34, // COLOR_BLUE
36, // COLOR_CYAN
35, // COLOR_MAGENTA
0 // COLOR_WHITE
};
while( *msg )
{
if( Q_IsColorString( msg ) || *msg == '\n' )
{
// First empty the buffer
if( length > 0 )
{
buffer[ length ] = '\0';
fputs( buffer, stderr );
length = 0;
}
if( *msg == '\n' )
{
// Issue a reset and then the newline
fputs( "\033[0m\n", stderr );
msg++;
}
else
{
// Print the color code
Com_sprintf( buffer, sizeof( buffer ), "\033[%dm",
q3ToAnsi[ ColorIndex( *( msg + 1 ) ) ] );
fputs( buffer, stderr );
msg += 2;
}
}
else
{
if( length >= MAXPRINTMSG - 1 )
break;
buffer[ length ] = *msg;
length++;
msg++;
}
}
// Empty anything still left in the buffer
if( length > 0 )
{
buffer[ length ] = '\0';
fputs( buffer, stderr );
}
}
/*
=================
Sys_Print
=================
*/
void Sys_Print( const char *msg )
{
CON_LogWrite( msg );
CON_Print( msg );
}
/*
=================
Sys_Error
=================
*/
void Sys_Error( const char *error, ... )
{
va_list argptr;
char string[1024];
va_start (argptr,error);
Q_vsnprintf (string, sizeof(string), error, argptr);
va_end (argptr);
Sys_ErrorDialog( string );
Sys_Exit( 3 );
}
#if 0
/*
=================
Sys_Warn
=================
*/
static __attribute__ ((format (printf, 1, 2))) void Sys_Warn( char *warning, ... )
{
va_list argptr;
char string[1024];
va_start (argptr,warning);
Q_vsnprintf (string, sizeof(string), warning, argptr);
va_end (argptr);
CON_Print( va( "Warning: %s", string ) );
}
#endif
/*
============
Sys_FileTime
returns -1 if not present
============
*/
int Sys_FileTime( char *path )
{
struct stat buf;
if (stat (path,&buf) == -1)
return -1;
return buf.st_mtime;
}
/*
=================
Sys_UnloadDll
=================
*/
void Sys_UnloadDll( void *dllHandle )
{
if( !dllHandle )
{
Com_Printf("Sys_UnloadDll(NULL)\n");
return;
}
Sys_UnloadLibrary(dllHandle);
}
/*
=================
Sys_LoadDll
First try to load library name from system library path,
from executable path, then fs_basepath.
=================
*/
void *Sys_LoadDll(const char *name, qboolean useSystemLib)
{
void *dllhandle;
if(useSystemLib)
Com_Printf("Trying to load \"%s\"...\n", name);
if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name)))
{
const char *topDir;
char libPath[MAX_OSPATH];
topDir = Sys_BinaryPath();
if(!*topDir)
topDir = ".";
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name);
if(!(dllhandle = Sys_LoadLibrary(libPath)))
{
const char *basePath = Cvar_VariableString("fs_basepath");
if(!basePath || !*basePath)
basePath = ".";
if(FS_FilenameCompare(topDir, basePath))
{
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name);
dllhandle = Sys_LoadLibrary(libPath);
}
if(!dllhandle)
Com_Printf("Loading \"%s\" failed\n", name);
}
}
return dllhandle;
}
/*
=================
Sys_LoadGameDll
Used to load a development dll instead of a virtual machine
=================
*/
void *Sys_LoadGameDll(const char *name,
intptr_t (QDECL **entryPoint)(intptr_t, ...),
intptr_t (*systemcalls)(intptr_t, ...))
{
void *libHandle;
void (*dllEntry)(intptr_t (*syscallptr)(intptr_t, ...));
assert(name);
Com_DPrintf( "Loading DLL file: %s\n", name);
libHandle = Sys_LoadLibrary(name);
if(!libHandle)
{
Com_Printf("Sys_LoadGameDll(%s) failed:\n\"%s\"\n", name, Sys_LibraryError());
return NULL;
}
dllEntry = Sys_LoadFunction( libHandle, "dllEntry" );
*entryPoint = Sys_LoadFunction( libHandle, "vmMain" );
if ( !*entryPoint || !dllEntry )
{
Com_Printf ( "Sys_LoadGameDll(%s) failed to find vmMain function:\n\"%s\" !\n", name, Sys_LibraryError( ) );
Sys_UnloadLibrary(libHandle);
return NULL;
}
Com_DPrintf ( "Sys_LoadGameDll(%s) found vmMain function at %p\n", name, *entryPoint );
dllEntry( systemcalls );
return libHandle;
}
/*
=================
Sys_ParseArgs
=================
*/
void Sys_ParseArgs( int argc, char **argv )
{
if( argc == 2 )
{
if( !strcmp( argv[1], "--version" ) ||
!strcmp( argv[1], "-v" ) )
{
const char* date = PRODUCT_DATE;
#ifdef DEDICATED
fprintf( stdout, Q3_VERSION " dedicated server (%s)\n", date );
#else
fprintf( stdout, Q3_VERSION " client (%s)\n", date );
#endif
Sys_Exit( 0 );
}
}
}
#ifndef DEFAULT_BASEDIR
# ifdef __APPLE__
# define DEFAULT_BASEDIR Sys_StripAppBundle(Sys_BinaryPath())
# else
# define DEFAULT_BASEDIR Sys_BinaryPath()
# endif
#endif
/*
=================
Sys_SigHandler
=================
*/
void Sys_SigHandler( int signal )
{
static qboolean signalcaught = qfalse;
if( signalcaught )
{
fprintf( stderr, "DOUBLE SIGNAL FAULT: Received signal %d, exiting...\n",
signal );
}
else
{
signalcaught = qtrue;
VM_Forced_Unload_Start();
#ifndef DEDICATED
CL_Shutdown(va("Received signal %d", signal), qtrue, qtrue);
#endif
SV_Shutdown(va("Received signal %d", signal) );
VM_Forced_Unload_Done();
}
if( signal == SIGTERM || signal == SIGINT )
Sys_Exit( 1 );
else
Sys_Exit( 2 );
}
/*
=================
main
=================
*/
int main( int argc, char **argv )
{
int i;
char commandLine[ MAX_STRING_CHARS ] = { 0 };
#ifndef DEDICATED
// SDL version check
// Compile time
# if !SDL_VERSION_ATLEAST(MINSDL_MAJOR,MINSDL_MINOR,MINSDL_PATCH)
# error A more recent version of SDL is required
# endif
// Run time
SDL_version ver;
SDL_GetVersion( &ver );
#define MINSDL_VERSION \
XSTRING(MINSDL_MAJOR) "." \
XSTRING(MINSDL_MINOR) "." \
XSTRING(MINSDL_PATCH)
if( SDL_VERSIONNUM( ver.major, ver.minor, ver.patch ) <
SDL_VERSIONNUM( MINSDL_MAJOR, MINSDL_MINOR, MINSDL_PATCH ) )
{
Sys_Dialog( DT_ERROR, va( "SDL version " MINSDL_VERSION " or greater is required, "
"but only version %d.%d.%d was found. You may be able to obtain a more recent copy "
"from http://www.libsdl.org/.", ver.major, ver.minor, ver.patch ), "SDL Library Too Old" );
Sys_Exit( 1 );
}
#endif
Sys_PlatformInit( );
// Set the initial time base
Sys_Milliseconds( );
#ifdef __APPLE__
// This is passed if we are launched by double-clicking
if ( argc >= 2 && Q_strncmp ( argv[1], "-psn", 4 ) == 0 )
argc = 1;
#endif
Sys_ParseArgs( argc, argv );
Sys_SetBinaryPath( Sys_Dirname( argv[ 0 ] ) );
Sys_SetDefaultInstallPath( DEFAULT_BASEDIR );
// Concatenate the command line for passing to Com_Init
for( i = 1; i < argc; i++ )
{
const qboolean containsSpaces = strchr(argv[i], ' ') != NULL;
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), argv[ i ] );
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), " " );
}
Com_Init( commandLine );
NET_Init( );
CON_Init( );
signal( SIGILL, Sys_SigHandler );
signal( SIGFPE, Sys_SigHandler );
signal( SIGSEGV, Sys_SigHandler );
signal( SIGTERM, Sys_SigHandler );
signal( SIGINT, Sys_SigHandler );
while( 1 )
{
IN_Frame( );
Com_Frame( );
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3233_5 |
crossvul-cpp_data_bad_3232_1 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
Copyright (C) 2005 Stuart Dalton (badcdev@gmail.com)
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "snd_local.h"
#include "snd_codec.h"
#include "client.h"
#ifdef USE_OPENAL
#include "qal.h"
// Console variables specific to OpenAL
cvar_t *s_alPrecache;
cvar_t *s_alGain;
cvar_t *s_alSources;
cvar_t *s_alDopplerFactor;
cvar_t *s_alDopplerSpeed;
cvar_t *s_alMinDistance;
cvar_t *s_alMaxDistance;
cvar_t *s_alRolloff;
cvar_t *s_alGraceDistance;
cvar_t *s_alDriver;
cvar_t *s_alDevice;
cvar_t *s_alInputDevice;
cvar_t *s_alAvailableDevices;
cvar_t *s_alAvailableInputDevices;
cvar_t *s_alTalkAnims;
static qboolean enumeration_ext = qfalse;
static qboolean enumeration_all_ext = qfalse;
#ifdef USE_VOIP
static qboolean capture_ext = qfalse;
#endif
/*
=================
S_AL_Format
=================
*/
static
ALuint S_AL_Format(int width, int channels)
{
ALuint format = AL_FORMAT_MONO16;
// Work out format
if(width == 1)
{
if(channels == 1)
format = AL_FORMAT_MONO8;
else if(channels == 2)
format = AL_FORMAT_STEREO8;
}
else if(width == 2)
{
if(channels == 1)
format = AL_FORMAT_MONO16;
else if(channels == 2)
format = AL_FORMAT_STEREO16;
}
return format;
}
/*
=================
S_AL_ErrorMsg
=================
*/
static const char *S_AL_ErrorMsg(ALenum error)
{
switch(error)
{
case AL_NO_ERROR:
return "No error";
case AL_INVALID_NAME:
return "Invalid name";
case AL_INVALID_ENUM:
return "Invalid enumerator";
case AL_INVALID_VALUE:
return "Invalid value";
case AL_INVALID_OPERATION:
return "Invalid operation";
case AL_OUT_OF_MEMORY:
return "Out of memory";
default:
return "Unknown error";
}
}
/*
=================
S_AL_ClearError
=================
*/
static void S_AL_ClearError( qboolean quiet )
{
int error = qalGetError();
if( quiet )
return;
if(error != AL_NO_ERROR)
{
Com_DPrintf(S_COLOR_YELLOW "WARNING: unhandled AL error: %s\n",
S_AL_ErrorMsg(error));
}
}
//===========================================================================
typedef struct alSfx_s
{
char filename[MAX_QPATH];
ALuint buffer; // OpenAL buffer
snd_info_t info; // information for this sound like rate, sample count..
qboolean isDefault; // Couldn't be loaded - use default FX
qboolean isDefaultChecked; // Sound has been check if it isDefault
qboolean inMemory; // Sound is stored in memory
qboolean isLocked; // Sound is locked (can not be unloaded)
int lastUsedTime; // Time last used
int loopCnt; // number of loops using this sfx
int loopActiveCnt; // number of playing loops using this sfx
int masterLoopSrc; // All other sources looping this buffer are synced to this master src
} alSfx_t;
static qboolean alBuffersInitialised = qfalse;
// Sound effect storage, data structures
#define MAX_SFX 4096
static alSfx_t knownSfx[MAX_SFX];
static sfxHandle_t numSfx = 0;
static sfxHandle_t default_sfx;
/*
=================
S_AL_BufferFindFree
Find a free handle
=================
*/
static sfxHandle_t S_AL_BufferFindFree( void )
{
int i;
for(i = 0; i < MAX_SFX; i++)
{
// Got one
if(knownSfx[i].filename[0] == '\0')
{
if(i >= numSfx)
numSfx = i + 1;
return i;
}
}
// Shit...
Com_Error(ERR_FATAL, "S_AL_BufferFindFree: No free sound handles");
return -1;
}
/*
=================
S_AL_BufferFind
Find a sound effect if loaded, set up a handle otherwise
=================
*/
static sfxHandle_t S_AL_BufferFind(const char *filename)
{
// Look it up in the table
sfxHandle_t sfx = -1;
int i;
if ( !filename ) {
//Com_Error( ERR_FATAL, "Sound name is NULL" );
filename = "*default*";
}
if ( !filename[0] ) {
//Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is empty\n" );
filename = "*default*";
}
if ( strlen( filename ) >= MAX_QPATH ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is too long: %s\n", filename );
return 0;
}
for(i = 0; i < numSfx; i++)
{
if(!Q_stricmp(knownSfx[i].filename, filename))
{
sfx = i;
break;
}
}
// Not found in table?
if(sfx == -1)
{
alSfx_t *ptr;
sfx = S_AL_BufferFindFree();
// Clear and copy the filename over
ptr = &knownSfx[sfx];
memset(ptr, 0, sizeof(*ptr));
ptr->masterLoopSrc = -1;
strcpy(ptr->filename, filename);
}
// Return the handle
return sfx;
}
/*
=================
S_AL_BufferUseDefault
=================
*/
static void S_AL_BufferUseDefault(sfxHandle_t sfx)
{
if(sfx == default_sfx)
Com_Error(ERR_FATAL, "Can't load default sound effect %s", knownSfx[sfx].filename);
// Com_Printf( S_COLOR_YELLOW "WARNING: Using default sound for %s\n", knownSfx[sfx].filename);
knownSfx[sfx].isDefault = qtrue;
knownSfx[sfx].buffer = knownSfx[default_sfx].buffer;
}
/*
=================
S_AL_BufferUnload
=================
*/
static void S_AL_BufferUnload(sfxHandle_t sfx)
{
if(knownSfx[sfx].filename[0] == '\0')
return;
if(!knownSfx[sfx].inMemory)
return;
// Delete it
S_AL_ClearError( qfalse );
qalDeleteBuffers(1, &knownSfx[sfx].buffer);
if(qalGetError() != AL_NO_ERROR)
Com_Printf( S_COLOR_RED "ERROR: Can't delete sound buffer for %s\n",
knownSfx[sfx].filename);
knownSfx[sfx].inMemory = qfalse;
}
/*
=================
S_AL_BufferEvict
=================
*/
static qboolean S_AL_BufferEvict( void )
{
int i, oldestBuffer = -1;
int oldestTime = Sys_Milliseconds( );
for( i = 0; i < numSfx; i++ )
{
if( !knownSfx[ i ].filename[ 0 ] )
continue;
if( !knownSfx[ i ].inMemory )
continue;
if( knownSfx[ i ].lastUsedTime < oldestTime )
{
oldestTime = knownSfx[ i ].lastUsedTime;
oldestBuffer = i;
}
}
if( oldestBuffer >= 0 )
{
S_AL_BufferUnload( oldestBuffer );
return qtrue;
}
else
return qfalse;
}
/*
=================
S_AL_GenBuffers
=================
*/
static qboolean S_AL_GenBuffers(ALsizei numBuffers, ALuint *buffers, const char *name)
{
ALenum error;
S_AL_ClearError( qfalse );
qalGenBuffers( numBuffers, buffers );
error = qalGetError();
// If we ran out of buffers, start evicting the least recently used sounds
while( error == AL_INVALID_VALUE )
{
if( !S_AL_BufferEvict( ) )
{
Com_Printf( S_COLOR_RED "ERROR: Out of audio buffers\n");
return qfalse;
}
// Try again
S_AL_ClearError( qfalse );
qalGenBuffers( numBuffers, buffers );
error = qalGetError();
}
if( error != AL_NO_ERROR )
{
Com_Printf( S_COLOR_RED "ERROR: Can't create a sound buffer for %s - %s\n",
name, S_AL_ErrorMsg(error));
return qfalse;
}
return qtrue;
}
/*
=================
S_AL_BufferLoad
=================
*/
static void S_AL_BufferLoad(sfxHandle_t sfx, qboolean cache)
{
ALenum error;
ALuint format;
void *data;
snd_info_t info;
alSfx_t *curSfx = &knownSfx[sfx];
// Nothing?
if(curSfx->filename[0] == '\0')
return;
// Player SFX
if(curSfx->filename[0] == '*')
return;
// Already done?
if((curSfx->inMemory) || (curSfx->isDefault) || (!cache && curSfx->isDefaultChecked))
return;
// Try to load
data = S_CodecLoad(curSfx->filename, &info);
if(!data)
{
S_AL_BufferUseDefault(sfx);
return;
}
curSfx->isDefaultChecked = qtrue;
if (!cache)
{
// Don't create AL cache
Hunk_FreeTempMemory(data);
return;
}
format = S_AL_Format(info.width, info.channels);
// Create a buffer
if (!S_AL_GenBuffers(1, &curSfx->buffer, curSfx->filename))
{
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
return;
}
// Fill the buffer
if( info.size == 0 )
{
// We have no data to buffer, so buffer silence
byte dummyData[ 2 ] = { 0 };
qalBufferData(curSfx->buffer, AL_FORMAT_MONO16, (void *)dummyData, 2, 22050);
}
else
qalBufferData(curSfx->buffer, format, data, info.size, info.rate);
error = qalGetError();
// If we ran out of memory, start evicting the least recently used sounds
while(error == AL_OUT_OF_MEMORY)
{
if( !S_AL_BufferEvict( ) )
{
qalDeleteBuffers(1, &curSfx->buffer);
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
Com_Printf( S_COLOR_RED "ERROR: Out of memory loading %s\n", curSfx->filename);
return;
}
// Try load it again
qalBufferData(curSfx->buffer, format, data, info.size, info.rate);
error = qalGetError();
}
// Some other error condition
if(error != AL_NO_ERROR)
{
qalDeleteBuffers(1, &curSfx->buffer);
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
Com_Printf( S_COLOR_RED "ERROR: Can't fill sound buffer for %s - %s\n",
curSfx->filename, S_AL_ErrorMsg(error));
return;
}
curSfx->info = info;
// Free the memory
Hunk_FreeTempMemory(data);
// Woo!
curSfx->inMemory = qtrue;
}
/*
=================
S_AL_BufferUse
=================
*/
static
void S_AL_BufferUse(sfxHandle_t sfx)
{
if(knownSfx[sfx].filename[0] == '\0')
return;
if((!knownSfx[sfx].inMemory) && (!knownSfx[sfx].isDefault))
S_AL_BufferLoad(sfx, qtrue);
knownSfx[sfx].lastUsedTime = Sys_Milliseconds();
}
/*
=================
S_AL_BufferInit
=================
*/
static
qboolean S_AL_BufferInit( void )
{
if(alBuffersInitialised)
return qtrue;
// Clear the hash table, and SFX table
memset(knownSfx, 0, sizeof(knownSfx));
numSfx = 0;
// Load the default sound, and lock it
default_sfx = S_AL_BufferFind( "***DEFAULT***" );
S_AL_BufferUse(default_sfx);
knownSfx[default_sfx].isLocked = qtrue;
// All done
alBuffersInitialised = qtrue;
return qtrue;
}
/*
=================
S_AL_BufferShutdown
=================
*/
static
void S_AL_BufferShutdown( void )
{
int i;
if(!alBuffersInitialised)
return;
// Unlock the default sound effect
knownSfx[default_sfx].isLocked = qfalse;
// Free all used effects
for(i = 0; i < numSfx; i++)
S_AL_BufferUnload(i);
// Clear the tables
numSfx = 0;
// All undone
alBuffersInitialised = qfalse;
}
/*
=================
S_AL_RegisterSound
=================
*/
static
sfxHandle_t S_AL_RegisterSound( const char *sample, qboolean compressed )
{
sfxHandle_t sfx = S_AL_BufferFind(sample);
if((!knownSfx[sfx].inMemory) && (!knownSfx[sfx].isDefault))
S_AL_BufferLoad(sfx, s_alPrecache->integer);
knownSfx[sfx].lastUsedTime = Com_Milliseconds();
if (knownSfx[sfx].isDefault) {
return 0;
}
return sfx;
}
/*
=================
S_AL_BufferGet
Return's a sfx's buffer
=================
*/
static
ALuint S_AL_BufferGet(sfxHandle_t sfx)
{
return knownSfx[sfx].buffer;
}
//===========================================================================
typedef struct src_s
{
ALuint alSource; // OpenAL source object
sfxHandle_t sfx; // Sound effect in use
int lastUsedTime; // Last time used
alSrcPriority_t priority; // Priority
int entity; // Owning entity (-1 if none)
int channel; // Associated channel (-1 if none)
qboolean isActive; // Is this source currently in use?
qboolean isPlaying; // Is this source currently playing, or stopped?
qboolean isLocked; // This is locked (un-allocatable)
qboolean isLooping; // Is this a looping effect (attached to an entity)
qboolean isTracking; // Is this object tracking its owner
qboolean isStream; // Is this source a stream
float curGain; // gain employed if source is within maxdistance.
float scaleGain; // Last gain value for this source. 0 if muted.
float lastTimePos; // On stopped loops, the last position in the buffer
int lastSampleTime; // Time when this was stopped
vec3_t loopSpeakerPos; // Origin of the loop speaker
qboolean local; // Is this local (relative to the cam)
int flags; // flags from StartSoundEx
} src_t;
#ifdef __APPLE__
#define MAX_SRC 128
#else
#define MAX_SRC 256
#endif
static src_t srcList[MAX_SRC];
static int srcCount = 0;
static int srcActiveCnt = 0;
static qboolean alSourcesInitialised = qfalse;
static int lastListenerNumber = -1;
static vec3_t lastListenerOrigin = { 0.0f, 0.0f, 0.0f };
typedef struct sentity_s
{
vec3_t origin;
qboolean srcAllocated; // If a src_t has been allocated to this entity
int srcIndex;
qboolean loopAddedThisFrame;
alSrcPriority_t loopPriority;
sfxHandle_t loopSfx;
qboolean startLoopingSound;
} sentity_t;
static sentity_t entityList[MAX_GENTITIES];
/*
=================
S_AL_SanitiseVector
=================
*/
#define S_AL_SanitiseVector(v) _S_AL_SanitiseVector(v,__LINE__)
static void _S_AL_SanitiseVector( vec3_t v, int line )
{
if( Q_isnan( v[ 0 ] ) || Q_isnan( v[ 1 ] ) || Q_isnan( v[ 2 ] ) )
{
Com_DPrintf( S_COLOR_YELLOW "WARNING: vector with one or more NaN components "
"being passed to OpenAL at %s:%d -- zeroing\n", __FILE__, line );
VectorClear( v );
}
}
/*
=================
S_AL_Gain
Set gain to 0 if muted, otherwise set it to given value.
=================
*/
static void S_AL_Gain(ALuint source, float gainval)
{
if(s_muted->integer)
qalSourcef(source, AL_GAIN, 0.0f);
else
qalSourcef(source, AL_GAIN, gainval);
}
/*
=================
S_AL_ScaleGain
Adapt the gain if necessary to get a quicker fadeout when the source is too far away.
=================
*/
static void S_AL_ScaleGain(src_t *chksrc, vec3_t origin)
{
float distance;
if(!chksrc->local)
distance = Distance(origin, lastListenerOrigin);
// If we exceed a certain distance, scale the gain linearly until the sound
// vanishes into nothingness.
if(!chksrc->local && (distance -= s_alMaxDistance->value) > 0)
{
float scaleFactor;
if(distance >= s_alGraceDistance->value)
scaleFactor = 0.0f;
else
scaleFactor = 1.0f - distance / s_alGraceDistance->value;
scaleFactor *= chksrc->curGain;
if(chksrc->scaleGain != scaleFactor)
{
chksrc->scaleGain = scaleFactor;
S_AL_Gain(chksrc->alSource, chksrc->scaleGain);
}
}
else if(chksrc->scaleGain != chksrc->curGain)
{
chksrc->scaleGain = chksrc->curGain;
S_AL_Gain(chksrc->alSource, chksrc->scaleGain);
}
}
/*
=================
S_AL_HearingThroughEntity
Also see S_Base_HearingThroughEntity
=================
*/
static qboolean S_AL_HearingThroughEntity( int entityNum )
{
float distanceSq;
if( lastListenerNumber == entityNum )
{
// This is an outrageous hack to detect
// whether or not the player is rendering in third person or not. We can't
// ask the renderer because the renderer has no notion of entities and we
// can't ask cgame since that would involve changing the API and hence mod
// compatibility. I don't think there is any way around this, but I'll leave
// the FIXME just in case anyone has a bright idea.
distanceSq = DistanceSquared(
entityList[ entityNum ].origin,
lastListenerOrigin );
if( distanceSq > THIRD_PERSON_THRESHOLD_SQ )
return qfalse; //we're the player, but third person
else
return qtrue; //we're the player
}
else
return qfalse; //not the player
}
/*
=================
S_AL_SrcInit
=================
*/
static
qboolean S_AL_SrcInit( void )
{
int i;
int limit;
// Clear the sources data structure
memset(srcList, 0, sizeof(srcList));
srcCount = 0;
srcActiveCnt = 0;
// Cap s_alSources to MAX_SRC
limit = s_alSources->integer;
if(limit > MAX_SRC)
limit = MAX_SRC;
else if(limit < 16)
limit = 16;
S_AL_ClearError( qfalse );
// Allocate as many sources as possible
for(i = 0; i < limit; i++)
{
qalGenSources(1, &srcList[i].alSource);
if(qalGetError() != AL_NO_ERROR)
break;
srcCount++;
}
alSourcesInitialised = qtrue;
return qtrue;
}
/*
=================
S_AL_SrcShutdown
=================
*/
static
void S_AL_SrcShutdown( void )
{
int i;
src_t *curSource;
if(!alSourcesInitialised)
return;
// Destroy all the sources
for(i = 0; i < srcCount; i++)
{
curSource = &srcList[i];
if(curSource->isLocked)
{
srcList[i].isLocked = qfalse;
Com_DPrintf( S_COLOR_YELLOW "WARNING: Source %d was locked\n", i);
}
if(curSource->entity > 0)
entityList[curSource->entity].srcAllocated = qfalse;
qalSourceStop(srcList[i].alSource);
qalDeleteSources(1, &srcList[i].alSource);
}
memset(srcList, 0, sizeof(srcList));
memset( s_entityTalkAmplitude, 0, sizeof( s_entityTalkAmplitude ) );
alSourcesInitialised = qfalse;
}
/*
=================
S_AL_SrcSetup
=================
*/
static void S_AL_SrcSetup(srcHandle_t src, sfxHandle_t sfx, alSrcPriority_t priority,
int entity, int channel, int flags, qboolean local)
{
src_t *curSource;
// Set up src struct
curSource = &srcList[src];
curSource->lastUsedTime = Sys_Milliseconds();
curSource->sfx = sfx;
curSource->priority = priority;
curSource->entity = entity;
curSource->channel = channel;
curSource->isPlaying = qfalse;
curSource->isLocked = qfalse;
curSource->isLooping = qfalse;
curSource->isTracking = qfalse;
curSource->isStream = qfalse;
curSource->curGain = s_alGain->value * s_volume->value;
curSource->scaleGain = curSource->curGain;
curSource->local = local;
curSource->flags = flags;
// Set up OpenAL source
if(sfx >= 0)
{
// Mark the SFX as used, and grab the raw AL buffer
S_AL_BufferUse(sfx);
qalSourcei(curSource->alSource, AL_BUFFER, S_AL_BufferGet(sfx));
}
qalSourcef(curSource->alSource, AL_PITCH, 1.0f);
S_AL_Gain(curSource->alSource, curSource->curGain);
qalSourcefv(curSource->alSource, AL_POSITION, vec3_origin);
qalSourcefv(curSource->alSource, AL_VELOCITY, vec3_origin);
qalSourcei(curSource->alSource, AL_LOOPING, AL_FALSE);
qalSourcef(curSource->alSource, AL_REFERENCE_DISTANCE, s_alMinDistance->value);
if(local)
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_TRUE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, 0.0f);
}
else
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_FALSE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
}
}
/*
=================
S_AL_SaveLoopPos
Remove given source as loop master if it is the master and hand off master status to another source in this case.
=================
*/
static void S_AL_SaveLoopPos(src_t *dest, ALuint alSource)
{
int error;
S_AL_ClearError( qfalse );
qalGetSourcef(alSource, AL_SEC_OFFSET, &dest->lastTimePos);
if((error = qalGetError()) != AL_NO_ERROR)
{
// Old OpenAL implementations don't support AL_SEC_OFFSET
if(error != AL_INVALID_ENUM)
{
Com_Printf(S_COLOR_YELLOW "WARNING: Could not get time offset for alSource %d: %s\n",
alSource, S_AL_ErrorMsg(error));
}
dest->lastTimePos = -1;
}
else
dest->lastSampleTime = Sys_Milliseconds();
}
/*
=================
S_AL_NewLoopMaster
Remove given source as loop master if it is the master and hand off master status to another source in this case.
=================
*/
static void S_AL_NewLoopMaster(src_t *rmSource, qboolean iskilled)
{
int index;
src_t *curSource = NULL;
alSfx_t *curSfx;
curSfx = &knownSfx[rmSource->sfx];
if(rmSource->isPlaying)
curSfx->loopActiveCnt--;
if(iskilled)
curSfx->loopCnt--;
if(curSfx->loopCnt)
{
if(rmSource->priority == SRCPRI_ENTITY)
{
if(!iskilled && rmSource->isPlaying)
{
// only sync ambient loops...
// It makes more sense to have sounds for weapons/projectiles unsynced
S_AL_SaveLoopPos(rmSource, rmSource->alSource);
}
}
else if(rmSource == &srcList[curSfx->masterLoopSrc])
{
int firstInactive = -1;
// Only if rmSource was the master and if there are still playing loops for
// this sound will we need to find a new master.
if(iskilled || curSfx->loopActiveCnt)
{
for(index = 0; index < srcCount; index++)
{
curSource = &srcList[index];
if(curSource->sfx == rmSource->sfx && curSource != rmSource &&
curSource->isActive && curSource->isLooping && curSource->priority == SRCPRI_AMBIENT)
{
if(curSource->isPlaying)
{
curSfx->masterLoopSrc = index;
break;
}
else if(firstInactive < 0)
firstInactive = index;
}
}
}
if(!curSfx->loopActiveCnt)
{
if(firstInactive < 0)
{
if(iskilled)
{
curSfx->masterLoopSrc = -1;
return;
}
else
curSource = rmSource;
}
else
curSource = &srcList[firstInactive];
if(rmSource->isPlaying)
{
// this was the last not stopped source, save last sample position + time
S_AL_SaveLoopPos(curSource, rmSource->alSource);
}
else
{
// second case: all loops using this sound have stopped due to listener being of of range,
// and now the inactive master gets deleted. Just move over the soundpos settings to the
// new master.
curSource->lastTimePos = rmSource->lastTimePos;
curSource->lastSampleTime = rmSource->lastSampleTime;
}
}
}
}
else
curSfx->masterLoopSrc = -1;
}
/*
=================
S_AL_SrcKill
=================
*/
static void S_AL_SrcKill(srcHandle_t src)
{
src_t *curSource = &srcList[src];
// I'm not touching it. Unlock it first.
if(curSource->isLocked)
return;
// Remove the entity association and loop master status
if(curSource->isLooping)
{
curSource->isLooping = qfalse;
if(curSource->entity != -1)
{
sentity_t *curEnt = &entityList[curSource->entity];
curEnt->srcAllocated = qfalse;
curEnt->srcIndex = -1;
curEnt->loopAddedThisFrame = qfalse;
curEnt->startLoopingSound = qfalse;
}
S_AL_NewLoopMaster(curSource, qtrue);
}
// Stop it if it's playing
if(curSource->isPlaying)
{
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
// Detach any buffers
qalSourcei(curSource->alSource, AL_BUFFER, 0);
curSource->sfx = 0;
curSource->lastUsedTime = 0;
curSource->priority = 0;
curSource->entity = -1;
curSource->channel = -1;
if(curSource->isActive)
{
curSource->isActive = qfalse;
srcActiveCnt--;
}
curSource->isLocked = qfalse;
curSource->isTracking = qfalse;
curSource->local = qfalse;
}
/*
=================
S_AL_SrcAlloc
=================
*/
static
srcHandle_t S_AL_SrcAlloc( sfxHandle_t sfx, alSrcPriority_t priority, int entnum, int channel, int flags )
{
int i;
int empty = -1;
int weakest = -1;
int weakest_time = Sys_Milliseconds();
int weakest_pri = 999;
float weakest_gain = 1000.0;
qboolean weakest_isplaying = qtrue;
int weakest_numloops = 0;
src_t *curSource;
qboolean cutDuplicateSound = qfalse;
for(i = 0; i < srcCount; i++)
{
curSource = &srcList[i];
// If it's locked, we aren't even going to look at it
if(curSource->isLocked)
continue;
// Is it empty or not?
if(!curSource->isActive)
{
if (empty == -1)
empty = i;
break;
}
if(curSource->isPlaying)
{
if(weakest_isplaying && curSource->priority < priority &&
(curSource->priority < weakest_pri ||
(!curSource->isLooping && (curSource->scaleGain < weakest_gain || curSource->lastUsedTime < weakest_time))))
{
// If it has lower priority, is fainter or older, flag it as weak
// the last two values are only compared if it's not a looping sound, because we want to prevent two
// loops (loops are added EVERY frame) fighting for a slot
weakest_pri = curSource->priority;
weakest_time = curSource->lastUsedTime;
weakest_gain = curSource->scaleGain;
weakest = i;
}
}
else
{
weakest_isplaying = qfalse;
if(weakest < 0 ||
knownSfx[curSource->sfx].loopCnt > weakest_numloops ||
curSource->priority < weakest_pri ||
curSource->lastUsedTime < weakest_time)
{
// Sources currently not playing of course have lowest priority
// also try to always keep at least one loop master for every loop sound
weakest_pri = curSource->priority;
weakest_time = curSource->lastUsedTime;
weakest_numloops = knownSfx[curSource->sfx].loopCnt;
weakest = i;
}
}
// shut off other sounds on this channel if necessary
if((curSource->entity == entnum) && curSource->sfx > 0 && (curSource->channel == channel))
{
// currently apply only to non-looping sounds
if ( curSource->isLooping ) {
continue;
}
// cutoff all on channel
if ( flags & SND_CUTOFF_ALL ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
if ( curSource->flags & SND_NOCUT ) {
continue;
}
// RF, let client voice sounds be overwritten
if ( entnum < MAX_CLIENTS && curSource->channel != -1 && curSource->channel != CHAN_AUTO && curSource->channel != CHAN_WEAPON ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
// cutoff sounds that expect to be overwritten
if ( curSource->flags & SND_OKTOCUT ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
// cutoff 'weak' sounds on channel
if ( flags & SND_CUTOFF ) {
if ( curSource->flags & SND_REQUESTCUT ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
}
// re-use channel if applicable
if ( curSource->channel != -1 && curSource->channel != CHAN_AUTO && curSource->sfx == sfx && !cutDuplicateSound ) {
cutDuplicateSound = qtrue;
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
}
}
if(empty == -1)
empty = weakest;
if(empty >= 0)
{
S_AL_SrcKill(empty);
srcList[empty].isActive = qtrue;
srcActiveCnt++;
}
return empty;
}
/*
=================
S_AL_SrcFind
Finds an active source with matching entity and channel numbers
Returns -1 if there isn't one
=================
*/
#if 0
static
srcHandle_t S_AL_SrcFind(int entnum, int channel)
{
int i;
for(i = 0; i < srcCount; i++)
{
if(!srcList[i].isActive)
continue;
if((srcList[i].entity == entnum) && (srcList[i].channel == channel))
return i;
}
return -1;
}
#endif
/*
=================
S_AL_SrcLock
Locked sources will not be automatically reallocated or managed
=================
*/
static
void S_AL_SrcLock(srcHandle_t src)
{
srcList[src].isLocked = qtrue;
}
/*
=================
S_AL_SrcUnlock
Once unlocked, the source may be reallocated again
=================
*/
static
void S_AL_SrcUnlock(srcHandle_t src)
{
srcList[src].isLocked = qfalse;
}
/*
=================
S_AL_UpdateEntityPosition
=================
*/
static
void S_AL_UpdateEntityPosition( int entityNum, const vec3_t origin )
{
vec3_t sanOrigin;
VectorCopy( origin, sanOrigin );
S_AL_SanitiseVector( sanOrigin );
if ( entityNum < 0 || entityNum >= MAX_GENTITIES )
Com_Error( ERR_DROP, "S_UpdateEntityPosition: bad entitynum %i", entityNum );
VectorCopy( sanOrigin, entityList[entityNum].origin );
}
/*
=================
S_AL_CheckInput
Check whether input values from mods are out of range.
Necessary for i.g. Western Quake3 mod which is buggy.
=================
*/
static qboolean S_AL_CheckInput(int entityNum, sfxHandle_t sfx)
{
if (entityNum < 0 || entityNum >= MAX_GENTITIES)
Com_Error(ERR_DROP, "ERROR: S_AL_CheckInput: bad entitynum %i", entityNum);
if (sfx < 0 || sfx >= numSfx)
{
Com_Printf(S_COLOR_RED "ERROR: S_AL_CheckInput: handle %i out of range\n", sfx);
return qtrue;
}
return qfalse;
}
/*
=================
S_AL_StartLocalSound
Play a local (non-spatialized) sound effect
=================
*/
static
void S_AL_StartLocalSound(sfxHandle_t sfx, int channel)
{
srcHandle_t src;
if(S_AL_CheckInput(0, sfx))
return;
// Try to grab a source
src = S_AL_SrcAlloc(sfx, SRCPRI_LOCAL, -1, channel, 0);
if(src == -1)
return;
// Set up the effect
S_AL_SrcSetup(src, sfx, SRCPRI_LOCAL, -1, channel, 0, qtrue);
// Start it playing
srcList[src].isPlaying = qtrue;
qalSourcePlay(srcList[src].alSource);
}
/*
=================
S_AL_MainStartSound
Play a one-shot sound effect
=================
*/
static void S_AL_MainStartSound( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx, int flags )
{
vec3_t sorigin;
srcHandle_t src;
src_t *curSource;
if(origin)
{
if(S_AL_CheckInput(0, sfx))
return;
VectorCopy(origin, sorigin);
}
else
{
if(S_AL_CheckInput(entnum, sfx))
return;
if(S_AL_HearingThroughEntity(entnum))
{
S_AL_StartLocalSound(sfx, entchannel);
return;
}
VectorCopy(entityList[entnum].origin, sorigin);
}
S_AL_SanitiseVector(sorigin);
if((srcActiveCnt > 5 * srcCount / 3) &&
(DistanceSquared(sorigin, lastListenerOrigin) >=
(s_alMaxDistance->value + s_alGraceDistance->value) * (s_alMaxDistance->value + s_alGraceDistance->value)))
{
// We're getting tight on sources and source is not within hearing distance so don't add it
return;
}
// Talk anims default to ZERO amplitude
if ( entchannel == CHAN_VOICE )
memset( s_entityTalkAmplitude, 0, sizeof( s_entityTalkAmplitude ) );
if ( entnum < MAX_CLIENTS && entchannel == CHAN_VOICE )
{
s_entityTalkAmplitude[entnum] = (unsigned char)(s_alTalkAnims->integer);
}
// Try to grab a source
src = S_AL_SrcAlloc(sfx, SRCPRI_ONESHOT, entnum, entchannel, flags);
if(src == -1)
return;
S_AL_SrcSetup(src, sfx, SRCPRI_ONESHOT, entnum, entchannel, flags, qfalse);
curSource = &srcList[src];
if(!origin)
curSource->isTracking = qtrue;
qalSourcefv(curSource->alSource, AL_POSITION, sorigin );
S_AL_ScaleGain(curSource, sorigin);
// Start it playing
curSource->isPlaying = qtrue;
qalSourcePlay(curSource->alSource);
}
/*
=================
S_AL_StartSound
=================
*/
static void S_AL_StartSound( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx )
{
S_AL_MainStartSound( origin, entnum, entchannel, sfx, 0 );
}
/*
=================
S_AL_StartSoundEx
=================
*/
static void S_AL_StartSoundEx( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx, int flags )
{
// RF, we have lots of NULL sounds using up valuable channels, so just ignore them
if ( !sfx && entchannel != CHAN_WEAPON ) { // let null weapon sounds try to play. they kill any weapon sounds playing when a guy dies
return;
}
// RF, make the call now, or else we could override following streaming sounds in the same frame, due to the delay
S_AL_MainStartSound( origin, entnum, entchannel, sfx, flags );
}
/*
=================
S_AL_ClearLoopingSounds
=================
*/
static
void S_AL_ClearLoopingSounds( qboolean killall )
{
int i;
for(i = 0; i < srcCount; i++)
{
if((srcList[i].isLooping) && (srcList[i].entity != -1))
entityList[srcList[i].entity].loopAddedThisFrame = qfalse;
}
}
/*
=================
S_AL_SrcLoop
=================
*/
static void S_AL_SrcLoop( alSrcPriority_t priority, sfxHandle_t sfx,
const vec3_t origin, const vec3_t velocity, int entityNum, int volume )
{
int src;
sentity_t *sent = &entityList[ entityNum ];
src_t *curSource;
vec3_t sorigin, svelocity;
if( entityNum < 0 || entityNum >= MAX_GENTITIES )
return;
if(S_AL_CheckInput(entityNum, sfx))
return;
// Do we need to allocate a new source for this entity
if( !sent->srcAllocated )
{
// Try to get a channel
src = S_AL_SrcAlloc( sfx, priority, entityNum, -1, 0 );
if( src == -1 )
{
Com_DPrintf( S_COLOR_YELLOW "WARNING: Failed to allocate source "
"for loop sfx %d on entity %d\n", sfx, entityNum );
return;
}
curSource = &srcList[src];
sent->startLoopingSound = qtrue;
curSource->lastTimePos = -1.0;
curSource->lastSampleTime = Sys_Milliseconds();
}
else
{
src = sent->srcIndex;
curSource = &srcList[src];
}
sent->srcAllocated = qtrue;
sent->srcIndex = src;
sent->loopPriority = priority;
sent->loopSfx = sfx;
// If this is not set then the looping sound is stopped.
sent->loopAddedThisFrame = qtrue;
// UGH
// These lines should be called via S_AL_SrcSetup, but we
// can't call that yet as it buffers sfxes that may change
// with subsequent calls to S_AL_SrcLoop
curSource->entity = entityNum;
curSource->isLooping = qtrue;
if( S_AL_HearingThroughEntity( entityNum ) )
{
curSource->local = qtrue;
VectorClear(sorigin);
if ( volume > 255 ) {
volume = 255;
} else if ( volume < 0 ) {
volume = 0;
}
qalSourcefv(curSource->alSource, AL_POSITION, sorigin);
qalSourcefv(curSource->alSource, AL_VELOCITY, vec3_origin);
S_AL_Gain(curSource->alSource, volume / 255.0f);
}
else
{
curSource->local = qfalse;
if(origin)
VectorCopy(origin, sorigin);
else
VectorCopy(sent->origin, sorigin);
S_AL_SanitiseVector(sorigin);
VectorCopy(sorigin, curSource->loopSpeakerPos);
if(velocity)
{
VectorCopy(velocity, svelocity);
S_AL_SanitiseVector(svelocity);
}
else
VectorClear(svelocity);
qalSourcefv(curSource->alSource, AL_POSITION, (ALfloat *) sorigin);
qalSourcefv(curSource->alSource, AL_VELOCITY, (ALfloat *) svelocity);
}
}
/*
=================
S_AL_AddLoopingSound
=================
*/
static void S_AL_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, const int range, sfxHandle_t sfx, int volume)
{
S_AL_SrcLoop(SRCPRI_ENTITY, sfx, origin, velocity, entityNum, volume);
}
/*
=================
S_AL_AddRealLoopingSound
=================
*/
static void S_AL_AddRealLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, const int range, sfxHandle_t sfx)
{
S_AL_SrcLoop(SRCPRI_AMBIENT, sfx, origin, velocity, entityNum, 255);
}
/*
=================
S_AL_StopLoopingSound
=================
*/
static
void S_AL_StopLoopingSound(int entityNum )
{
if(entityList[entityNum].srcAllocated)
S_AL_SrcKill(entityList[entityNum].srcIndex);
}
/*
=================
S_AL_SrcUpdate
Update state (move things around, manage sources, and so on)
=================
*/
static
void S_AL_SrcUpdate( void )
{
int i;
int entityNum;
ALint state;
src_t *curSource;
for(i = 0; i < srcCount; i++)
{
entityNum = srcList[i].entity;
curSource = &srcList[i];
if(curSource->isLocked)
continue;
if(!curSource->isActive)
continue;
// Update source parameters
if((s_alGain->modified) || (s_volume->modified))
curSource->curGain = s_alGain->value * s_volume->value;
if((s_alRolloff->modified) && (!curSource->local))
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
if(s_alMinDistance->modified)
qalSourcef(curSource->alSource, AL_REFERENCE_DISTANCE, s_alMinDistance->value);
if(curSource->isLooping)
{
sentity_t *sent = &entityList[ entityNum ];
// If a looping effect hasn't been touched this frame, pause or kill it
if(sent->loopAddedThisFrame)
{
alSfx_t *curSfx;
// The sound has changed without an intervening removal
if(curSource->isActive && !sent->startLoopingSound &&
curSource->sfx != sent->loopSfx)
{
S_AL_NewLoopMaster(curSource, qtrue);
curSource->isPlaying = qfalse;
qalSourceStop(curSource->alSource);
qalSourcei(curSource->alSource, AL_BUFFER, 0);
sent->startLoopingSound = qtrue;
}
// The sound hasn't been started yet
if(sent->startLoopingSound)
{
S_AL_SrcSetup(i, sent->loopSfx, sent->loopPriority,
entityNum, -1, 0, curSource->local);
curSource->isLooping = qtrue;
knownSfx[curSource->sfx].loopCnt++;
sent->startLoopingSound = qfalse;
}
curSfx = &knownSfx[curSource->sfx];
S_AL_ScaleGain(curSource, curSource->loopSpeakerPos);
if(!curSource->scaleGain)
{
if(curSource->isPlaying)
{
// Sound is mute, stop playback until we are in range again
S_AL_NewLoopMaster(curSource, qfalse);
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
else if(!curSfx->loopActiveCnt && curSfx->masterLoopSrc < 0)
curSfx->masterLoopSrc = i;
continue;
}
if(!curSource->isPlaying)
{
qalSourcei(curSource->alSource, AL_LOOPING, AL_TRUE);
curSource->isPlaying = qtrue;
qalSourcePlay(curSource->alSource);
if(curSource->priority == SRCPRI_AMBIENT)
{
// If there are other ambient looping sources with the same sound,
// make sure the sound of these sources are in sync.
if(curSfx->loopActiveCnt)
{
int offset, error;
// we already have a master loop playing, get buffer position.
S_AL_ClearError( qfalse );
qalGetSourcei(srcList[curSfx->masterLoopSrc].alSource, AL_SAMPLE_OFFSET, &offset);
if((error = qalGetError()) != AL_NO_ERROR)
{
if(error != AL_INVALID_ENUM)
{
Com_Printf(S_COLOR_YELLOW "WARNING: Cannot get sample offset from source %d: "
"%s\n", i, S_AL_ErrorMsg(error));
}
}
else
qalSourcei(curSource->alSource, AL_SAMPLE_OFFSET, offset);
}
else if(curSfx->loopCnt && curSfx->masterLoopSrc >= 0)
{
float secofs;
src_t *master = &srcList[curSfx->masterLoopSrc];
// This loop sound used to be played, but all sources are stopped. Use last sample position/time
// to calculate offset so the player thinks the sources continued playing while they were inaudible.
if(master->lastTimePos >= 0)
{
secofs = master->lastTimePos + (Sys_Milliseconds() - master->lastSampleTime) / 1000.0f;
secofs = fmodf(secofs, (float) curSfx->info.samples / curSfx->info.rate);
qalSourcef(curSource->alSource, AL_SEC_OFFSET, secofs);
}
// I be the master now
curSfx->masterLoopSrc = i;
}
else
curSfx->masterLoopSrc = i;
}
else if(curSource->lastTimePos >= 0)
{
float secofs;
// For unsynced loops (SRCPRI_ENTITY) just carry on playing as if the sound was never stopped
secofs = curSource->lastTimePos + (Sys_Milliseconds() - curSource->lastSampleTime) / 1000.0f;
secofs = fmodf(secofs, (float) curSfx->info.samples / curSfx->info.rate);
qalSourcef(curSource->alSource, AL_SEC_OFFSET, secofs);
}
curSfx->loopActiveCnt++;
}
// Update locality
if(curSource->local)
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_TRUE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, 0.0f);
}
else
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_FALSE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
}
}
else if(curSource->priority == SRCPRI_AMBIENT)
{
if(curSource->isPlaying)
{
S_AL_NewLoopMaster(curSource, qfalse);
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
}
else
S_AL_SrcKill(i);
continue;
}
if(!curSource->isStream)
{
// Check if it's done, and flag it
qalGetSourcei(curSource->alSource, AL_SOURCE_STATE, &state);
if(state == AL_STOPPED)
{
curSource->isPlaying = qfalse;
S_AL_SrcKill(i);
continue;
}
}
// Query relativity of source, don't move if it's true
qalGetSourcei(curSource->alSource, AL_SOURCE_RELATIVE, &state);
// See if it needs to be moved
if(curSource->isTracking && !state)
{
qalSourcefv(curSource->alSource, AL_POSITION, entityList[entityNum].origin);
S_AL_ScaleGain(curSource, entityList[entityNum].origin);
}
}
}
/*
=================
S_AL_SrcShutup
=================
*/
static
void S_AL_SrcShutup( void )
{
int i;
for(i = 0; i < srcCount; i++)
S_AL_SrcKill(i);
}
/*
=================
S_AL_SrcGet
=================
*/
static
ALuint S_AL_SrcGet(srcHandle_t src)
{
return srcList[src].alSource;
}
//===========================================================================
// Q3A cinematics use up to 12 buffers at once
#define MAX_STREAM_BUFFERS 20
static srcHandle_t streamSourceHandles[MAX_RAW_STREAMS];
static qboolean streamPlaying[MAX_RAW_STREAMS];
static ALuint streamSources[MAX_RAW_STREAMS];
static ALuint streamBuffers[MAX_RAW_STREAMS][MAX_STREAM_BUFFERS];
static int streamNumBuffers[MAX_RAW_STREAMS];
static int streamBufIndex[MAX_RAW_STREAMS];
/*
=================
S_AL_AllocateStreamChannel
=================
*/
static void S_AL_AllocateStreamChannel(int stream, int entityNum)
{
srcHandle_t cursrc;
ALuint alsrc;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(entityNum >= 0)
{
// This is a stream that tracks an entity
// Allocate a streamSource at normal priority
cursrc = S_AL_SrcAlloc(-1, SRCPRI_ENTITY, entityNum, 0, 0);
if(cursrc < 0)
return;
S_AL_SrcSetup(cursrc, -1, SRCPRI_ENTITY, entityNum, 0, 0, qfalse);
alsrc = S_AL_SrcGet(cursrc);
srcList[cursrc].isTracking = qtrue;
srcList[cursrc].isStream = qtrue;
}
else
{
// Unspatialized stream source
// Allocate a streamSource at high priority
cursrc = S_AL_SrcAlloc(-1, SRCPRI_STREAM, -2, 0, 0);
if(cursrc < 0)
return;
alsrc = S_AL_SrcGet(cursrc);
// Lock the streamSource so nobody else can use it, and get the raw streamSource
S_AL_SrcLock(cursrc);
// make sure that after unmuting the S_AL_Gain in S_Update() does not turn
// volume up prematurely for this source
srcList[cursrc].scaleGain = 0.0f;
// Set some streamSource parameters
qalSourcei (alsrc, AL_BUFFER, 0 );
qalSourcei (alsrc, AL_LOOPING, AL_FALSE );
qalSource3f(alsrc, AL_POSITION, 0.0, 0.0, 0.0);
qalSource3f(alsrc, AL_VELOCITY, 0.0, 0.0, 0.0);
qalSource3f(alsrc, AL_DIRECTION, 0.0, 0.0, 0.0);
qalSourcef (alsrc, AL_ROLLOFF_FACTOR, 0.0 );
qalSourcei (alsrc, AL_SOURCE_RELATIVE, AL_TRUE );
}
streamSourceHandles[stream] = cursrc;
streamSources[stream] = alsrc;
streamNumBuffers[stream] = 0;
streamBufIndex[stream] = 0;
}
/*
=================
S_AL_FreeStreamChannel
=================
*/
static void S_AL_FreeStreamChannel( int stream )
{
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
// Detach any buffers
qalSourcei(streamSources[stream], AL_BUFFER, 0);
// Delete the buffers
if (streamNumBuffers[stream] > 0) {
qalDeleteBuffers(streamNumBuffers[stream], streamBuffers[stream]);
streamNumBuffers[stream] = 0;
}
// Release the output streamSource
S_AL_SrcUnlock(streamSourceHandles[stream]);
S_AL_SrcKill(streamSourceHandles[stream]);
streamSources[stream] = 0;
streamSourceHandles[stream] = -1;
}
/*
=================
S_AL_RawSamples
=================
*/
static
void S_AL_RawSamples(int stream, int samples, int rate, int width, int channels, const byte *data, float volume, int entityNum)
{
int numBuffers;
ALuint buffer;
ALuint format;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
format = S_AL_Format( width, channels );
// Create the streamSource if necessary
if(streamSourceHandles[stream] == -1)
{
S_AL_AllocateStreamChannel(stream, entityNum);
// Failed?
if(streamSourceHandles[stream] == -1)
{
Com_Printf( S_COLOR_RED "ERROR: Can't allocate streaming streamSource\n");
return;
}
}
qalGetSourcei(streamSources[stream], AL_BUFFERS_QUEUED, &numBuffers);
if (numBuffers == MAX_STREAM_BUFFERS)
{
Com_DPrintf(S_COLOR_RED"WARNING: Steam dropping raw samples, reached MAX_STREAM_BUFFERS\n");
return;
}
// Allocate a new AL buffer if needed
if (numBuffers == streamNumBuffers[stream])
{
ALuint oldBuffers[MAX_STREAM_BUFFERS];
int i;
if (!S_AL_GenBuffers(1, &buffer, "stream"))
return;
Com_Memcpy(oldBuffers, &streamBuffers[stream], sizeof (oldBuffers));
// Reorder buffer array in order of oldest to newest
for ( i = 0; i < streamNumBuffers[stream]; ++i )
streamBuffers[stream][i] = oldBuffers[(streamBufIndex[stream] + i) % streamNumBuffers[stream]];
// Add the new buffer to end
streamBuffers[stream][streamNumBuffers[stream]] = buffer;
streamBufIndex[stream] = streamNumBuffers[stream];
streamNumBuffers[stream]++;
}
// Select next buffer in loop
buffer = streamBuffers[stream][ streamBufIndex[stream] ];
streamBufIndex[stream] = (streamBufIndex[stream] + 1) % streamNumBuffers[stream];
// Fill buffer
qalBufferData(buffer, format, (ALvoid *)data, (samples * width * channels), rate);
// Shove the data onto the streamSource
qalSourceQueueBuffers(streamSources[stream], 1, &buffer);
if(entityNum < 0)
{
// Volume
S_AL_Gain (streamSources[stream], volume * s_volume->value * s_alGain->value);
}
// Start stream
if(!streamPlaying[stream])
{
qalSourcePlay( streamSources[stream] );
streamPlaying[stream] = qtrue;
}
}
/*
=================
S_AL_StreamUpdate
=================
*/
static
void S_AL_StreamUpdate( int stream )
{
int numBuffers;
ALint state;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(streamSourceHandles[stream] == -1)
return;
// Un-queue any buffers
qalGetSourcei( streamSources[stream], AL_BUFFERS_PROCESSED, &numBuffers );
while( numBuffers-- )
{
ALuint buffer;
qalSourceUnqueueBuffers(streamSources[stream], 1, &buffer);
}
// Start the streamSource playing if necessary
qalGetSourcei( streamSources[stream], AL_BUFFERS_QUEUED, &numBuffers );
qalGetSourcei(streamSources[stream], AL_SOURCE_STATE, &state);
if(state == AL_STOPPED)
{
streamPlaying[stream] = qfalse;
// If there are no buffers queued up, release the streamSource
if( !numBuffers )
S_AL_FreeStreamChannel( stream );
}
if( !streamPlaying[stream] && numBuffers )
{
qalSourcePlay( streamSources[stream] );
streamPlaying[stream] = qtrue;
}
}
/*
=================
S_AL_StreamDie
=================
*/
static
void S_AL_StreamDie( int stream )
{
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(streamSourceHandles[stream] == -1)
return;
streamPlaying[stream] = qfalse;
qalSourceStop(streamSources[stream]);
S_AL_FreeStreamChannel(stream);
}
//===========================================================================
#define NUM_MUSIC_BUFFERS 4
#define MUSIC_BUFFER_SIZE 4096
static qboolean musicPlaying = qfalse;
static srcHandle_t musicSourceHandle = -1;
static ALuint musicSource;
static ALuint musicBuffers[NUM_MUSIC_BUFFERS];
static snd_stream_t *mus_stream;
static snd_stream_t *intro_stream;
static char s_backgroundLoop[MAX_QPATH];
static byte decode_buffer[MUSIC_BUFFER_SIZE];
/*
=================
S_AL_MusicSourceGet
=================
*/
static void S_AL_MusicSourceGet( void )
{
// Allocate a musicSource at high priority
musicSourceHandle = S_AL_SrcAlloc(-1, SRCPRI_STREAM, -2, 0, 0);
if(musicSourceHandle == -1)
return;
// Lock the musicSource so nobody else can use it, and get the raw musicSource
S_AL_SrcLock(musicSourceHandle);
musicSource = S_AL_SrcGet(musicSourceHandle);
// make sure that after unmuting the S_AL_Gain in S_Update() does not turn
// volume up prematurely for this source
srcList[musicSourceHandle].scaleGain = 0.0f;
// Set some musicSource parameters
qalSource3f(musicSource, AL_POSITION, 0.0, 0.0, 0.0);
qalSource3f(musicSource, AL_VELOCITY, 0.0, 0.0, 0.0);
qalSource3f(musicSource, AL_DIRECTION, 0.0, 0.0, 0.0);
qalSourcef (musicSource, AL_ROLLOFF_FACTOR, 0.0 );
qalSourcei (musicSource, AL_SOURCE_RELATIVE, AL_TRUE );
}
/*
=================
S_AL_MusicSourceFree
=================
*/
static void S_AL_MusicSourceFree( void )
{
// Release the output musicSource
S_AL_SrcUnlock(musicSourceHandle);
S_AL_SrcKill(musicSourceHandle);
musicSource = 0;
musicSourceHandle = -1;
}
/*
=================
S_AL_CloseMusicFiles
=================
*/
static void S_AL_CloseMusicFiles(void)
{
if(intro_stream)
{
S_CodecCloseStream(intro_stream);
intro_stream = NULL;
}
if(mus_stream)
{
S_CodecCloseStream(mus_stream);
mus_stream = NULL;
}
}
/*
=================
S_AL_StopBackgroundTrack
=================
*/
static
void S_AL_StopBackgroundTrack( void )
{
if(!musicPlaying)
return;
// Stop playing
qalSourceStop(musicSource);
// Detach any buffers
qalSourcei(musicSource, AL_BUFFER, 0);
// Delete the buffers
qalDeleteBuffers(NUM_MUSIC_BUFFERS, musicBuffers);
// Free the musicSource
S_AL_MusicSourceFree();
// Unload the stream
S_AL_CloseMusicFiles();
musicPlaying = qfalse;
}
/*
=================
S_AL_MusicProcess
=================
*/
static
void S_AL_MusicProcess(ALuint b)
{
ALenum error;
int l;
ALuint format;
snd_stream_t *curstream;
S_AL_ClearError( qfalse );
if(intro_stream)
curstream = intro_stream;
else
curstream = mus_stream;
if(!curstream)
return;
l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
// Run out data to read, start at the beginning again
if(l == 0)
{
S_CodecCloseStream(curstream);
// the intro stream just finished playing so we don't need to reopen
// the music stream.
if(intro_stream)
intro_stream = NULL;
else
mus_stream = S_CodecOpenStream(s_backgroundLoop);
curstream = mus_stream;
if(!curstream)
{
S_AL_StopBackgroundTrack();
return;
}
l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
}
format = S_AL_Format(curstream->info.width, curstream->info.channels);
if( l == 0 )
{
// We have no data to buffer, so buffer silence
byte dummyData[ 2 ] = { 0 };
qalBufferData( b, AL_FORMAT_MONO16, (void *)dummyData, 2, 22050 );
}
else
qalBufferData(b, format, decode_buffer, l, curstream->info.rate);
if( ( error = qalGetError( ) ) != AL_NO_ERROR )
{
S_AL_StopBackgroundTrack( );
Com_Printf( S_COLOR_RED "ERROR: while buffering data for music stream - %s\n",
S_AL_ErrorMsg( error ) );
return;
}
}
/*
=================
S_AL_StartBackgroundTrack
=================
*/
static
void S_AL_StartBackgroundTrack( const char *intro, const char *loop )
{
int i;
qboolean issame;
Com_DPrintf( "S_AL_StartBackgroundTrack( %s, %s )\n", intro, loop );
// Stop any existing music that might be playing
S_AL_StopBackgroundTrack();
Cvar_Set( "s_currentMusic", "" ); //----(SA) so the savegame will have the right music
if((!intro || !*intro) && (!loop || !*loop))
return;
// Allocate a musicSource
S_AL_MusicSourceGet();
if(musicSourceHandle == -1)
return;
if (!loop || !*loop)
{
loop = intro;
issame = qtrue;
}
else if(intro && *intro && !strcmp(intro, loop))
issame = qtrue;
else
issame = qfalse;
// Copy the loop over
Q_strncpyz( s_backgroundLoop, loop, sizeof( s_backgroundLoop ) );
if(!issame)
{
// Open the intro and don't mind whether it succeeds.
// The important part is the loop.
intro_stream = S_CodecOpenStream(intro);
}
else
intro_stream = NULL;
Cvar_Set( "s_currentMusic", s_backgroundLoop ); //----(SA) so the savegame will have the right music
mus_stream = S_CodecOpenStream(s_backgroundLoop);
if(!mus_stream)
{
S_AL_CloseMusicFiles();
S_AL_MusicSourceFree();
return;
}
// Generate the musicBuffers
if (!S_AL_GenBuffers(NUM_MUSIC_BUFFERS, musicBuffers, "music"))
return;
// Queue the musicBuffers up
for(i = 0; i < NUM_MUSIC_BUFFERS; i++)
{
S_AL_MusicProcess(musicBuffers[i]);
}
qalSourceQueueBuffers(musicSource, NUM_MUSIC_BUFFERS, musicBuffers);
// Set the initial gain property
S_AL_Gain(musicSource, s_alGain->value * s_musicVolume->value);
// Start playing
qalSourcePlay(musicSource);
musicPlaying = qtrue;
}
/*
=================
S_AL_MusicUpdate
=================
*/
static
void S_AL_MusicUpdate( void )
{
int numBuffers;
ALint state;
if(!musicPlaying)
return;
qalGetSourcei( musicSource, AL_BUFFERS_PROCESSED, &numBuffers );
while( numBuffers-- )
{
ALuint b;
qalSourceUnqueueBuffers(musicSource, 1, &b);
S_AL_MusicProcess(b);
qalSourceQueueBuffers(musicSource, 1, &b);
}
// Hitches can cause OpenAL to be starved of buffers when streaming.
// If this happens, it will stop playback. This restarts the source if
// it is no longer playing, and if there are buffers available
qalGetSourcei( musicSource, AL_SOURCE_STATE, &state );
qalGetSourcei( musicSource, AL_BUFFERS_QUEUED, &numBuffers );
if( state == AL_STOPPED && numBuffers )
{
Com_DPrintf( S_COLOR_YELLOW "Restarted OpenAL music\n" );
qalSourcePlay(musicSource);
}
// Set the gain property
S_AL_Gain(musicSource, s_alGain->value * s_musicVolume->value);
}
/*
======================
S_FadeStreamingSound
======================
*/
static
void S_AL_FadeStreamingSound( float targetvol, int time, int ssNum ) {
// FIXME: Stub
}
/*
======================
S_FadeAllSounds
======================
*/
static
void S_AL_FadeAllSounds( float targetvol, int time ) {
// FIXME: Stub
}
/*
======================
S_StartStreamingSound
======================
*/
static void S_AL_StartStreamingSound( const char *intro, const char *loop, int entnum, int channel, int attenuation ) {
// FIXME: Stub
}
/*
======================
S_StopEntStreamingSound
======================
*/
static void S_AL_StopEntStreamingSound( int entnum ) {
// FIXME: Stub
}
/*
======================
S_GetVoiceAmplitude
======================
*/
int S_AL_GetVoiceAmplitude( int entityNum ) {
if ( entityNum >= MAX_CLIENTS ) {
Com_Printf( "Error: S_GetVoiceAmplitude() called for a non-client\n" );
return 0;
}
return (int)s_entityTalkAmplitude[entityNum];
}
//===========================================================================
// Local state variables
static ALCdevice *alDevice;
static ALCcontext *alContext;
#ifdef USE_VOIP
static ALCdevice *alCaptureDevice;
static cvar_t *s_alCapture;
#endif
#ifdef _WIN32
#define ALDRIVER_DEFAULT "OpenAL32.dll"
#elif defined(__APPLE__)
#define ALDRIVER_DEFAULT "libopenal.dylib"
#elif defined(__OpenBSD__)
#define ALDRIVER_DEFAULT "libopenal.so"
#else
#define ALDRIVER_DEFAULT "libopenal.so.1"
#endif
/*
=================
S_AL_ClearSoundBuffer
=================
*/
static
void S_AL_ClearSoundBuffer( void )
{
S_AL_SrcShutdown( );
S_AL_SrcInit( );
}
/*
=================
S_AL_StopAllSounds
=================
*/
static
void S_AL_StopAllSounds( void )
{
int i;
S_AL_SrcShutup();
S_AL_StopBackgroundTrack();
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamDie(i);
S_AL_ClearSoundBuffer();
}
/*
=================
S_AL_Respatialize
=================
*/
static
void S_AL_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], int inwater )
{
float orientation[6];
vec3_t sorigin;
VectorCopy( origin, sorigin );
S_AL_SanitiseVector( sorigin );
S_AL_SanitiseVector( axis[ 0 ] );
S_AL_SanitiseVector( axis[ 1 ] );
S_AL_SanitiseVector( axis[ 2 ] );
orientation[0] = axis[0][0]; orientation[1] = axis[0][1]; orientation[2] = axis[0][2];
orientation[3] = axis[2][0]; orientation[4] = axis[2][1]; orientation[5] = axis[2][2];
lastListenerNumber = entityNum;
VectorCopy( sorigin, lastListenerOrigin );
// Set OpenAL listener paramaters
qalListenerfv(AL_POSITION, (ALfloat *)sorigin);
qalListenerfv(AL_VELOCITY, vec3_origin);
qalListenerfv(AL_ORIENTATION, orientation);
}
/*
=================
S_AL_Update
=================
*/
static
void S_AL_Update( void )
{
int i;
if(s_muted->modified)
{
// muted state changed. Let S_AL_Gain turn up all sources again.
for(i = 0; i < srcCount; i++)
{
if(srcList[i].isActive)
S_AL_Gain(srcList[i].alSource, srcList[i].scaleGain);
}
s_muted->modified = qfalse;
}
// Update SFX channels
S_AL_SrcUpdate();
// Update streams
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamUpdate(i);
S_AL_MusicUpdate();
// Doppler
if(s_doppler->modified)
{
s_alDopplerFactor->modified = qtrue;
s_doppler->modified = qfalse;
}
// Doppler parameters
if(s_alDopplerFactor->modified)
{
if(s_doppler->integer)
qalDopplerFactor(s_alDopplerFactor->value);
else
qalDopplerFactor(0.0f);
s_alDopplerFactor->modified = qfalse;
}
if(s_alDopplerSpeed->modified)
{
qalSpeedOfSound(s_alDopplerSpeed->value);
s_alDopplerSpeed->modified = qfalse;
}
// Clear the modified flags on the other cvars
s_alGain->modified = qfalse;
s_volume->modified = qfalse;
s_musicVolume->modified = qfalse;
s_alMinDistance->modified = qfalse;
s_alRolloff->modified = qfalse;
}
/*
=================
S_AL_DisableSounds
=================
*/
static
void S_AL_DisableSounds( void )
{
S_AL_StopAllSounds();
}
/*
=================
S_AL_BeginRegistration
=================
*/
static
void S_AL_BeginRegistration( void )
{
if(!numSfx)
S_AL_BufferInit();
}
/*
=================
S_AL_SoundList
=================
*/
static
void S_AL_SoundList( void )
{
}
#ifdef USE_VOIP
static
void S_AL_StartCapture( void )
{
if (alCaptureDevice != NULL)
qalcCaptureStart(alCaptureDevice);
}
static
int S_AL_AvailableCaptureSamples( void )
{
int retval = 0;
if (alCaptureDevice != NULL)
{
ALint samples = 0;
qalcGetIntegerv(alCaptureDevice, ALC_CAPTURE_SAMPLES, sizeof (samples), &samples);
retval = (int) samples;
}
return retval;
}
static
void S_AL_Capture( int samples, byte *data )
{
if (alCaptureDevice != NULL)
qalcCaptureSamples(alCaptureDevice, data, samples);
}
void S_AL_StopCapture( void )
{
if (alCaptureDevice != NULL)
qalcCaptureStop(alCaptureDevice);
}
void S_AL_MasterGain( float gain )
{
qalListenerf(AL_GAIN, gain);
}
#endif
/*
=================
S_AL_SoundInfo
=================
*/
static void S_AL_SoundInfo(void)
{
Com_Printf( "OpenAL info:\n" );
Com_Printf( " Vendor: %s\n", qalGetString( AL_VENDOR ) );
Com_Printf( " Version: %s\n", qalGetString( AL_VERSION ) );
Com_Printf( " Renderer: %s\n", qalGetString( AL_RENDERER ) );
Com_Printf( " AL Extensions: %s\n", qalGetString( AL_EXTENSIONS ) );
Com_Printf( " ALC Extensions: %s\n", qalcGetString( alDevice, ALC_EXTENSIONS ) );
if(enumeration_all_ext)
Com_Printf(" Device: %s\n", qalcGetString(alDevice, ALC_ALL_DEVICES_SPECIFIER));
else if(enumeration_ext)
Com_Printf(" Device: %s\n", qalcGetString(alDevice, ALC_DEVICE_SPECIFIER));
if(enumeration_all_ext || enumeration_ext)
Com_Printf(" Available Devices:\n%s", s_alAvailableDevices->string);
#ifdef USE_VOIP
if(capture_ext)
{
#ifdef __APPLE__
Com_Printf(" Input Device: %s\n", qalcGetString(alCaptureDevice, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER));
#else
Com_Printf(" Input Device: %s\n", qalcGetString(alCaptureDevice, ALC_CAPTURE_DEVICE_SPECIFIER));
#endif
Com_Printf(" Available Input Devices:\n%s", s_alAvailableInputDevices->string);
}
#endif
}
/*
=================
S_AL_Shutdown
=================
*/
static
void S_AL_Shutdown( void )
{
// Shut down everything
int i;
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamDie(i);
S_AL_StopBackgroundTrack( );
S_AL_SrcShutdown( );
S_AL_BufferShutdown( );
qalcDestroyContext(alContext);
qalcCloseDevice(alDevice);
#ifdef USE_VOIP
if (alCaptureDevice != NULL) {
qalcCaptureStop(alCaptureDevice);
qalcCaptureCloseDevice(alCaptureDevice);
alCaptureDevice = NULL;
Com_Printf( "OpenAL capture device closed.\n" );
}
#endif
for (i = 0; i < MAX_RAW_STREAMS; i++) {
streamSourceHandles[i] = -1;
streamPlaying[i] = qfalse;
streamSources[i] = 0;
}
QAL_Shutdown();
}
#endif
/*
=================
S_AL_Init
=================
*/
qboolean S_AL_Init( soundInterface_t *si )
{
#ifdef USE_OPENAL
const char* device = NULL;
const char* inputdevice = NULL;
int i;
if( !si ) {
return qfalse;
}
for (i = 0; i < MAX_RAW_STREAMS; i++) {
streamSourceHandles[i] = -1;
streamPlaying[i] = qfalse;
streamSources[i] = 0;
streamNumBuffers[i] = 0;
streamBufIndex[i] = 0;
}
// New console variables
s_alPrecache = Cvar_Get( "s_alPrecache", "1", CVAR_ARCHIVE );
s_alGain = Cvar_Get( "s_alGain", "1.0", CVAR_ARCHIVE );
s_alSources = Cvar_Get( "s_alSources", "128", CVAR_ARCHIVE );
s_alDopplerFactor = Cvar_Get( "s_alDopplerFactor", "1.0", CVAR_ARCHIVE );
s_alDopplerSpeed = Cvar_Get( "s_alDopplerSpeed", "9000", CVAR_ARCHIVE );
s_alMinDistance = Cvar_Get( "s_alMinDistance", "256", CVAR_ARCHIVE );
s_alMaxDistance = Cvar_Get("s_alMaxDistance", "1024", CVAR_ARCHIVE);
s_alRolloff = Cvar_Get( "s_alRolloff", "1.3", CVAR_ARCHIVE);
s_alGraceDistance = Cvar_Get("s_alGraceDistance", "512", CVAR_ARCHIVE);
s_alTalkAnims = Cvar_Get("s_alTalkAnims", "160", CVAR_ARCHIVE);
s_alDriver = Cvar_Get( "s_alDriver", ALDRIVER_DEFAULT, CVAR_ARCHIVE | CVAR_LATCH );
s_alInputDevice = Cvar_Get( "s_alInputDevice", "", CVAR_ARCHIVE | CVAR_LATCH );
s_alDevice = Cvar_Get("s_alDevice", "", CVAR_ARCHIVE | CVAR_LATCH);
// Load QAL
if( !QAL_Init( s_alDriver->string ) )
{
#if defined( _WIN32 )
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) && !QAL_Init( "OpenAL64.dll" ) ) {
#elif defined ( __APPLE__ )
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) && !QAL_Init( "/System/Library/Frameworks/OpenAL.framework/OpenAL" ) ) {
#else
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) || !QAL_Init( ALDRIVER_DEFAULT ) ) {
#endif
return qfalse;
}
}
device = s_alDevice->string;
if(device && !*device)
device = NULL;
inputdevice = s_alInputDevice->string;
if(inputdevice && !*inputdevice)
inputdevice = NULL;
// Device enumeration support
enumeration_all_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT");
enumeration_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT");
if(enumeration_ext || enumeration_all_ext)
{
char devicenames[16384] = "";
const char *devicelist;
#ifdef _WIN32
const char *defaultdevice;
#endif
int curlen;
// get all available devices + the default device name.
if(enumeration_all_ext)
{
devicelist = qalcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_ALL_DEVICES_SPECIFIER);
#endif
}
else
{
// We don't have ALC_ENUMERATE_ALL_EXT but normal enumeration.
devicelist = qalcGetString(NULL, ALC_DEVICE_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
#endif
enumeration_ext = qtrue;
}
#ifdef _WIN32
// check whether the default device is generic hardware. If it is, change to
// Generic Software as that one works more reliably with various sound systems.
// If it's not, use OpenAL's default selection as we don't want to ignore
// native hardware acceleration.
if(!device && defaultdevice && !strcmp(defaultdevice, "Generic Hardware"))
device = "Generic Software";
#endif
// dump a list of available devices to a cvar for the user to see.
if(devicelist)
{
while((curlen = strlen(devicelist)))
{
Q_strcat(devicenames, sizeof(devicenames), devicelist);
Q_strcat(devicenames, sizeof(devicenames), "\n");
devicelist += curlen + 1;
}
}
s_alAvailableDevices = Cvar_Get("s_alAvailableDevices", devicenames, CVAR_ROM | CVAR_NORESTART);
}
alDevice = qalcOpenDevice(device);
if( !alDevice && device )
{
Com_Printf( "Failed to open OpenAL device '%s', trying default.\n", device );
alDevice = qalcOpenDevice(NULL);
}
if( !alDevice )
{
QAL_Shutdown( );
Com_Printf( "Failed to open OpenAL device.\n" );
return qfalse;
}
// Create OpenAL context
alContext = qalcCreateContext( alDevice, NULL );
if( !alContext )
{
QAL_Shutdown( );
qalcCloseDevice( alDevice );
Com_Printf( "Failed to create OpenAL context.\n" );
return qfalse;
}
qalcMakeContextCurrent( alContext );
// Initialize sources, buffers, music
S_AL_BufferInit( );
S_AL_SrcInit( );
// Print this for informational purposes
Com_Printf( "Allocated %d sources.\n", srcCount);
// Set up OpenAL parameters (doppler, etc)
qalDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
qalDopplerFactor( s_alDopplerFactor->value );
qalSpeedOfSound( s_alDopplerSpeed->value );
#ifdef USE_VOIP
// !!! FIXME: some of these alcCaptureOpenDevice() values should be cvars.
// !!! FIXME: add support for capture device enumeration.
// !!! FIXME: add some better error reporting.
s_alCapture = Cvar_Get( "s_alCapture", "1", CVAR_ARCHIVE | CVAR_LATCH );
if (!s_alCapture->integer)
{
Com_Printf("OpenAL capture support disabled by user ('+set s_alCapture 1' to enable)\n");
}
#if USE_MUMBLE
else if (cl_useMumble->integer)
{
Com_Printf("OpenAL capture support disabled for Mumble support\n");
}
#endif
else
{
#ifdef __APPLE__
// !!! FIXME: Apple has a 1.1-compliant OpenAL, which includes
// !!! FIXME: capture support, but they don't list it in the
// !!! FIXME: extension string. We need to check the version string,
// !!! FIXME: then the extension string, but that's too much trouble,
// !!! FIXME: so we'll just check the function pointer for now.
if (qalcCaptureOpenDevice == NULL)
#else
if (!qalcIsExtensionPresent(NULL, "ALC_EXT_capture"))
#endif
{
Com_Printf("No ALC_EXT_capture support, can't record audio.\n");
}
else
{
char inputdevicenames[16384] = "";
const char *inputdevicelist;
const char *defaultinputdevice;
int curlen;
capture_ext = qtrue;
// get all available input devices + the default input device name.
inputdevicelist = qalcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER);
defaultinputdevice = qalcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
// dump a list of available devices to a cvar for the user to see.
if (inputdevicelist)
{
while((curlen = strlen(inputdevicelist)))
{
Q_strcat(inputdevicenames, sizeof(inputdevicenames), inputdevicelist);
Q_strcat(inputdevicenames, sizeof(inputdevicenames), "\n");
inputdevicelist += curlen + 1;
}
}
s_alAvailableInputDevices = Cvar_Get("s_alAvailableInputDevices", inputdevicenames, CVAR_ROM | CVAR_NORESTART);
Com_Printf("OpenAL default capture device is '%s'\n", defaultinputdevice ? defaultinputdevice : "none");
alCaptureDevice = qalcCaptureOpenDevice(inputdevice, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
if( !alCaptureDevice && inputdevice )
{
Com_Printf( "Failed to open OpenAL Input device '%s', trying default.\n", inputdevice );
alCaptureDevice = qalcCaptureOpenDevice(NULL, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
}
Com_Printf( "OpenAL capture device %s.\n",
(alCaptureDevice == NULL) ? "failed to open" : "opened");
}
}
#endif
si->Shutdown = S_AL_Shutdown;
si->StartSound = S_AL_StartSound;
si->StartSoundEx = S_AL_StartSoundEx;
si->StartLocalSound = S_AL_StartLocalSound;
si->StartBackgroundTrack = S_AL_StartBackgroundTrack;
si->StopBackgroundTrack = S_AL_StopBackgroundTrack;
si->FadeStreamingSound = S_AL_FadeStreamingSound;
si->FadeAllSounds = S_AL_FadeAllSounds;
si->StartStreamingSound = S_AL_StartStreamingSound;
si->StopEntStreamingSound = S_AL_StopEntStreamingSound;
si->GetVoiceAmplitude = S_AL_GetVoiceAmplitude;
si->RawSamples = S_AL_RawSamples;
si->StopAllSounds = S_AL_StopAllSounds;
si->ClearLoopingSounds = S_AL_ClearLoopingSounds;
si->AddLoopingSound = S_AL_AddLoopingSound;
si->AddRealLoopingSound = S_AL_AddRealLoopingSound;
si->StopLoopingSound = S_AL_StopLoopingSound;
si->Respatialize = S_AL_Respatialize;
si->UpdateEntityPosition = S_AL_UpdateEntityPosition;
si->Update = S_AL_Update;
si->DisableSounds = S_AL_DisableSounds;
si->BeginRegistration = S_AL_BeginRegistration;
si->RegisterSound = S_AL_RegisterSound;
si->ClearSoundBuffer = S_AL_ClearSoundBuffer;
si->SoundInfo = S_AL_SoundInfo;
si->SoundList = S_AL_SoundList;
#ifdef USE_VOIP
si->StartCapture = S_AL_StartCapture;
si->AvailableCaptureSamples = S_AL_AvailableCaptureSamples;
si->Capture = S_AL_Capture;
si->StopCapture = S_AL_StopCapture;
si->MasterGain = S_AL_MasterGain;
#endif
return qtrue;
#else
return qfalse;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3232_1 |
crossvul-cpp_data_good_3232_0 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
Copyright (C) 2005 Stuart Dalton (badcdev@gmail.com)
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "snd_local.h"
#include "snd_codec.h"
#include "client.h"
#ifdef USE_OPENAL
#include "qal.h"
// Console variables specific to OpenAL
cvar_t *s_alPrecache;
cvar_t *s_alGain;
cvar_t *s_alSources;
cvar_t *s_alDopplerFactor;
cvar_t *s_alDopplerSpeed;
cvar_t *s_alMinDistance;
cvar_t *s_alMaxDistance;
cvar_t *s_alRolloff;
cvar_t *s_alGraceDistance;
cvar_t *s_alDriver;
cvar_t *s_alDevice;
cvar_t *s_alInputDevice;
cvar_t *s_alAvailableDevices;
cvar_t *s_alAvailableInputDevices;
static qboolean enumeration_ext = qfalse;
static qboolean enumeration_all_ext = qfalse;
#ifdef USE_VOIP
static qboolean capture_ext = qfalse;
#endif
/*
=================
S_AL_Format
=================
*/
static
ALuint S_AL_Format(int width, int channels)
{
ALuint format = AL_FORMAT_MONO16;
// Work out format
if(width == 1)
{
if(channels == 1)
format = AL_FORMAT_MONO8;
else if(channels == 2)
format = AL_FORMAT_STEREO8;
}
else if(width == 2)
{
if(channels == 1)
format = AL_FORMAT_MONO16;
else if(channels == 2)
format = AL_FORMAT_STEREO16;
}
return format;
}
/*
=================
S_AL_ErrorMsg
=================
*/
static const char *S_AL_ErrorMsg(ALenum error)
{
switch(error)
{
case AL_NO_ERROR:
return "No error";
case AL_INVALID_NAME:
return "Invalid name";
case AL_INVALID_ENUM:
return "Invalid enumerator";
case AL_INVALID_VALUE:
return "Invalid value";
case AL_INVALID_OPERATION:
return "Invalid operation";
case AL_OUT_OF_MEMORY:
return "Out of memory";
default:
return "Unknown error";
}
}
/*
=================
S_AL_ClearError
=================
*/
static void S_AL_ClearError( qboolean quiet )
{
int error = qalGetError();
if( quiet )
return;
if(error != AL_NO_ERROR)
{
Com_DPrintf(S_COLOR_YELLOW "WARNING: unhandled AL error: %s\n",
S_AL_ErrorMsg(error));
}
}
//===========================================================================
typedef struct alSfx_s
{
char filename[MAX_QPATH];
ALuint buffer; // OpenAL buffer
snd_info_t info; // information for this sound like rate, sample count..
qboolean isDefault; // Couldn't be loaded - use default FX
qboolean isDefaultChecked; // Sound has been check if it isDefault
qboolean inMemory; // Sound is stored in memory
qboolean isLocked; // Sound is locked (can not be unloaded)
int lastUsedTime; // Time last used
int loopCnt; // number of loops using this sfx
int loopActiveCnt; // number of playing loops using this sfx
int masterLoopSrc; // All other sources looping this buffer are synced to this master src
} alSfx_t;
static qboolean alBuffersInitialised = qfalse;
// Sound effect storage, data structures
#define MAX_SFX 4096
static alSfx_t knownSfx[MAX_SFX];
static sfxHandle_t numSfx = 0;
static sfxHandle_t default_sfx;
/*
=================
S_AL_BufferFindFree
Find a free handle
=================
*/
static sfxHandle_t S_AL_BufferFindFree( void )
{
int i;
for(i = 0; i < MAX_SFX; i++)
{
// Got one
if(knownSfx[i].filename[0] == '\0')
{
if(i >= numSfx)
numSfx = i + 1;
return i;
}
}
// Shit...
Com_Error(ERR_FATAL, "S_AL_BufferFindFree: No free sound handles");
return -1;
}
/*
=================
S_AL_BufferFind
Find a sound effect if loaded, set up a handle otherwise
=================
*/
static sfxHandle_t S_AL_BufferFind(const char *filename)
{
// Look it up in the table
sfxHandle_t sfx = -1;
int i;
if ( !filename ) {
//Com_Error( ERR_FATAL, "Sound name is NULL" );
filename = "*default*";
}
if ( !filename[0] ) {
//Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is empty\n" );
filename = "*default*";
}
if ( strlen( filename ) >= MAX_QPATH ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is too long: %s\n", filename );
return 0;
}
for(i = 0; i < numSfx; i++)
{
if(!Q_stricmp(knownSfx[i].filename, filename))
{
sfx = i;
break;
}
}
// Not found in table?
if(sfx == -1)
{
alSfx_t *ptr;
sfx = S_AL_BufferFindFree();
// Clear and copy the filename over
ptr = &knownSfx[sfx];
memset(ptr, 0, sizeof(*ptr));
ptr->masterLoopSrc = -1;
strcpy(ptr->filename, filename);
}
// Return the handle
return sfx;
}
/*
=================
S_AL_BufferUseDefault
=================
*/
static void S_AL_BufferUseDefault(sfxHandle_t sfx)
{
if(sfx == default_sfx)
Com_Error(ERR_FATAL, "Can't load default sound effect %s", knownSfx[sfx].filename);
// Com_Printf( S_COLOR_YELLOW "WARNING: Using default sound for %s\n", knownSfx[sfx].filename);
knownSfx[sfx].isDefault = qtrue;
knownSfx[sfx].buffer = knownSfx[default_sfx].buffer;
}
/*
=================
S_AL_BufferUnload
=================
*/
static void S_AL_BufferUnload(sfxHandle_t sfx)
{
if(knownSfx[sfx].filename[0] == '\0')
return;
if(!knownSfx[sfx].inMemory)
return;
// Delete it
S_AL_ClearError( qfalse );
qalDeleteBuffers(1, &knownSfx[sfx].buffer);
if(qalGetError() != AL_NO_ERROR)
Com_Printf( S_COLOR_RED "ERROR: Can't delete sound buffer for %s\n",
knownSfx[sfx].filename);
knownSfx[sfx].inMemory = qfalse;
}
/*
=================
S_AL_BufferEvict
=================
*/
static qboolean S_AL_BufferEvict( void )
{
int i, oldestBuffer = -1;
int oldestTime = Sys_Milliseconds( );
for( i = 0; i < numSfx; i++ )
{
if( !knownSfx[ i ].filename[ 0 ] )
continue;
if( !knownSfx[ i ].inMemory )
continue;
if( knownSfx[ i ].lastUsedTime < oldestTime )
{
oldestTime = knownSfx[ i ].lastUsedTime;
oldestBuffer = i;
}
}
if( oldestBuffer >= 0 )
{
S_AL_BufferUnload( oldestBuffer );
return qtrue;
}
else
return qfalse;
}
/*
=================
S_AL_GenBuffers
=================
*/
static qboolean S_AL_GenBuffers(ALsizei numBuffers, ALuint *buffers, const char *name)
{
ALenum error;
S_AL_ClearError( qfalse );
qalGenBuffers( numBuffers, buffers );
error = qalGetError();
// If we ran out of buffers, start evicting the least recently used sounds
while( error == AL_INVALID_VALUE )
{
if( !S_AL_BufferEvict( ) )
{
Com_Printf( S_COLOR_RED "ERROR: Out of audio buffers\n");
return qfalse;
}
// Try again
S_AL_ClearError( qfalse );
qalGenBuffers( numBuffers, buffers );
error = qalGetError();
}
if( error != AL_NO_ERROR )
{
Com_Printf( S_COLOR_RED "ERROR: Can't create a sound buffer for %s - %s\n",
name, S_AL_ErrorMsg(error));
return qfalse;
}
return qtrue;
}
/*
=================
S_AL_BufferLoad
=================
*/
static void S_AL_BufferLoad(sfxHandle_t sfx, qboolean cache)
{
ALenum error;
ALuint format;
void *data;
snd_info_t info;
alSfx_t *curSfx = &knownSfx[sfx];
// Nothing?
if(curSfx->filename[0] == '\0')
return;
// Player SFX
if(curSfx->filename[0] == '*')
return;
// Already done?
if((curSfx->inMemory) || (curSfx->isDefault) || (!cache && curSfx->isDefaultChecked))
return;
// Try to load
data = S_CodecLoad(curSfx->filename, &info);
if(!data)
{
S_AL_BufferUseDefault(sfx);
return;
}
curSfx->isDefaultChecked = qtrue;
if (!cache)
{
// Don't create AL cache
Hunk_FreeTempMemory(data);
return;
}
format = S_AL_Format(info.width, info.channels);
// Create a buffer
if (!S_AL_GenBuffers(1, &curSfx->buffer, curSfx->filename))
{
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
return;
}
// Fill the buffer
if( info.size == 0 )
{
// We have no data to buffer, so buffer silence
byte dummyData[ 2 ] = { 0 };
qalBufferData(curSfx->buffer, AL_FORMAT_MONO16, (void *)dummyData, 2, 22050);
}
else
qalBufferData(curSfx->buffer, format, data, info.size, info.rate);
error = qalGetError();
// If we ran out of memory, start evicting the least recently used sounds
while(error == AL_OUT_OF_MEMORY)
{
if( !S_AL_BufferEvict( ) )
{
qalDeleteBuffers(1, &curSfx->buffer);
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
Com_Printf( S_COLOR_RED "ERROR: Out of memory loading %s\n", curSfx->filename);
return;
}
// Try load it again
qalBufferData(curSfx->buffer, format, data, info.size, info.rate);
error = qalGetError();
}
// Some other error condition
if(error != AL_NO_ERROR)
{
qalDeleteBuffers(1, &curSfx->buffer);
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
Com_Printf( S_COLOR_RED "ERROR: Can't fill sound buffer for %s - %s\n",
curSfx->filename, S_AL_ErrorMsg(error));
return;
}
curSfx->info = info;
// Free the memory
Hunk_FreeTempMemory(data);
// Woo!
curSfx->inMemory = qtrue;
}
/*
=================
S_AL_BufferUse
=================
*/
static
void S_AL_BufferUse(sfxHandle_t sfx)
{
if(knownSfx[sfx].filename[0] == '\0')
return;
if((!knownSfx[sfx].inMemory) && (!knownSfx[sfx].isDefault))
S_AL_BufferLoad(sfx, qtrue);
knownSfx[sfx].lastUsedTime = Sys_Milliseconds();
}
/*
=================
S_AL_BufferInit
=================
*/
static
qboolean S_AL_BufferInit( void )
{
if(alBuffersInitialised)
return qtrue;
// Clear the hash table, and SFX table
memset(knownSfx, 0, sizeof(knownSfx));
numSfx = 0;
// Load the default sound, and lock it
default_sfx = S_AL_BufferFind( "***DEFAULT***" );
S_AL_BufferUse(default_sfx);
knownSfx[default_sfx].isLocked = qtrue;
// All done
alBuffersInitialised = qtrue;
return qtrue;
}
/*
=================
S_AL_BufferShutdown
=================
*/
static
void S_AL_BufferShutdown( void )
{
int i;
if(!alBuffersInitialised)
return;
// Unlock the default sound effect
knownSfx[default_sfx].isLocked = qfalse;
// Free all used effects
for(i = 0; i < numSfx; i++)
S_AL_BufferUnload(i);
// Clear the tables
numSfx = 0;
// All undone
alBuffersInitialised = qfalse;
}
/*
=================
S_AL_RegisterSound
=================
*/
static
sfxHandle_t S_AL_RegisterSound( const char *sample, qboolean compressed )
{
sfxHandle_t sfx = S_AL_BufferFind(sample);
if((!knownSfx[sfx].inMemory) && (!knownSfx[sfx].isDefault))
S_AL_BufferLoad(sfx, s_alPrecache->integer);
knownSfx[sfx].lastUsedTime = Com_Milliseconds();
if (knownSfx[sfx].isDefault) {
return 0;
}
return sfx;
}
/*
=================
S_AL_BufferGet
Return's a sfx's buffer
=================
*/
static
ALuint S_AL_BufferGet(sfxHandle_t sfx)
{
return knownSfx[sfx].buffer;
}
//===========================================================================
typedef struct src_s
{
ALuint alSource; // OpenAL source object
sfxHandle_t sfx; // Sound effect in use
int lastUsedTime; // Last time used
alSrcPriority_t priority; // Priority
int entity; // Owning entity (-1 if none)
int channel; // Associated channel (-1 if none)
qboolean isActive; // Is this source currently in use?
qboolean isPlaying; // Is this source currently playing, or stopped?
qboolean isLocked; // This is locked (un-allocatable)
qboolean isLooping; // Is this a looping effect (attached to an entity)
qboolean isTracking; // Is this object tracking its owner
qboolean isStream; // Is this source a stream
float curGain; // gain employed if source is within maxdistance.
float scaleGain; // Last gain value for this source. 0 if muted.
float lastTimePos; // On stopped loops, the last position in the buffer
int lastSampleTime; // Time when this was stopped
vec3_t loopSpeakerPos; // Origin of the loop speaker
qboolean local; // Is this local (relative to the cam)
int flags; // flags from StartSoundEx
} src_t;
#ifdef __APPLE__
#define MAX_SRC 128
#else
#define MAX_SRC 256
#endif
static src_t srcList[MAX_SRC];
static int srcCount = 0;
static int srcActiveCnt = 0;
static qboolean alSourcesInitialised = qfalse;
static int lastListenerNumber = -1;
static vec3_t lastListenerOrigin = { 0.0f, 0.0f, 0.0f };
typedef struct sentity_s
{
vec3_t origin;
qboolean srcAllocated; // If a src_t has been allocated to this entity
int srcIndex;
qboolean loopAddedThisFrame;
alSrcPriority_t loopPriority;
sfxHandle_t loopSfx;
qboolean startLoopingSound;
} sentity_t;
static sentity_t entityList[MAX_GENTITIES];
/*
=================
S_AL_SanitiseVector
=================
*/
#define S_AL_SanitiseVector(v) _S_AL_SanitiseVector(v,__LINE__)
static void _S_AL_SanitiseVector( vec3_t v, int line )
{
if( Q_isnan( v[ 0 ] ) || Q_isnan( v[ 1 ] ) || Q_isnan( v[ 2 ] ) )
{
Com_DPrintf( S_COLOR_YELLOW "WARNING: vector with one or more NaN components "
"being passed to OpenAL at %s:%d -- zeroing\n", __FILE__, line );
VectorClear( v );
}
}
/*
=================
S_AL_Gain
Set gain to 0 if muted, otherwise set it to given value.
=================
*/
static void S_AL_Gain(ALuint source, float gainval)
{
if(s_muted->integer)
qalSourcef(source, AL_GAIN, 0.0f);
else
qalSourcef(source, AL_GAIN, gainval);
}
/*
=================
S_AL_ScaleGain
Adapt the gain if necessary to get a quicker fadeout when the source is too far away.
=================
*/
static void S_AL_ScaleGain(src_t *chksrc, vec3_t origin)
{
float distance;
if(!chksrc->local)
distance = Distance(origin, lastListenerOrigin);
// If we exceed a certain distance, scale the gain linearly until the sound
// vanishes into nothingness.
if(!chksrc->local && (distance -= s_alMaxDistance->value) > 0)
{
float scaleFactor;
if(distance >= s_alGraceDistance->value)
scaleFactor = 0.0f;
else
scaleFactor = 1.0f - distance / s_alGraceDistance->value;
scaleFactor *= chksrc->curGain;
if(chksrc->scaleGain != scaleFactor)
{
chksrc->scaleGain = scaleFactor;
S_AL_Gain(chksrc->alSource, chksrc->scaleGain);
}
}
else if(chksrc->scaleGain != chksrc->curGain)
{
chksrc->scaleGain = chksrc->curGain;
S_AL_Gain(chksrc->alSource, chksrc->scaleGain);
}
}
/*
=================
S_AL_HearingThroughEntity
Also see S_Base_HearingThroughEntity
=================
*/
static qboolean S_AL_HearingThroughEntity( int entityNum )
{
float distanceSq;
if( lastListenerNumber == entityNum )
{
// This is an outrageous hack to detect
// whether or not the player is rendering in third person or not. We can't
// ask the renderer because the renderer has no notion of entities and we
// can't ask cgame since that would involve changing the API and hence mod
// compatibility. I don't think there is any way around this, but I'll leave
// the FIXME just in case anyone has a bright idea.
distanceSq = DistanceSquared(
entityList[ entityNum ].origin,
lastListenerOrigin );
if( distanceSq > THIRD_PERSON_THRESHOLD_SQ )
return qfalse; //we're the player, but third person
else
return qtrue; //we're the player
}
else
return qfalse; //not the player
}
/*
=================
S_AL_SrcInit
=================
*/
static
qboolean S_AL_SrcInit( void )
{
int i;
int limit;
// Clear the sources data structure
memset(srcList, 0, sizeof(srcList));
srcCount = 0;
srcActiveCnt = 0;
// Cap s_alSources to MAX_SRC
limit = s_alSources->integer;
if(limit > MAX_SRC)
limit = MAX_SRC;
else if(limit < 16)
limit = 16;
S_AL_ClearError( qfalse );
// Allocate as many sources as possible
for(i = 0; i < limit; i++)
{
qalGenSources(1, &srcList[i].alSource);
if(qalGetError() != AL_NO_ERROR)
break;
srcCount++;
}
alSourcesInitialised = qtrue;
return qtrue;
}
/*
=================
S_AL_SrcShutdown
=================
*/
static
void S_AL_SrcShutdown( void )
{
int i;
src_t *curSource;
if(!alSourcesInitialised)
return;
// Destroy all the sources
for(i = 0; i < srcCount; i++)
{
curSource = &srcList[i];
if(curSource->isLocked)
{
srcList[i].isLocked = qfalse;
Com_DPrintf( S_COLOR_YELLOW "WARNING: Source %d was locked\n", i);
}
if(curSource->entity > 0)
entityList[curSource->entity].srcAllocated = qfalse;
qalSourceStop(srcList[i].alSource);
qalDeleteSources(1, &srcList[i].alSource);
}
memset(srcList, 0, sizeof(srcList));
alSourcesInitialised = qfalse;
}
/*
=================
S_AL_SrcSetup
=================
*/
static void S_AL_SrcSetup(srcHandle_t src, sfxHandle_t sfx, alSrcPriority_t priority,
int entity, int channel, int flags, qboolean local)
{
src_t *curSource;
// Set up src struct
curSource = &srcList[src];
curSource->lastUsedTime = Sys_Milliseconds();
curSource->sfx = sfx;
curSource->priority = priority;
curSource->entity = entity;
curSource->channel = channel;
curSource->isPlaying = qfalse;
curSource->isLocked = qfalse;
curSource->isLooping = qfalse;
curSource->isTracking = qfalse;
curSource->isStream = qfalse;
curSource->curGain = s_alGain->value * s_volume->value;
curSource->scaleGain = curSource->curGain;
curSource->local = local;
curSource->flags = flags;
// Set up OpenAL source
if(sfx >= 0)
{
// Mark the SFX as used, and grab the raw AL buffer
S_AL_BufferUse(sfx);
qalSourcei(curSource->alSource, AL_BUFFER, S_AL_BufferGet(sfx));
}
qalSourcef(curSource->alSource, AL_PITCH, 1.0f);
S_AL_Gain(curSource->alSource, curSource->curGain);
qalSourcefv(curSource->alSource, AL_POSITION, vec3_origin);
qalSourcefv(curSource->alSource, AL_VELOCITY, vec3_origin);
qalSourcei(curSource->alSource, AL_LOOPING, AL_FALSE);
qalSourcef(curSource->alSource, AL_REFERENCE_DISTANCE, s_alMinDistance->value);
if(local)
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_TRUE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, 0.0f);
}
else
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_FALSE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
}
}
/*
=================
S_AL_SaveLoopPos
Remove given source as loop master if it is the master and hand off master status to another source in this case.
=================
*/
static void S_AL_SaveLoopPos(src_t *dest, ALuint alSource)
{
int error;
S_AL_ClearError( qfalse );
qalGetSourcef(alSource, AL_SEC_OFFSET, &dest->lastTimePos);
if((error = qalGetError()) != AL_NO_ERROR)
{
// Old OpenAL implementations don't support AL_SEC_OFFSET
if(error != AL_INVALID_ENUM)
{
Com_Printf(S_COLOR_YELLOW "WARNING: Could not get time offset for alSource %d: %s\n",
alSource, S_AL_ErrorMsg(error));
}
dest->lastTimePos = -1;
}
else
dest->lastSampleTime = Sys_Milliseconds();
}
/*
=================
S_AL_NewLoopMaster
Remove given source as loop master if it is the master and hand off master status to another source in this case.
=================
*/
static void S_AL_NewLoopMaster(src_t *rmSource, qboolean iskilled)
{
int index;
src_t *curSource = NULL;
alSfx_t *curSfx;
curSfx = &knownSfx[rmSource->sfx];
if(rmSource->isPlaying)
curSfx->loopActiveCnt--;
if(iskilled)
curSfx->loopCnt--;
if(curSfx->loopCnt)
{
if(rmSource->priority == SRCPRI_ENTITY)
{
if(!iskilled && rmSource->isPlaying)
{
// only sync ambient loops...
// It makes more sense to have sounds for weapons/projectiles unsynced
S_AL_SaveLoopPos(rmSource, rmSource->alSource);
}
}
else if(rmSource == &srcList[curSfx->masterLoopSrc])
{
int firstInactive = -1;
// Only if rmSource was the master and if there are still playing loops for
// this sound will we need to find a new master.
if(iskilled || curSfx->loopActiveCnt)
{
for(index = 0; index < srcCount; index++)
{
curSource = &srcList[index];
if(curSource->sfx == rmSource->sfx && curSource != rmSource &&
curSource->isActive && curSource->isLooping && curSource->priority == SRCPRI_AMBIENT)
{
if(curSource->isPlaying)
{
curSfx->masterLoopSrc = index;
break;
}
else if(firstInactive < 0)
firstInactive = index;
}
}
}
if(!curSfx->loopActiveCnt)
{
if(firstInactive < 0)
{
if(iskilled)
{
curSfx->masterLoopSrc = -1;
return;
}
else
curSource = rmSource;
}
else
curSource = &srcList[firstInactive];
if(rmSource->isPlaying)
{
// this was the last not stopped source, save last sample position + time
S_AL_SaveLoopPos(curSource, rmSource->alSource);
}
else
{
// second case: all loops using this sound have stopped due to listener being of of range,
// and now the inactive master gets deleted. Just move over the soundpos settings to the
// new master.
curSource->lastTimePos = rmSource->lastTimePos;
curSource->lastSampleTime = rmSource->lastSampleTime;
}
}
}
}
else
curSfx->masterLoopSrc = -1;
}
/*
=================
S_AL_SrcKill
=================
*/
static void S_AL_SrcKill(srcHandle_t src)
{
src_t *curSource = &srcList[src];
// I'm not touching it. Unlock it first.
if(curSource->isLocked)
return;
// Remove the entity association and loop master status
if(curSource->isLooping)
{
curSource->isLooping = qfalse;
if(curSource->entity != -1)
{
sentity_t *curEnt = &entityList[curSource->entity];
curEnt->srcAllocated = qfalse;
curEnt->srcIndex = -1;
curEnt->loopAddedThisFrame = qfalse;
curEnt->startLoopingSound = qfalse;
}
S_AL_NewLoopMaster(curSource, qtrue);
}
// Stop it if it's playing
if(curSource->isPlaying)
{
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
// Detach any buffers
qalSourcei(curSource->alSource, AL_BUFFER, 0);
curSource->sfx = 0;
curSource->lastUsedTime = 0;
curSource->priority = 0;
curSource->entity = -1;
curSource->channel = -1;
if(curSource->isActive)
{
curSource->isActive = qfalse;
srcActiveCnt--;
}
curSource->isLocked = qfalse;
curSource->isTracking = qfalse;
curSource->local = qfalse;
}
/*
=================
S_AL_SrcAlloc
=================
*/
static
srcHandle_t S_AL_SrcAlloc( sfxHandle_t sfx, alSrcPriority_t priority, int entnum, int channel, int flags )
{
int i;
int empty = -1;
int weakest = -1;
int weakest_time = Sys_Milliseconds();
int weakest_pri = 999;
float weakest_gain = 1000.0;
qboolean weakest_isplaying = qtrue;
int weakest_numloops = 0;
src_t *curSource;
qboolean cutDuplicateSound = qfalse;
for(i = 0; i < srcCount; i++)
{
curSource = &srcList[i];
// If it's locked, we aren't even going to look at it
if(curSource->isLocked)
continue;
// Is it empty or not?
if(!curSource->isActive)
{
if (empty == -1)
empty = i;
break;
}
if(curSource->isPlaying)
{
if(weakest_isplaying && curSource->priority < priority &&
(curSource->priority < weakest_pri ||
(!curSource->isLooping && (curSource->scaleGain < weakest_gain || curSource->lastUsedTime < weakest_time))))
{
// If it has lower priority, is fainter or older, flag it as weak
// the last two values are only compared if it's not a looping sound, because we want to prevent two
// loops (loops are added EVERY frame) fighting for a slot
weakest_pri = curSource->priority;
weakest_time = curSource->lastUsedTime;
weakest_gain = curSource->scaleGain;
weakest = i;
}
}
else
{
weakest_isplaying = qfalse;
if(weakest < 0 ||
knownSfx[curSource->sfx].loopCnt > weakest_numloops ||
curSource->priority < weakest_pri ||
curSource->lastUsedTime < weakest_time)
{
// Sources currently not playing of course have lowest priority
// also try to always keep at least one loop master for every loop sound
weakest_pri = curSource->priority;
weakest_time = curSource->lastUsedTime;
weakest_numloops = knownSfx[curSource->sfx].loopCnt;
weakest = i;
}
}
// shut off other sounds on this channel if necessary
if((curSource->entity == entnum) && curSource->sfx > 0 && (curSource->channel == channel))
{
// currently apply only to non-looping sounds
if ( curSource->isLooping ) {
continue;
}
// cutoff all on channel
if ( flags & SND_CUTOFF_ALL ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
if ( curSource->flags & SND_NOCUT ) {
continue;
}
// cutoff sounds that expect to be overwritten
if ( curSource->flags & SND_OKTOCUT ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
// cutoff 'weak' sounds on channel
if ( flags & SND_CUTOFF ) {
if ( curSource->flags & SND_REQUESTCUT ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
}
// re-use channel if applicable
if ( curSource->channel != -1 && curSource->sfx == sfx && !cutDuplicateSound ) {
cutDuplicateSound = qtrue;
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
}
}
if(empty == -1)
empty = weakest;
if(empty >= 0)
{
S_AL_SrcKill(empty);
srcList[empty].isActive = qtrue;
srcActiveCnt++;
}
return empty;
}
/*
=================
S_AL_SrcFind
Finds an active source with matching entity and channel numbers
Returns -1 if there isn't one
=================
*/
#if 0
static
srcHandle_t S_AL_SrcFind(int entnum, int channel)
{
int i;
for(i = 0; i < srcCount; i++)
{
if(!srcList[i].isActive)
continue;
if((srcList[i].entity == entnum) && (srcList[i].channel == channel))
return i;
}
return -1;
}
#endif
/*
=================
S_AL_SrcLock
Locked sources will not be automatically reallocated or managed
=================
*/
static
void S_AL_SrcLock(srcHandle_t src)
{
srcList[src].isLocked = qtrue;
}
/*
=================
S_AL_SrcUnlock
Once unlocked, the source may be reallocated again
=================
*/
static
void S_AL_SrcUnlock(srcHandle_t src)
{
srcList[src].isLocked = qfalse;
}
/*
=================
S_AL_UpdateEntityPosition
=================
*/
static
void S_AL_UpdateEntityPosition( int entityNum, const vec3_t origin )
{
vec3_t sanOrigin;
VectorCopy( origin, sanOrigin );
S_AL_SanitiseVector( sanOrigin );
if ( entityNum < 0 || entityNum >= MAX_GENTITIES )
Com_Error( ERR_DROP, "S_UpdateEntityPosition: bad entitynum %i", entityNum );
VectorCopy( sanOrigin, entityList[entityNum].origin );
}
/*
=================
S_AL_CheckInput
Check whether input values from mods are out of range.
Necessary for i.g. Western Quake3 mod which is buggy.
=================
*/
static qboolean S_AL_CheckInput(int entityNum, sfxHandle_t sfx)
{
if (entityNum < 0 || entityNum >= MAX_GENTITIES)
Com_Error(ERR_DROP, "ERROR: S_AL_CheckInput: bad entitynum %i", entityNum);
if (sfx < 0 || sfx >= numSfx)
{
Com_Printf(S_COLOR_RED "ERROR: S_AL_CheckInput: handle %i out of range\n", sfx);
return qtrue;
}
return qfalse;
}
/*
=================
S_AL_StartLocalSound
Play a local (non-spatialized) sound effect
=================
*/
static
void S_AL_StartLocalSound(sfxHandle_t sfx, int channel)
{
srcHandle_t src;
if(S_AL_CheckInput(0, sfx))
return;
// Try to grab a source
src = S_AL_SrcAlloc(sfx, SRCPRI_LOCAL, -1, channel, 0);
if(src == -1)
return;
// Set up the effect
S_AL_SrcSetup(src, sfx, SRCPRI_LOCAL, -1, channel, 0, qtrue);
// Start it playing
srcList[src].isPlaying = qtrue;
qalSourcePlay(srcList[src].alSource);
}
/*
=================
S_AL_MainStartSound
Play a one-shot sound effect
=================
*/
static void S_AL_MainStartSound( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx, int flags )
{
vec3_t sorigin;
srcHandle_t src;
src_t *curSource;
if(origin)
{
if(S_AL_CheckInput(0, sfx))
return;
VectorCopy(origin, sorigin);
}
else
{
if(S_AL_CheckInput(entnum, sfx))
return;
if(S_AL_HearingThroughEntity(entnum))
{
S_AL_StartLocalSound(sfx, entchannel);
return;
}
VectorCopy(entityList[entnum].origin, sorigin);
}
S_AL_SanitiseVector(sorigin);
if((srcActiveCnt > 5 * srcCount / 3) &&
(DistanceSquared(sorigin, lastListenerOrigin) >=
(s_alMaxDistance->value + s_alGraceDistance->value) * (s_alMaxDistance->value + s_alGraceDistance->value)))
{
// We're getting tight on sources and source is not within hearing distance so don't add it
return;
}
// Try to grab a source
src = S_AL_SrcAlloc(sfx, SRCPRI_ONESHOT, entnum, entchannel, flags);
if(src == -1)
return;
S_AL_SrcSetup(src, sfx, SRCPRI_ONESHOT, entnum, entchannel, flags, qfalse);
curSource = &srcList[src];
if(!origin)
curSource->isTracking = qtrue;
qalSourcefv(curSource->alSource, AL_POSITION, sorigin );
S_AL_ScaleGain(curSource, sorigin);
// Start it playing
curSource->isPlaying = qtrue;
qalSourcePlay(curSource->alSource);
}
/*
=================
S_AL_StartSound
=================
*/
static void S_AL_StartSound( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx )
{
S_AL_MainStartSound( origin, entnum, entchannel, sfx, 0 );
}
/*
=================
S_AL_StartSoundEx
=================
*/
static void S_AL_StartSoundEx( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx, int flags )
{
// RF, we have lots of NULL sounds using up valuable channels, so just ignore them
if ( !sfx && entchannel != CHAN_WEAPON ) { // let null weapon sounds try to play. they kill any weapon sounds playing when a guy dies
return;
}
// RF, make the call now, or else we could override following streaming sounds in the same frame, due to the delay
S_AL_MainStartSound( origin, entnum, entchannel, sfx, flags );
}
/*
=================
S_AL_ClearLoopingSounds
=================
*/
static
void S_AL_ClearLoopingSounds( qboolean killall )
{
int i;
for(i = 0; i < srcCount; i++)
{
if((srcList[i].isLooping) && (srcList[i].entity != -1))
entityList[srcList[i].entity].loopAddedThisFrame = qfalse;
}
}
/*
=================
S_AL_SrcLoop
=================
*/
static void S_AL_SrcLoop( alSrcPriority_t priority, sfxHandle_t sfx,
const vec3_t origin, const vec3_t velocity, int entityNum, int volume )
{
int src;
sentity_t *sent = &entityList[ entityNum ];
src_t *curSource;
vec3_t sorigin, svelocity;
if( entityNum < 0 || entityNum >= MAX_GENTITIES )
return;
if(S_AL_CheckInput(entityNum, sfx))
return;
// Do we need to allocate a new source for this entity
if( !sent->srcAllocated )
{
// Try to get a channel
src = S_AL_SrcAlloc( sfx, priority, entityNum, -1, 0 );
if( src == -1 )
{
Com_DPrintf( S_COLOR_YELLOW "WARNING: Failed to allocate source "
"for loop sfx %d on entity %d\n", sfx, entityNum );
return;
}
curSource = &srcList[src];
sent->startLoopingSound = qtrue;
curSource->lastTimePos = -1.0;
curSource->lastSampleTime = Sys_Milliseconds();
}
else
{
src = sent->srcIndex;
curSource = &srcList[src];
}
sent->srcAllocated = qtrue;
sent->srcIndex = src;
sent->loopPriority = priority;
sent->loopSfx = sfx;
// If this is not set then the looping sound is stopped.
sent->loopAddedThisFrame = qtrue;
// UGH
// These lines should be called via S_AL_SrcSetup, but we
// can't call that yet as it buffers sfxes that may change
// with subsequent calls to S_AL_SrcLoop
curSource->entity = entityNum;
curSource->isLooping = qtrue;
if( S_AL_HearingThroughEntity( entityNum ) )
{
curSource->local = qtrue;
VectorClear(sorigin);
if ( volume > 255 ) {
volume = 255;
} else if ( volume < 0 ) {
volume = 0;
}
qalSourcefv(curSource->alSource, AL_POSITION, sorigin);
qalSourcefv(curSource->alSource, AL_VELOCITY, vec3_origin);
S_AL_Gain(curSource->alSource, volume / 255.0f);
}
else
{
curSource->local = qfalse;
if(origin)
VectorCopy(origin, sorigin);
else
VectorCopy(sent->origin, sorigin);
S_AL_SanitiseVector(sorigin);
VectorCopy(sorigin, curSource->loopSpeakerPos);
if(velocity)
{
VectorCopy(velocity, svelocity);
S_AL_SanitiseVector(svelocity);
}
else
VectorClear(svelocity);
qalSourcefv(curSource->alSource, AL_POSITION, (ALfloat *) sorigin);
qalSourcefv(curSource->alSource, AL_VELOCITY, (ALfloat *) svelocity);
}
}
/*
=================
S_AL_AddLoopingSound
=================
*/
static void S_AL_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, const int range, sfxHandle_t sfx, int volume)
{
S_AL_SrcLoop(SRCPRI_ENTITY, sfx, origin, velocity, entityNum, volume);
}
/*
=================
S_AL_AddRealLoopingSound
=================
*/
static void S_AL_AddRealLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, const int range, sfxHandle_t sfx)
{
S_AL_SrcLoop(SRCPRI_AMBIENT, sfx, origin, velocity, entityNum, 255);
}
/*
=================
S_AL_StopLoopingSound
=================
*/
static
void S_AL_StopLoopingSound(int entityNum )
{
if(entityList[entityNum].srcAllocated)
S_AL_SrcKill(entityList[entityNum].srcIndex);
}
/*
=================
S_AL_SrcUpdate
Update state (move things around, manage sources, and so on)
=================
*/
static
void S_AL_SrcUpdate( void )
{
int i;
int entityNum;
ALint state;
src_t *curSource;
for(i = 0; i < srcCount; i++)
{
entityNum = srcList[i].entity;
curSource = &srcList[i];
if(curSource->isLocked)
continue;
if(!curSource->isActive)
continue;
// Update source parameters
if((s_alGain->modified) || (s_volume->modified))
curSource->curGain = s_alGain->value * s_volume->value;
if((s_alRolloff->modified) && (!curSource->local))
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
if(s_alMinDistance->modified)
qalSourcef(curSource->alSource, AL_REFERENCE_DISTANCE, s_alMinDistance->value);
if(curSource->isLooping)
{
sentity_t *sent = &entityList[ entityNum ];
// If a looping effect hasn't been touched this frame, pause or kill it
if(sent->loopAddedThisFrame)
{
alSfx_t *curSfx;
// The sound has changed without an intervening removal
if(curSource->isActive && !sent->startLoopingSound &&
curSource->sfx != sent->loopSfx)
{
S_AL_NewLoopMaster(curSource, qtrue);
curSource->isPlaying = qfalse;
qalSourceStop(curSource->alSource);
qalSourcei(curSource->alSource, AL_BUFFER, 0);
sent->startLoopingSound = qtrue;
}
// The sound hasn't been started yet
if(sent->startLoopingSound)
{
S_AL_SrcSetup(i, sent->loopSfx, sent->loopPriority,
entityNum, -1, 0, curSource->local);
curSource->isLooping = qtrue;
knownSfx[curSource->sfx].loopCnt++;
sent->startLoopingSound = qfalse;
}
curSfx = &knownSfx[curSource->sfx];
S_AL_ScaleGain(curSource, curSource->loopSpeakerPos);
if(!curSource->scaleGain)
{
if(curSource->isPlaying)
{
// Sound is mute, stop playback until we are in range again
S_AL_NewLoopMaster(curSource, qfalse);
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
else if(!curSfx->loopActiveCnt && curSfx->masterLoopSrc < 0)
curSfx->masterLoopSrc = i;
continue;
}
if(!curSource->isPlaying)
{
qalSourcei(curSource->alSource, AL_LOOPING, AL_TRUE);
curSource->isPlaying = qtrue;
qalSourcePlay(curSource->alSource);
if(curSource->priority == SRCPRI_AMBIENT)
{
// If there are other ambient looping sources with the same sound,
// make sure the sound of these sources are in sync.
if(curSfx->loopActiveCnt)
{
int offset, error;
// we already have a master loop playing, get buffer position.
S_AL_ClearError( qfalse );
qalGetSourcei(srcList[curSfx->masterLoopSrc].alSource, AL_SAMPLE_OFFSET, &offset);
if((error = qalGetError()) != AL_NO_ERROR)
{
if(error != AL_INVALID_ENUM)
{
Com_Printf(S_COLOR_YELLOW "WARNING: Cannot get sample offset from source %d: "
"%s\n", i, S_AL_ErrorMsg(error));
}
}
else
qalSourcei(curSource->alSource, AL_SAMPLE_OFFSET, offset);
}
else if(curSfx->loopCnt && curSfx->masterLoopSrc >= 0)
{
float secofs;
src_t *master = &srcList[curSfx->masterLoopSrc];
// This loop sound used to be played, but all sources are stopped. Use last sample position/time
// to calculate offset so the player thinks the sources continued playing while they were inaudible.
if(master->lastTimePos >= 0)
{
secofs = master->lastTimePos + (Sys_Milliseconds() - master->lastSampleTime) / 1000.0f;
secofs = fmodf(secofs, (float) curSfx->info.samples / curSfx->info.rate);
qalSourcef(curSource->alSource, AL_SEC_OFFSET, secofs);
}
// I be the master now
curSfx->masterLoopSrc = i;
}
else
curSfx->masterLoopSrc = i;
}
else if(curSource->lastTimePos >= 0)
{
float secofs;
// For unsynced loops (SRCPRI_ENTITY) just carry on playing as if the sound was never stopped
secofs = curSource->lastTimePos + (Sys_Milliseconds() - curSource->lastSampleTime) / 1000.0f;
secofs = fmodf(secofs, (float) curSfx->info.samples / curSfx->info.rate);
qalSourcef(curSource->alSource, AL_SEC_OFFSET, secofs);
}
curSfx->loopActiveCnt++;
}
// Update locality
if(curSource->local)
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_TRUE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, 0.0f);
}
else
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_FALSE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
}
}
else if(curSource->priority == SRCPRI_AMBIENT)
{
if(curSource->isPlaying)
{
S_AL_NewLoopMaster(curSource, qfalse);
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
}
else
S_AL_SrcKill(i);
continue;
}
if(!curSource->isStream)
{
// Check if it's done, and flag it
qalGetSourcei(curSource->alSource, AL_SOURCE_STATE, &state);
if(state == AL_STOPPED)
{
curSource->isPlaying = qfalse;
S_AL_SrcKill(i);
continue;
}
}
// Query relativity of source, don't move if it's true
qalGetSourcei(curSource->alSource, AL_SOURCE_RELATIVE, &state);
// See if it needs to be moved
if(curSource->isTracking && !state)
{
qalSourcefv(curSource->alSource, AL_POSITION, entityList[entityNum].origin);
S_AL_ScaleGain(curSource, entityList[entityNum].origin);
}
}
}
/*
=================
S_AL_SrcShutup
=================
*/
static
void S_AL_SrcShutup( void )
{
int i;
for(i = 0; i < srcCount; i++)
S_AL_SrcKill(i);
}
/*
=================
S_AL_SrcGet
=================
*/
static
ALuint S_AL_SrcGet(srcHandle_t src)
{
return srcList[src].alSource;
}
//===========================================================================
// Q3A cinematics use up to 12 buffers at once
#define MAX_STREAM_BUFFERS 20
static srcHandle_t streamSourceHandles[MAX_RAW_STREAMS];
static qboolean streamPlaying[MAX_RAW_STREAMS];
static ALuint streamSources[MAX_RAW_STREAMS];
static ALuint streamBuffers[MAX_RAW_STREAMS][MAX_STREAM_BUFFERS];
static int streamNumBuffers[MAX_RAW_STREAMS];
static int streamBufIndex[MAX_RAW_STREAMS];
/*
=================
S_AL_AllocateStreamChannel
=================
*/
static void S_AL_AllocateStreamChannel(int stream, int entityNum)
{
srcHandle_t cursrc;
ALuint alsrc;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(entityNum >= 0)
{
// This is a stream that tracks an entity
// Allocate a streamSource at normal priority
cursrc = S_AL_SrcAlloc(-1, SRCPRI_ENTITY, entityNum, 0, 0);
if(cursrc < 0)
return;
S_AL_SrcSetup(cursrc, -1, SRCPRI_ENTITY, entityNum, 0, 0, qfalse);
alsrc = S_AL_SrcGet(cursrc);
srcList[cursrc].isTracking = qtrue;
srcList[cursrc].isStream = qtrue;
}
else
{
// Unspatialized stream source
// Allocate a streamSource at high priority
cursrc = S_AL_SrcAlloc(-1, SRCPRI_STREAM, -2, 0, 0);
if(cursrc < 0)
return;
alsrc = S_AL_SrcGet(cursrc);
// Lock the streamSource so nobody else can use it, and get the raw streamSource
S_AL_SrcLock(cursrc);
// make sure that after unmuting the S_AL_Gain in S_Update() does not turn
// volume up prematurely for this source
srcList[cursrc].scaleGain = 0.0f;
// Set some streamSource parameters
qalSourcei (alsrc, AL_BUFFER, 0 );
qalSourcei (alsrc, AL_LOOPING, AL_FALSE );
qalSource3f(alsrc, AL_POSITION, 0.0, 0.0, 0.0);
qalSource3f(alsrc, AL_VELOCITY, 0.0, 0.0, 0.0);
qalSource3f(alsrc, AL_DIRECTION, 0.0, 0.0, 0.0);
qalSourcef (alsrc, AL_ROLLOFF_FACTOR, 0.0 );
qalSourcei (alsrc, AL_SOURCE_RELATIVE, AL_TRUE );
}
streamSourceHandles[stream] = cursrc;
streamSources[stream] = alsrc;
streamNumBuffers[stream] = 0;
streamBufIndex[stream] = 0;
}
/*
=================
S_AL_FreeStreamChannel
=================
*/
static void S_AL_FreeStreamChannel( int stream )
{
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
// Detach any buffers
qalSourcei(streamSources[stream], AL_BUFFER, 0);
// Delete the buffers
if (streamNumBuffers[stream] > 0) {
qalDeleteBuffers(streamNumBuffers[stream], streamBuffers[stream]);
streamNumBuffers[stream] = 0;
}
// Release the output streamSource
S_AL_SrcUnlock(streamSourceHandles[stream]);
S_AL_SrcKill(streamSourceHandles[stream]);
streamSources[stream] = 0;
streamSourceHandles[stream] = -1;
}
/*
=================
S_AL_RawSamples
=================
*/
static
void S_AL_RawSamples(int stream, int samples, int rate, int width, int channels, const byte *data, float volume, int entityNum)
{
int numBuffers;
ALuint buffer;
ALuint format;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
format = S_AL_Format( width, channels );
// Create the streamSource if necessary
if(streamSourceHandles[stream] == -1)
{
S_AL_AllocateStreamChannel(stream, entityNum);
// Failed?
if(streamSourceHandles[stream] == -1)
{
Com_Printf( S_COLOR_RED "ERROR: Can't allocate streaming streamSource\n");
return;
}
}
qalGetSourcei(streamSources[stream], AL_BUFFERS_QUEUED, &numBuffers);
if (numBuffers == MAX_STREAM_BUFFERS)
{
Com_DPrintf(S_COLOR_RED"WARNING: Steam dropping raw samples, reached MAX_STREAM_BUFFERS\n");
return;
}
// Allocate a new AL buffer if needed
if (numBuffers == streamNumBuffers[stream])
{
ALuint oldBuffers[MAX_STREAM_BUFFERS];
int i;
if (!S_AL_GenBuffers(1, &buffer, "stream"))
return;
Com_Memcpy(oldBuffers, &streamBuffers[stream], sizeof (oldBuffers));
// Reorder buffer array in order of oldest to newest
for ( i = 0; i < streamNumBuffers[stream]; ++i )
streamBuffers[stream][i] = oldBuffers[(streamBufIndex[stream] + i) % streamNumBuffers[stream]];
// Add the new buffer to end
streamBuffers[stream][streamNumBuffers[stream]] = buffer;
streamBufIndex[stream] = streamNumBuffers[stream];
streamNumBuffers[stream]++;
}
// Select next buffer in loop
buffer = streamBuffers[stream][ streamBufIndex[stream] ];
streamBufIndex[stream] = (streamBufIndex[stream] + 1) % streamNumBuffers[stream];
// Fill buffer
qalBufferData(buffer, format, (ALvoid *)data, (samples * width * channels), rate);
// Shove the data onto the streamSource
qalSourceQueueBuffers(streamSources[stream], 1, &buffer);
if(entityNum < 0)
{
// Volume
S_AL_Gain (streamSources[stream], volume * s_volume->value * s_alGain->value);
}
// Start stream
if(!streamPlaying[stream])
{
qalSourcePlay( streamSources[stream] );
streamPlaying[stream] = qtrue;
}
}
/*
=================
S_AL_StreamUpdate
=================
*/
static
void S_AL_StreamUpdate( int stream )
{
int numBuffers;
ALint state;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(streamSourceHandles[stream] == -1)
return;
// Un-queue any buffers
qalGetSourcei( streamSources[stream], AL_BUFFERS_PROCESSED, &numBuffers );
while( numBuffers-- )
{
ALuint buffer;
qalSourceUnqueueBuffers(streamSources[stream], 1, &buffer);
}
// Start the streamSource playing if necessary
qalGetSourcei( streamSources[stream], AL_BUFFERS_QUEUED, &numBuffers );
qalGetSourcei(streamSources[stream], AL_SOURCE_STATE, &state);
if(state == AL_STOPPED)
{
streamPlaying[stream] = qfalse;
// If there are no buffers queued up, release the streamSource
if( !numBuffers )
S_AL_FreeStreamChannel( stream );
}
if( !streamPlaying[stream] && numBuffers )
{
qalSourcePlay( streamSources[stream] );
streamPlaying[stream] = qtrue;
}
}
/*
=================
S_AL_StreamDie
=================
*/
static
void S_AL_StreamDie( int stream )
{
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(streamSourceHandles[stream] == -1)
return;
streamPlaying[stream] = qfalse;
qalSourceStop(streamSources[stream]);
S_AL_FreeStreamChannel(stream);
}
//===========================================================================
#define NUM_MUSIC_BUFFERS 4
#define MUSIC_BUFFER_SIZE 4096
static qboolean musicPlaying = qfalse;
static srcHandle_t musicSourceHandle = -1;
static ALuint musicSource;
static ALuint musicBuffers[NUM_MUSIC_BUFFERS];
static snd_stream_t *mus_stream;
static snd_stream_t *intro_stream;
static char s_backgroundLoop[MAX_QPATH];
static byte decode_buffer[MUSIC_BUFFER_SIZE];
/*
=================
S_AL_MusicSourceGet
=================
*/
static void S_AL_MusicSourceGet( void )
{
// Allocate a musicSource at high priority
musicSourceHandle = S_AL_SrcAlloc(-1, SRCPRI_STREAM, -2, 0, 0);
if(musicSourceHandle == -1)
return;
// Lock the musicSource so nobody else can use it, and get the raw musicSource
S_AL_SrcLock(musicSourceHandle);
musicSource = S_AL_SrcGet(musicSourceHandle);
// make sure that after unmuting the S_AL_Gain in S_Update() does not turn
// volume up prematurely for this source
srcList[musicSourceHandle].scaleGain = 0.0f;
// Set some musicSource parameters
qalSource3f(musicSource, AL_POSITION, 0.0, 0.0, 0.0);
qalSource3f(musicSource, AL_VELOCITY, 0.0, 0.0, 0.0);
qalSource3f(musicSource, AL_DIRECTION, 0.0, 0.0, 0.0);
qalSourcef (musicSource, AL_ROLLOFF_FACTOR, 0.0 );
qalSourcei (musicSource, AL_SOURCE_RELATIVE, AL_TRUE );
}
/*
=================
S_AL_MusicSourceFree
=================
*/
static void S_AL_MusicSourceFree( void )
{
// Release the output musicSource
S_AL_SrcUnlock(musicSourceHandle);
S_AL_SrcKill(musicSourceHandle);
musicSource = 0;
musicSourceHandle = -1;
}
/*
=================
S_AL_CloseMusicFiles
=================
*/
static void S_AL_CloseMusicFiles(void)
{
if(intro_stream)
{
S_CodecCloseStream(intro_stream);
intro_stream = NULL;
}
if(mus_stream)
{
S_CodecCloseStream(mus_stream);
mus_stream = NULL;
}
}
/*
=================
S_AL_StopBackgroundTrack
=================
*/
static
void S_AL_StopBackgroundTrack( void )
{
if(!musicPlaying)
return;
// Stop playing
qalSourceStop(musicSource);
// Detach any buffers
qalSourcei(musicSource, AL_BUFFER, 0);
// Delete the buffers
qalDeleteBuffers(NUM_MUSIC_BUFFERS, musicBuffers);
// Free the musicSource
S_AL_MusicSourceFree();
// Unload the stream
S_AL_CloseMusicFiles();
musicPlaying = qfalse;
}
/*
=================
S_AL_MusicProcess
=================
*/
static
void S_AL_MusicProcess(ALuint b)
{
ALenum error;
int l;
ALuint format;
snd_stream_t *curstream;
S_AL_ClearError( qfalse );
if(intro_stream)
curstream = intro_stream;
else
curstream = mus_stream;
if(!curstream)
return;
l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
// Run out data to read, start at the beginning again
if(l == 0)
{
S_CodecCloseStream(curstream);
// the intro stream just finished playing so we don't need to reopen
// the music stream.
if(intro_stream)
intro_stream = NULL;
else
mus_stream = S_CodecOpenStream(s_backgroundLoop);
curstream = mus_stream;
if(!curstream)
{
S_AL_StopBackgroundTrack();
return;
}
l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
}
format = S_AL_Format(curstream->info.width, curstream->info.channels);
if( l == 0 )
{
// We have no data to buffer, so buffer silence
byte dummyData[ 2 ] = { 0 };
qalBufferData( b, AL_FORMAT_MONO16, (void *)dummyData, 2, 22050 );
}
else
qalBufferData(b, format, decode_buffer, l, curstream->info.rate);
if( ( error = qalGetError( ) ) != AL_NO_ERROR )
{
S_AL_StopBackgroundTrack( );
Com_Printf( S_COLOR_RED "ERROR: while buffering data for music stream - %s\n",
S_AL_ErrorMsg( error ) );
return;
}
}
/*
=================
S_AL_StartBackgroundTrack
=================
*/
static
void S_AL_StartBackgroundTrack( const char *intro, const char *loop )
{
int i;
qboolean issame;
Com_DPrintf( "S_AL_StartBackgroundTrack( %s, %s )\n", intro, loop );
// Stop any existing music that might be playing
S_AL_StopBackgroundTrack();
if((!intro || !*intro) && (!loop || !*loop))
return;
// Allocate a musicSource
S_AL_MusicSourceGet();
if(musicSourceHandle == -1)
return;
if (!loop || !*loop)
{
loop = intro;
issame = qtrue;
}
else if(intro && *intro && !strcmp(intro, loop))
issame = qtrue;
else
issame = qfalse;
// Copy the loop over
Q_strncpyz( s_backgroundLoop, loop, sizeof( s_backgroundLoop ) );
if(!issame)
{
// Open the intro and don't mind whether it succeeds.
// The important part is the loop.
intro_stream = S_CodecOpenStream(intro);
}
else
intro_stream = NULL;
mus_stream = S_CodecOpenStream(s_backgroundLoop);
if(!mus_stream)
{
S_AL_CloseMusicFiles();
S_AL_MusicSourceFree();
return;
}
// Generate the musicBuffers
if (!S_AL_GenBuffers(NUM_MUSIC_BUFFERS, musicBuffers, "music"))
return;
// Queue the musicBuffers up
for(i = 0; i < NUM_MUSIC_BUFFERS; i++)
{
S_AL_MusicProcess(musicBuffers[i]);
}
qalSourceQueueBuffers(musicSource, NUM_MUSIC_BUFFERS, musicBuffers);
// Set the initial gain property
S_AL_Gain(musicSource, s_alGain->value * s_musicVolume->value);
// Start playing
qalSourcePlay(musicSource);
musicPlaying = qtrue;
}
/*
=================
S_AL_MusicUpdate
=================
*/
static
void S_AL_MusicUpdate( void )
{
int numBuffers;
ALint state;
if(!musicPlaying)
return;
qalGetSourcei( musicSource, AL_BUFFERS_PROCESSED, &numBuffers );
while( numBuffers-- )
{
ALuint b;
qalSourceUnqueueBuffers(musicSource, 1, &b);
S_AL_MusicProcess(b);
qalSourceQueueBuffers(musicSource, 1, &b);
}
// Hitches can cause OpenAL to be starved of buffers when streaming.
// If this happens, it will stop playback. This restarts the source if
// it is no longer playing, and if there are buffers available
qalGetSourcei( musicSource, AL_SOURCE_STATE, &state );
qalGetSourcei( musicSource, AL_BUFFERS_QUEUED, &numBuffers );
if( state == AL_STOPPED && numBuffers )
{
Com_DPrintf( S_COLOR_YELLOW "Restarted OpenAL music\n" );
qalSourcePlay(musicSource);
}
// Set the gain property
S_AL_Gain(musicSource, s_alGain->value * s_musicVolume->value);
}
/*
======================
S_StartStreamingSound
======================
*/
void S_AL_StartStreamingSound( const char *intro, const char *loop, int entnum, int channel, int attenuation ) {
// FIXME: Stub
}
/*
======================
S_GetVoiceAmplitude
======================
*/
int S_AL_GetVoiceAmplitude( int entityNum ) {
// FIXME: Stub
return 0;
}
//===========================================================================
// Local state variables
static ALCdevice *alDevice;
static ALCcontext *alContext;
#ifdef USE_VOIP
static ALCdevice *alCaptureDevice;
static cvar_t *s_alCapture;
#endif
#ifdef _WIN32
#define ALDRIVER_DEFAULT "OpenAL32.dll"
#elif defined(__APPLE__)
#define ALDRIVER_DEFAULT "libopenal.dylib"
#elif defined(__OpenBSD__)
#define ALDRIVER_DEFAULT "libopenal.so"
#else
#define ALDRIVER_DEFAULT "libopenal.so.1"
#endif
/*
=================
S_AL_ClearSoundBuffer
=================
*/
static
void S_AL_ClearSoundBuffer( void )
{
S_AL_SrcShutdown( );
S_AL_SrcInit( );
}
/*
=================
S_AL_StopAllSounds
=================
*/
static
void S_AL_StopAllSounds( void )
{
int i;
S_AL_SrcShutup();
S_AL_StopBackgroundTrack();
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamDie(i);
S_AL_ClearSoundBuffer();
}
/*
=================
S_AL_Respatialize
=================
*/
static
void S_AL_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], int inwater )
{
float orientation[6];
vec3_t sorigin;
VectorCopy( origin, sorigin );
S_AL_SanitiseVector( sorigin );
S_AL_SanitiseVector( axis[ 0 ] );
S_AL_SanitiseVector( axis[ 1 ] );
S_AL_SanitiseVector( axis[ 2 ] );
orientation[0] = axis[0][0]; orientation[1] = axis[0][1]; orientation[2] = axis[0][2];
orientation[3] = axis[2][0]; orientation[4] = axis[2][1]; orientation[5] = axis[2][2];
lastListenerNumber = entityNum;
VectorCopy( sorigin, lastListenerOrigin );
// Set OpenAL listener paramaters
qalListenerfv(AL_POSITION, (ALfloat *)sorigin);
qalListenerfv(AL_VELOCITY, vec3_origin);
qalListenerfv(AL_ORIENTATION, orientation);
}
/*
=================
S_AL_Update
=================
*/
static
void S_AL_Update( void )
{
int i;
if(s_muted->modified)
{
// muted state changed. Let S_AL_Gain turn up all sources again.
for(i = 0; i < srcCount; i++)
{
if(srcList[i].isActive)
S_AL_Gain(srcList[i].alSource, srcList[i].scaleGain);
}
s_muted->modified = qfalse;
}
// Update SFX channels
S_AL_SrcUpdate();
// Update streams
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamUpdate(i);
S_AL_MusicUpdate();
// Doppler
if(s_doppler->modified)
{
s_alDopplerFactor->modified = qtrue;
s_doppler->modified = qfalse;
}
// Doppler parameters
if(s_alDopplerFactor->modified)
{
if(s_doppler->integer)
qalDopplerFactor(s_alDopplerFactor->value);
else
qalDopplerFactor(0.0f);
s_alDopplerFactor->modified = qfalse;
}
if(s_alDopplerSpeed->modified)
{
qalSpeedOfSound(s_alDopplerSpeed->value);
s_alDopplerSpeed->modified = qfalse;
}
// Clear the modified flags on the other cvars
s_alGain->modified = qfalse;
s_volume->modified = qfalse;
s_musicVolume->modified = qfalse;
s_alMinDistance->modified = qfalse;
s_alRolloff->modified = qfalse;
}
/*
=================
S_AL_DisableSounds
=================
*/
static
void S_AL_DisableSounds( void )
{
S_AL_StopAllSounds();
}
/*
=================
S_AL_BeginRegistration
=================
*/
static
void S_AL_BeginRegistration( void )
{
if(!numSfx)
S_AL_BufferInit();
}
/*
=================
S_AL_SoundList
=================
*/
static
void S_AL_SoundList( void )
{
}
#ifdef USE_VOIP
static
void S_AL_StartCapture( void )
{
if (alCaptureDevice != NULL)
qalcCaptureStart(alCaptureDevice);
}
static
int S_AL_AvailableCaptureSamples( void )
{
int retval = 0;
if (alCaptureDevice != NULL)
{
ALint samples = 0;
qalcGetIntegerv(alCaptureDevice, ALC_CAPTURE_SAMPLES, sizeof (samples), &samples);
retval = (int) samples;
}
return retval;
}
static
void S_AL_Capture( int samples, byte *data )
{
if (alCaptureDevice != NULL)
qalcCaptureSamples(alCaptureDevice, data, samples);
}
void S_AL_StopCapture( void )
{
if (alCaptureDevice != NULL)
qalcCaptureStop(alCaptureDevice);
}
void S_AL_MasterGain( float gain )
{
qalListenerf(AL_GAIN, gain);
}
#endif
/*
=================
S_AL_SoundInfo
=================
*/
static void S_AL_SoundInfo(void)
{
Com_Printf( "OpenAL info:\n" );
Com_Printf( " Vendor: %s\n", qalGetString( AL_VENDOR ) );
Com_Printf( " Version: %s\n", qalGetString( AL_VERSION ) );
Com_Printf( " Renderer: %s\n", qalGetString( AL_RENDERER ) );
Com_Printf( " AL Extensions: %s\n", qalGetString( AL_EXTENSIONS ) );
Com_Printf( " ALC Extensions: %s\n", qalcGetString( alDevice, ALC_EXTENSIONS ) );
if(enumeration_all_ext)
Com_Printf(" Device: %s\n", qalcGetString(alDevice, ALC_ALL_DEVICES_SPECIFIER));
else if(enumeration_ext)
Com_Printf(" Device: %s\n", qalcGetString(alDevice, ALC_DEVICE_SPECIFIER));
if(enumeration_all_ext || enumeration_ext)
Com_Printf(" Available Devices:\n%s", s_alAvailableDevices->string);
#ifdef USE_VOIP
if(capture_ext)
{
#ifdef __APPLE__
Com_Printf(" Input Device: %s\n", qalcGetString(alCaptureDevice, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER));
#else
Com_Printf(" Input Device: %s\n", qalcGetString(alCaptureDevice, ALC_CAPTURE_DEVICE_SPECIFIER));
#endif
Com_Printf(" Available Input Devices:\n%s", s_alAvailableInputDevices->string);
}
#endif
}
/*
=================
S_AL_Shutdown
=================
*/
static
void S_AL_Shutdown( void )
{
// Shut down everything
int i;
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamDie(i);
S_AL_StopBackgroundTrack( );
S_AL_SrcShutdown( );
S_AL_BufferShutdown( );
qalcDestroyContext(alContext);
qalcCloseDevice(alDevice);
#ifdef USE_VOIP
if (alCaptureDevice != NULL) {
qalcCaptureStop(alCaptureDevice);
qalcCaptureCloseDevice(alCaptureDevice);
alCaptureDevice = NULL;
Com_Printf( "OpenAL capture device closed.\n" );
}
#endif
for (i = 0; i < MAX_RAW_STREAMS; i++) {
streamSourceHandles[i] = -1;
streamPlaying[i] = qfalse;
streamSources[i] = 0;
}
QAL_Shutdown();
}
#endif
/*
=================
S_AL_Init
=================
*/
qboolean S_AL_Init( soundInterface_t *si )
{
#ifdef USE_OPENAL
const char* device = NULL;
const char* inputdevice = NULL;
int i;
if( !si ) {
return qfalse;
}
for (i = 0; i < MAX_RAW_STREAMS; i++) {
streamSourceHandles[i] = -1;
streamPlaying[i] = qfalse;
streamSources[i] = 0;
streamNumBuffers[i] = 0;
streamBufIndex[i] = 0;
}
// New console variables
s_alPrecache = Cvar_Get( "s_alPrecache", "1", CVAR_ARCHIVE );
s_alGain = Cvar_Get( "s_alGain", "1.0", CVAR_ARCHIVE );
s_alSources = Cvar_Get( "s_alSources", "128", CVAR_ARCHIVE );
s_alDopplerFactor = Cvar_Get( "s_alDopplerFactor", "1.0", CVAR_ARCHIVE );
s_alDopplerSpeed = Cvar_Get( "s_alDopplerSpeed", "9000", CVAR_ARCHIVE );
s_alMinDistance = Cvar_Get( "s_alMinDistance", "120", CVAR_CHEAT );
s_alMaxDistance = Cvar_Get("s_alMaxDistance", "1024", CVAR_CHEAT);
s_alRolloff = Cvar_Get( "s_alRolloff", "2", CVAR_CHEAT);
s_alGraceDistance = Cvar_Get("s_alGraceDistance", "512", CVAR_CHEAT);
s_alDriver = Cvar_Get( "s_alDriver", ALDRIVER_DEFAULT, CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED );
s_alInputDevice = Cvar_Get( "s_alInputDevice", "", CVAR_ARCHIVE | CVAR_LATCH );
s_alDevice = Cvar_Get("s_alDevice", "", CVAR_ARCHIVE | CVAR_LATCH);
if ( COM_CompareExtension( s_alDriver->string, ".pk3" ) )
{
Com_Printf( "Rejecting DLL named \"%s\"", s_alDriver->string );
return qfalse;
}
// Load QAL
if( !QAL_Init( s_alDriver->string ) )
{
#if defined( _WIN32 )
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) && !QAL_Init( "OpenAL64.dll" ) ) {
#elif defined ( __APPLE__ )
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) && !QAL_Init( "/System/Library/Frameworks/OpenAL.framework/OpenAL" ) ) {
#else
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) || !QAL_Init( ALDRIVER_DEFAULT ) ) {
#endif
return qfalse;
}
}
device = s_alDevice->string;
if(device && !*device)
device = NULL;
inputdevice = s_alInputDevice->string;
if(inputdevice && !*inputdevice)
inputdevice = NULL;
// Device enumeration support
enumeration_all_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT");
enumeration_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT");
if(enumeration_ext || enumeration_all_ext)
{
char devicenames[16384] = "";
const char *devicelist;
#ifdef _WIN32
const char *defaultdevice;
#endif
int curlen;
// get all available devices + the default device name.
if(enumeration_all_ext)
{
devicelist = qalcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_ALL_DEVICES_SPECIFIER);
#endif
}
else
{
// We don't have ALC_ENUMERATE_ALL_EXT but normal enumeration.
devicelist = qalcGetString(NULL, ALC_DEVICE_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
#endif
enumeration_ext = qtrue;
}
#ifdef _WIN32
// check whether the default device is generic hardware. If it is, change to
// Generic Software as that one works more reliably with various sound systems.
// If it's not, use OpenAL's default selection as we don't want to ignore
// native hardware acceleration.
if(!device && defaultdevice && !strcmp(defaultdevice, "Generic Hardware"))
device = "Generic Software";
#endif
// dump a list of available devices to a cvar for the user to see.
if(devicelist)
{
while((curlen = strlen(devicelist)))
{
Q_strcat(devicenames, sizeof(devicenames), devicelist);
Q_strcat(devicenames, sizeof(devicenames), "\n");
devicelist += curlen + 1;
}
}
s_alAvailableDevices = Cvar_Get("s_alAvailableDevices", devicenames, CVAR_ROM | CVAR_NORESTART);
}
alDevice = qalcOpenDevice(device);
if( !alDevice && device )
{
Com_Printf( "Failed to open OpenAL device '%s', trying default.\n", device );
alDevice = qalcOpenDevice(NULL);
}
if( !alDevice )
{
QAL_Shutdown( );
Com_Printf( "Failed to open OpenAL device.\n" );
return qfalse;
}
// Create OpenAL context
alContext = qalcCreateContext( alDevice, NULL );
if( !alContext )
{
QAL_Shutdown( );
qalcCloseDevice( alDevice );
Com_Printf( "Failed to create OpenAL context.\n" );
return qfalse;
}
qalcMakeContextCurrent( alContext );
// Initialize sources, buffers, music
S_AL_BufferInit( );
S_AL_SrcInit( );
// Print this for informational purposes
Com_Printf( "Allocated %d sources.\n", srcCount);
// Set up OpenAL parameters (doppler, etc)
qalDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
qalDopplerFactor( s_alDopplerFactor->value );
qalSpeedOfSound( s_alDopplerSpeed->value );
#ifdef USE_VOIP
// !!! FIXME: some of these alcCaptureOpenDevice() values should be cvars.
// !!! FIXME: add support for capture device enumeration.
// !!! FIXME: add some better error reporting.
s_alCapture = Cvar_Get( "s_alCapture", "1", CVAR_ARCHIVE | CVAR_LATCH );
if (!s_alCapture->integer)
{
Com_Printf("OpenAL capture support disabled by user ('+set s_alCapture 1' to enable)\n");
}
#if USE_MUMBLE
else if (cl_useMumble->integer)
{
Com_Printf("OpenAL capture support disabled for Mumble support\n");
}
#endif
else
{
#ifdef __APPLE__
// !!! FIXME: Apple has a 1.1-compliant OpenAL, which includes
// !!! FIXME: capture support, but they don't list it in the
// !!! FIXME: extension string. We need to check the version string,
// !!! FIXME: then the extension string, but that's too much trouble,
// !!! FIXME: so we'll just check the function pointer for now.
if (qalcCaptureOpenDevice == NULL)
#else
if (!qalcIsExtensionPresent(NULL, "ALC_EXT_capture"))
#endif
{
Com_Printf("No ALC_EXT_capture support, can't record audio.\n");
}
else
{
char inputdevicenames[16384] = "";
const char *inputdevicelist;
const char *defaultinputdevice;
int curlen;
capture_ext = qtrue;
// get all available input devices + the default input device name.
inputdevicelist = qalcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER);
defaultinputdevice = qalcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
// dump a list of available devices to a cvar for the user to see.
if (inputdevicelist)
{
while((curlen = strlen(inputdevicelist)))
{
Q_strcat(inputdevicenames, sizeof(inputdevicenames), inputdevicelist);
Q_strcat(inputdevicenames, sizeof(inputdevicenames), "\n");
inputdevicelist += curlen + 1;
}
}
s_alAvailableInputDevices = Cvar_Get("s_alAvailableInputDevices", inputdevicenames, CVAR_ROM | CVAR_NORESTART);
Com_Printf("OpenAL default capture device is '%s'\n", defaultinputdevice ? defaultinputdevice : "none");
alCaptureDevice = qalcCaptureOpenDevice(inputdevice, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
if( !alCaptureDevice && inputdevice )
{
Com_Printf( "Failed to open OpenAL Input device '%s', trying default.\n", inputdevice );
alCaptureDevice = qalcCaptureOpenDevice(NULL, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
}
Com_Printf( "OpenAL capture device %s.\n",
(alCaptureDevice == NULL) ? "failed to open" : "opened");
}
}
#endif
si->Shutdown = S_AL_Shutdown;
si->StartSound = S_AL_StartSound;
si->StartSoundEx = S_AL_StartSoundEx;
si->StartLocalSound = S_AL_StartLocalSound;
si->StartBackgroundTrack = S_AL_StartBackgroundTrack;
si->StopBackgroundTrack = S_AL_StopBackgroundTrack;
si->StartStreamingSound = S_AL_StartStreamingSound;
si->GetVoiceAmplitude = S_AL_GetVoiceAmplitude;
si->RawSamples = S_AL_RawSamples;
si->StopAllSounds = S_AL_StopAllSounds;
si->ClearLoopingSounds = S_AL_ClearLoopingSounds;
si->AddLoopingSound = S_AL_AddLoopingSound;
si->AddRealLoopingSound = S_AL_AddRealLoopingSound;
si->StopLoopingSound = S_AL_StopLoopingSound;
si->Respatialize = S_AL_Respatialize;
si->UpdateEntityPosition = S_AL_UpdateEntityPosition;
si->Update = S_AL_Update;
si->DisableSounds = S_AL_DisableSounds;
si->BeginRegistration = S_AL_BeginRegistration;
si->RegisterSound = S_AL_RegisterSound;
si->ClearSoundBuffer = S_AL_ClearSoundBuffer;
si->SoundInfo = S_AL_SoundInfo;
si->SoundList = S_AL_SoundList;
#ifdef USE_VOIP
si->StartCapture = S_AL_StartCapture;
si->AvailableCaptureSamples = S_AL_AvailableCaptureSamples;
si->Capture = S_AL_Capture;
si->StopCapture = S_AL_StopCapture;
si->MasterGain = S_AL_MasterGain;
#endif
return qtrue;
#else
return qfalse;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3232_0 |
crossvul-cpp_data_bad_3231_1 | /*
===========================================================================
Return to Castle Wolfenstein multiplayer GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (RTCW MP Source Code).
RTCW MP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW MP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW MP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
// common.c -- misc functions used in client and server
#include "q_shared.h"
#include "qcommon.h"
#include <setjmp.h>
#ifndef _WIN32
#include <netinet/in.h>
#include <sys/stat.h> // umask
#else
#include <winsock.h>
#endif
int demo_protocols[] =
{ 59, 58, 57, 0 };
#define MAX_NUM_ARGVS 50
#define MIN_DEDICATED_COMHUNKMEGS 1
#define MIN_COMHUNKMEGS 128 // JPW NERVE changed this to 42 for MP, was 56 for team arena and 75 for wolfSP
#define DEF_COMHUNKMEGS 256 // RF, increased this, some maps are exceeding 56mb // JPW NERVE changed this for multiplayer back to 42, 56 for depot/mp_cpdepot, 42 for everything else
#define DEF_COMZONEMEGS 32 // JPW NERVE cut this back too was 30
#define DEF_COMHUNKMEGS_S XSTRING(DEF_COMHUNKMEGS)
#define DEF_COMZONEMEGS_S XSTRING(DEF_COMZONEMEGS)
int com_argc;
char *com_argv[MAX_NUM_ARGVS + 1];
jmp_buf abortframe; // an ERR_DROP occured, exit the entire frame
FILE *debuglogfile;
static fileHandle_t pipefile;
static fileHandle_t logfile;
fileHandle_t com_journalFile; // events are written here
fileHandle_t com_journalDataFile; // config files are written here
cvar_t *com_speeds;
cvar_t *com_developer;
cvar_t *com_dedicated;
cvar_t *com_timescale;
cvar_t *com_fixedtime;
cvar_t *com_journal;
cvar_t *com_maxfps;
cvar_t *com_altivec;
cvar_t *com_timedemo;
cvar_t *com_sv_running;
cvar_t *com_cl_running;
cvar_t *com_logfile; // 1 = buffer log, 2 = flush after each print
cvar_t *com_pipefile;
cvar_t *com_showtrace;
cvar_t *com_fsgame;
cvar_t *com_version;
cvar_t *com_legacyversion;
cvar_t *com_blood;
cvar_t *com_buildScript; // for automated data building scripts
#ifdef CINEMATICS_INTRO
cvar_t *com_introPlayed;
#endif
cvar_t *cl_paused;
cvar_t *sv_paused;
cvar_t *cl_packetdelay;
cvar_t *sv_packetdelay;
cvar_t *com_cameraMode;
cvar_t *com_recommendedSet;
// Rafael Notebook
cvar_t *cl_notebook;
cvar_t *com_hunkused; // Ridah
cvar_t *com_ansiColor;
cvar_t *com_unfocused;
cvar_t *com_maxfpsUnfocused;
cvar_t *com_minimized;
cvar_t *com_maxfpsMinimized;
cvar_t *com_abnormalExit;
cvar_t *com_standalone;
cvar_t *com_gamename;
cvar_t *com_protocol;
#ifdef LEGACY_PROTOCOL
cvar_t *com_legacyprotocol;
#endif
cvar_t *com_basegame;
cvar_t *com_homepath;
cvar_t *com_busyWait;
#if idx64
int (*Q_VMftol)(void);
#elif id386
long (QDECL *Q_ftol)(float f);
int (QDECL *Q_VMftol)(void);
void (QDECL *Q_SnapVector)(vec3_t vec);
#endif
// com_speeds times
int time_game;
int time_frontend; // renderer frontend time
int time_backend; // renderer backend time
int com_frameTime;
int com_frameNumber;
qboolean com_errorEntered = qfalse;
qboolean com_fullyInitialized = qfalse;
qboolean com_gameRestarting = qfalse;
qboolean com_gameClientRestarting = qfalse;
char com_errorMessage[MAXPRINTMSG];
void Com_WriteConfig_f( void );
void CIN_CloseAllVideos( void );
//============================================================================
static char *rd_buffer;
static int rd_buffersize;
static void ( *rd_flush )( char *buffer );
void Com_BeginRedirect( char *buffer, int buffersize, void ( *flush )( char *) ) {
if ( !buffer || !buffersize || !flush ) {
return;
}
rd_buffer = buffer;
rd_buffersize = buffersize;
rd_flush = flush;
*rd_buffer = 0;
}
void Com_EndRedirect( void ) {
if ( rd_flush ) {
rd_flush( rd_buffer );
}
rd_buffer = NULL;
rd_buffersize = 0;
rd_flush = NULL;
}
/*
=============
Com_Printf
Both client and server can use this, and it will output
to the apropriate place.
A raw string should NEVER be passed as fmt, because of "%f" type crashers.
=============
*/
void QDECL Com_Printf( const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
static qboolean opening_qconsole = qfalse;
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof( msg ), fmt, argptr );
va_end( argptr );
if ( rd_buffer ) {
if ( ( strlen( msg ) + strlen( rd_buffer ) ) > ( rd_buffersize - 1 ) ) {
rd_flush( rd_buffer );
*rd_buffer = 0;
}
Q_strcat( rd_buffer, rd_buffersize, msg );
// show_bug.cgi?id=51
// only flush the rcon buffer when it's necessary, avoid fragmenting
//rd_flush(rd_buffer);
//*rd_buffer = 0;
return;
}
#ifndef DEDICATED
CL_ConsolePrint( msg );
#endif
// echo to dedicated console and early console
Sys_Print( msg );
// logfile
if ( com_logfile && com_logfile->integer ) {
// TTimo: only open the qconsole.log if the filesystem is in an initialized state
// also, avoid recursing in the qconsole.log opening (i.e. if fs_debug is on)
if ( !logfile && FS_Initialized() && !opening_qconsole ) {
struct tm *newtime;
time_t aclock;
opening_qconsole = qtrue;
time( &aclock );
newtime = localtime( &aclock );
logfile = FS_FOpenFileWrite( "rtcwconsole.log" );
if(logfile)
{
Com_Printf( "logfile opened on %s\n", asctime( newtime ) );
if ( com_logfile->integer > 1 )
{
// force it to not buffer so we get valid
// data even if we are crashing
FS_ForceFlush(logfile);
}
}
else
{
Com_Printf("Opening rtcwconsole.log failed!\n");
Cvar_SetValue("logfile", 0);
}
opening_qconsole = qfalse;
}
if ( logfile && FS_Initialized() ) {
FS_Write( msg, strlen( msg ), logfile );
}
}
}
/*
================
Com_DPrintf
A Com_Printf that only shows up if the "developer" cvar is set
================
*/
void QDECL Com_DPrintf( const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
if ( !com_developer || !com_developer->integer ) {
return; // don't confuse non-developers with techie stuff...
}
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof( msg ), fmt, argptr );
va_end( argptr );
Com_Printf( "%s", msg );
}
/*
=============
Com_Error
Both client and server can use this, and it will
do the appropriate thing.
=============
*/
void QDECL Com_Error( int code, const char *fmt, ... ) {
va_list argptr;
static int lastErrorTime;
static int errorCount;
int currentTime;
qboolean restartClient;
if(com_errorEntered)
Sys_Error("recursive error after: %s", com_errorMessage);
com_errorEntered = qtrue;
Cvar_Set("com_errorCode", va("%i", code));
// when we are running automated scripts, make sure we
// know if anything failed
if ( com_buildScript && com_buildScript->integer ) {
code = ERR_FATAL;
}
// if we are getting a solid stream of ERR_DROP, do an ERR_FATAL
currentTime = Sys_Milliseconds();
if ( currentTime - lastErrorTime < 100 ) {
if ( ++errorCount > 3 ) {
code = ERR_FATAL;
}
} else {
errorCount = 0;
}
lastErrorTime = currentTime;
va_start( argptr,fmt );
Q_vsnprintf (com_errorMessage, sizeof(com_errorMessage),fmt,argptr);
va_end( argptr );
if (code != ERR_DISCONNECT && code != ERR_NEED_CD)
Cvar_Set( "com_errorMessage", com_errorMessage );
restartClient = com_gameClientRestarting && !( com_cl_running && com_cl_running->integer );
com_gameRestarting = qfalse;
com_gameClientRestarting = qfalse;
if (code == ERR_DISCONNECT || code == ERR_SERVERDISCONNECT) {
VM_Forced_Unload_Start();
SV_Shutdown( "Server disconnected" );
if ( restartClient ) {
CL_Init();
}
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
// make sure we can get at our local stuff
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else if (code == ERR_DROP) {
Com_Printf( "********************\nERROR: %s\n********************\n", com_errorMessage );
VM_Forced_Unload_Start();
SV_Shutdown (va("Server crashed: %s", com_errorMessage));
if ( restartClient ) {
CL_Init();
}
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else if ( code == ERR_NEED_CD ) {
VM_Forced_Unload_Start();
SV_Shutdown( "Server didn't have CD" );
if ( restartClient ) {
CL_Init();
}
if ( com_cl_running && com_cl_running->integer ) {
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
CL_CDDialog();
} else {
Com_Printf( "Server didn't have CD\n" );
VM_Forced_Unload_Done();
}
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else {
VM_Forced_Unload_Start();
CL_Shutdown(va("Client fatal crashed: %s", com_errorMessage), qtrue, qtrue);
SV_Shutdown(va("Server fatal crashed: %s", com_errorMessage));
VM_Forced_Unload_Done();
}
Com_Shutdown();
Sys_Error( "%s", com_errorMessage );
}
/*
=============
Com_Quit_f
Both client and server can use this, and it will
do the apropriate things.
=============
*/
void Com_Quit_f( void ) {
// don't try to shutdown if we are in a recursive error
char *p = Cmd_Args( );
if ( !com_errorEntered ) {
// Some VMs might execute "quit" command directly,
// which would trigger an unload of active VM error.
// Sys_Quit will kill this process anyways, so
// a corrupt call stack makes no difference
VM_Forced_Unload_Start();
SV_Shutdown(p[0] ? p : "Server quit");
CL_Shutdown(p[0] ? p : "Client quit", qtrue, qtrue);
VM_Forced_Unload_Done();
Com_Shutdown();
FS_Shutdown( qtrue );
}
Sys_Quit();
}
/*
============================================================================
COMMAND LINE FUNCTIONS
+ characters seperate the commandLine string into multiple console
command lines.
All of these are valid:
quake3 +set test blah +map test
quake3 set test blah+map test
quake3 set test blah + map test
============================================================================
*/
#define MAX_CONSOLE_LINES 32
int com_numConsoleLines;
char *com_consoleLines[MAX_CONSOLE_LINES];
/*
==================
Com_ParseCommandLine
Break it up into multiple console lines
==================
*/
void Com_ParseCommandLine( char *commandLine ) {
com_consoleLines[0] = commandLine;
com_numConsoleLines = 1;
while ( *commandLine ) {
// look for a + separating character
// if commandLine came from a file, we might have real line seperators
if ( *commandLine == '+' || *commandLine == '\n' ) {
if ( com_numConsoleLines == MAX_CONSOLE_LINES ) {
return;
}
com_consoleLines[com_numConsoleLines] = commandLine + 1;
com_numConsoleLines++;
*commandLine = 0;
}
commandLine++;
}
}
/*
===================
Com_SafeMode
Check for "safe" on the command line, which will
skip loading of wolfconfig.cfg
===================
*/
qboolean Com_SafeMode( void ) {
int i;
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
Cmd_TokenizeString( com_consoleLines[i] );
if ( !Q_stricmp( Cmd_Argv( 0 ), "safe" )
|| !Q_stricmp( Cmd_Argv( 0 ), "cvar_restart" ) ) {
com_consoleLines[i][0] = 0;
return qtrue;
}
}
return qfalse;
}
/*
===============
Com_StartupVariable
Searches for command line parameters that are set commands.
If match is not NULL, only that cvar will be looked for.
That is necessary because cddir and basedir need to be set
before the filesystem is started, but all other sets should
be after execing the config and default.
===============
*/
void Com_StartupVariable( const char *match ) {
int i;
char *s;
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
Cmd_TokenizeString( com_consoleLines[i] );
if ( strcmp( Cmd_Argv( 0 ), "set" ) ) {
continue;
}
s = Cmd_Argv( 1 );
if(!match || !strcmp(s, match))
{
if(Cvar_Flags(s) == CVAR_NONEXISTENT)
Cvar_Get(s, Cmd_ArgsFrom(2), CVAR_USER_CREATED);
else
Cvar_Set2(s, Cmd_ArgsFrom(2), qfalse);
}
}
}
/*
=================
Com_AddStartupCommands
Adds command line parameters as script statements
Commands are seperated by + signs
Returns qtrue if any late commands were added, which
will keep the demoloop from immediately starting
=================
*/
qboolean Com_AddStartupCommands( void ) {
int i;
qboolean added;
added = qfalse;
// quote every token, so args with semicolons can work
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
if ( !com_consoleLines[i] || !com_consoleLines[i][0] ) {
continue;
}
// set commands already added with Com_StartupVariable
if ( !Q_stricmpn( com_consoleLines[i], "set ", 4 ) ) {
continue;
}
added = qtrue;
Cbuf_AddText( com_consoleLines[i] );
Cbuf_AddText( "\n" );
}
return added;
}
//============================================================================
void Info_Print( const char *s ) {
char key[BIG_INFO_KEY];
char value[BIG_INFO_VALUE];
char *o;
int l;
if ( *s == '\\' ) {
s++;
}
while ( *s )
{
o = key;
while ( *s && *s != '\\' )
*o++ = *s++;
l = o - key;
if ( l < 20 ) {
memset( o, ' ', 20 - l );
key[20] = 0;
} else {
*o = 0;
}
Com_Printf( "%s ", key );
if ( !*s ) {
Com_Printf( "MISSING VALUE\n" );
return;
}
o = value;
s++;
while ( *s && *s != '\\' )
*o++ = *s++;
*o = 0;
if ( *s ) {
s++;
}
Com_Printf( "%s\n", value );
}
}
/*
============
Com_StringContains
============
*/
char *Com_StringContains( char *str1, char *str2, int casesensitive ) {
int len, i, j;
len = strlen( str1 ) - strlen( str2 );
for ( i = 0; i <= len; i++, str1++ ) {
for ( j = 0; str2[j]; j++ ) {
if ( casesensitive ) {
if ( str1[j] != str2[j] ) {
break;
}
} else {
if ( toupper( str1[j] ) != toupper( str2[j] ) ) {
break;
}
}
}
if ( !str2[j] ) {
return str1;
}
}
return NULL;
}
/*
============
Com_Filter
============
*/
int Com_Filter( char *filter, char *name, int casesensitive ) {
char buf[MAX_TOKEN_CHARS];
char *ptr;
int i, found;
while ( *filter ) {
if ( *filter == '*' ) {
filter++;
for ( i = 0; *filter; i++ ) {
if ( *filter == '*' || *filter == '?' ) {
break;
}
buf[i] = *filter;
filter++;
}
buf[i] = '\0';
if ( strlen( buf ) ) {
ptr = Com_StringContains( name, buf, casesensitive );
if ( !ptr ) {
return qfalse;
}
name = ptr + strlen( buf );
}
} else if ( *filter == '?' ) {
filter++;
name++;
} else if ( *filter == '[' && *( filter + 1 ) == '[' ) {
filter++;
} else if ( *filter == '[' ) {
filter++;
found = qfalse;
while ( *filter && !found ) {
if ( *filter == ']' && *( filter + 1 ) != ']' ) {
break;
}
if ( *( filter + 1 ) == '-' && *( filter + 2 ) && ( *( filter + 2 ) != ']' || *( filter + 3 ) == ']' ) ) {
if ( casesensitive ) {
if ( *name >= *filter && *name <= *( filter + 2 ) ) {
found = qtrue;
}
} else {
if ( toupper( *name ) >= toupper( *filter ) &&
toupper( *name ) <= toupper( *( filter + 2 ) ) ) {
found = qtrue;
}
}
filter += 3;
} else {
if ( casesensitive ) {
if ( *filter == *name ) {
found = qtrue;
}
} else {
if ( toupper( *filter ) == toupper( *name ) ) {
found = qtrue;
}
}
filter++;
}
}
if ( !found ) {
return qfalse;
}
while ( *filter ) {
if ( *filter == ']' && *( filter + 1 ) != ']' ) {
break;
}
filter++;
}
filter++;
name++;
} else {
if ( casesensitive ) {
if ( *filter != *name ) {
return qfalse;
}
} else {
if ( toupper( *filter ) != toupper( *name ) ) {
return qfalse;
}
}
filter++;
name++;
}
}
return qtrue;
}
/*
============
Com_FilterPath
============
*/
int Com_FilterPath( char *filter, char *name, int casesensitive ) {
int i;
char new_filter[MAX_QPATH];
char new_name[MAX_QPATH];
for ( i = 0; i < MAX_QPATH - 1 && filter[i]; i++ ) {
if ( filter[i] == '\\' || filter[i] == ':' ) {
new_filter[i] = '/';
} else {
new_filter[i] = filter[i];
}
}
new_filter[i] = '\0';
for ( i = 0; i < MAX_QPATH - 1 && name[i]; i++ ) {
if ( name[i] == '\\' || name[i] == ':' ) {
new_name[i] = '/';
} else {
new_name[i] = name[i];
}
}
new_name[i] = '\0';
return Com_Filter( new_filter, new_name, casesensitive );
}
/*
================
Com_RealTime
================
*/
int Com_RealTime( qtime_t *qtime ) {
time_t t;
struct tm *tms;
t = time( NULL );
if ( !qtime ) {
return t;
}
tms = localtime( &t );
if ( tms ) {
qtime->tm_sec = tms->tm_sec;
qtime->tm_min = tms->tm_min;
qtime->tm_hour = tms->tm_hour;
qtime->tm_mday = tms->tm_mday;
qtime->tm_mon = tms->tm_mon;
qtime->tm_year = tms->tm_year;
qtime->tm_wday = tms->tm_wday;
qtime->tm_yday = tms->tm_yday;
qtime->tm_isdst = tms->tm_isdst;
}
return t;
}
/*
==============================================================================
ZONE MEMORY ALLOCATION
There is never any space between memblocks, and there will never be two
contiguous free memblocks.
The rover can be left pointing at a non-empty block
The zone calls are pretty much only used for small strings and structures,
all big things are allocated on the hunk.
==============================================================================
*/
#define ZONEID 0x1d4a11
#define MINFRAGMENT 64
typedef struct zonedebug_s {
char *label;
char *file;
int line;
int allocSize;
} zonedebug_t;
typedef struct memblock_s {
int size; // including the header and possibly tiny fragments
int tag; // a tag of 0 is a free block
struct memblock_s *next, *prev;
int id; // should be ZONEID
#ifdef ZONE_DEBUG
zonedebug_t d;
#endif
} memblock_t;
typedef struct {
int size; // total bytes malloced, including header
int used; // total bytes used
memblock_t blocklist; // start / end cap for linked list
memblock_t *rover;
} memzone_t;
// main zone for all "dynamic" memory allocation
memzone_t *mainzone;
// we also have a small zone for small allocations that would only
// fragment the main zone (think of cvar and cmd strings)
memzone_t *smallzone;
void Z_CheckHeap( void );
/*
========================
Z_ClearZone
========================
*/
void Z_ClearZone( memzone_t *zone, int size ) {
memblock_t *block;
// set the entire zone to one free block
zone->blocklist.next = zone->blocklist.prev = block =
( memblock_t * )( (byte *)zone + sizeof( memzone_t ) );
zone->blocklist.tag = 1; // in use block
zone->blocklist.id = 0;
zone->blocklist.size = 0;
zone->rover = block;
zone->size = size;
zone->used = 0;
block->prev = block->next = &zone->blocklist;
block->tag = 0; // free block
block->id = ZONEID;
block->size = size - sizeof( memzone_t );
}
/*
========================
Z_Free
========================
*/
void Z_Free( void *ptr ) {
memblock_t *block, *other;
memzone_t *zone;
if ( !ptr ) {
Com_Error( ERR_DROP, "Z_Free: NULL pointer" );
}
block = ( memblock_t * )( (byte *)ptr - sizeof( memblock_t ) );
if ( block->id != ZONEID ) {
Com_Error( ERR_FATAL, "Z_Free: freed a pointer without ZONEID" );
}
if ( block->tag == 0 ) {
Com_Error( ERR_FATAL, "Z_Free: freed a freed pointer" );
}
// if static memory
if ( block->tag == TAG_STATIC ) {
return;
}
// check the memory trash tester
if ( *( int * )( (byte *)block + block->size - 4 ) != ZONEID ) {
Com_Error( ERR_FATAL, "Z_Free: memory block wrote past end" );
}
if ( block->tag == TAG_SMALL ) {
zone = smallzone;
} else {
zone = mainzone;
}
zone->used -= block->size;
// set the block to something that should cause problems
// if it is referenced...
memset( ptr, 0xaa, block->size - sizeof( *block ) );
block->tag = 0; // mark as free
other = block->prev;
if ( !other->tag ) {
// merge with previous free block
other->size += block->size;
other->next = block->next;
other->next->prev = other;
if ( block == zone->rover ) {
zone->rover = other;
}
block = other;
}
zone->rover = block;
other = block->next;
if ( !other->tag ) {
// merge the next free block onto the end
block->size += other->size;
block->next = other->next;
block->next->prev = block;
}
}
/*
================
Z_FreeTags
================
*/
void Z_FreeTags( int tag ) {
int count;
memzone_t *zone;
if ( tag == TAG_SMALL ) {
zone = smallzone;
} else {
zone = mainzone;
}
count = 0;
// use the rover as our pointer, because
// Z_Free automatically adjusts it
zone->rover = zone->blocklist.next;
do {
if ( zone->rover->tag == tag ) {
count++;
Z_Free( ( void * )( zone->rover + 1 ) );
continue;
}
zone->rover = zone->rover->next;
} while ( zone->rover != &zone->blocklist );
}
/*
================
Z_TagMalloc
================
*/
memblock_t *debugblock; // RF, jusy so we can track a block to find out when it's getting trashed
#ifdef ZONE_DEBUG
void *Z_TagMallocDebug( int size, int tag, char *label, char *file, int line ) {
int allocSize;
#else
void *Z_TagMalloc( int size, int tag ) {
#endif
int extra;
memblock_t *start, *rover, *new, *base;
memzone_t *zone;
if ( !tag ) {
Com_Error( ERR_FATAL, "Z_TagMalloc: tried to use a 0 tag" );
}
if ( tag == TAG_SMALL ) {
zone = smallzone;
} else {
zone = mainzone;
}
#ifdef ZONE_DEBUG
allocSize = size;
#endif
//
// scan through the block list looking for the first free block
// of sufficient size
//
size += sizeof( memblock_t ); // account for size of block header
size += 4; // space for memory trash tester
size = PAD(size, sizeof(intptr_t)); // align to 32/64 bit boundary
base = rover = zone->rover;
start = base->prev;
do {
if ( rover == start ) {
// scaned all the way around the list
#ifdef ZONE_DEBUG
Z_LogHeap();
Com_Error(ERR_FATAL, "Z_Malloc: failed on allocation of %i bytes from the %s zone: %s, line: %d (%s)",
size, zone == smallzone ? "small" : "main", file, line, label);
#else
Com_Error(ERR_FATAL, "Z_Malloc: failed on allocation of %i bytes from the %s zone",
size, zone == smallzone ? "small" : "main" );
#endif
return NULL;
}
if ( rover->tag ) {
base = rover = rover->next;
} else {
rover = rover->next;
}
} while ( base->tag || base->size < size );
//
// found a block big enough
//
extra = base->size - size;
if ( extra > MINFRAGMENT ) {
// there will be a free fragment after the allocated block
new = ( memblock_t * )( (byte *)base + size );
new->size = extra;
new->tag = 0; // free block
new->prev = base;
new->id = ZONEID;
new->next = base->next;
new->next->prev = new;
base->next = new;
base->size = size;
}
base->tag = tag; // no longer a free block
zone->rover = base->next; // next allocation will start looking here
zone->used += base->size; //
base->id = ZONEID;
#ifdef ZONE_DEBUG
base->d.label = label;
base->d.file = file;
base->d.line = line;
base->d.allocSize = allocSize;
#endif
// marker for memory trash testing
*( int * )( (byte *)base + base->size - 4 ) = ZONEID;
return ( void * )( (byte *)base + sizeof( memblock_t ) );
}
/*
========================
Z_Malloc
========================
*/
#ifdef ZONE_DEBUG
void *Z_MallocDebug( int size, char *label, char *file, int line ) {
#else
void *Z_Malloc( int size ) {
#endif
void *buf;
//Z_CheckHeap (); // DEBUG
#ifdef ZONE_DEBUG
buf = Z_TagMallocDebug( size, TAG_GENERAL, label, file, line );
#else
buf = Z_TagMalloc( size, TAG_GENERAL );
#endif
Com_Memset( buf, 0, size );
return buf;
}
#ifdef ZONE_DEBUG
void *S_MallocDebug( int size, char *label, char *file, int line ) {
return Z_TagMallocDebug( size, TAG_SMALL, label, file, line );
}
#else
void *S_Malloc( int size ) {
return Z_TagMalloc( size, TAG_SMALL );
}
#endif
/*
========================
Z_CheckHeap
========================
*/
void Z_CheckHeap( void ) {
memblock_t *block;
for ( block = mainzone->blocklist.next ; ; block = block->next ) {
if ( block->next == &mainzone->blocklist ) {
break; // all blocks have been hit
}
if ( (byte *)block + block->size != (byte *)block->next ) {
Com_Error( ERR_FATAL, "Z_CheckHeap: block size does not touch the next block" );
}
if ( block->next->prev != block ) {
Com_Error( ERR_FATAL, "Z_CheckHeap: next block doesn't have proper back link" );
}
if ( !block->tag && !block->next->tag ) {
Com_Error( ERR_FATAL, "Z_CheckHeap: two consecutive free blocks" );
}
}
}
/*
========================
Z_LogZoneHeap
========================
*/
void Z_LogZoneHeap( memzone_t *zone, char *name ) {
#ifdef ZONE_DEBUG
char dump[32], *ptr;
int i, j;
#endif
memblock_t *block;
char buf[4096];
int size, allocSize, numBlocks;
if ( !logfile || !FS_Initialized() ) {
return;
}
size = numBlocks = 0;
#ifdef ZONE_DEBUG
allocSize = 0;
#endif
Com_sprintf( buf, sizeof( buf ), "\r\n================\r\n%s log\r\n================\r\n", name );
FS_Write( buf, strlen( buf ), logfile );
for ( block = zone->blocklist.next ; block->next != &zone->blocklist; block = block->next ) {
if ( block->tag ) {
#ifdef ZONE_DEBUG
ptr = ( (char *) block ) + sizeof( memblock_t );
j = 0;
for ( i = 0; i < 20 && i < block->d.allocSize; i++ ) {
if ( ptr[i] >= 32 && ptr[i] < 127 ) {
dump[j++] = ptr[i];
} else {
dump[j++] = '_';
}
}
dump[j] = '\0';
Com_sprintf( buf, sizeof( buf ), "size = %8d: %s, line: %d (%s) [%s]\r\n", block->d.allocSize, block->d.file, block->d.line, block->d.label, dump );
FS_Write( buf, strlen( buf ), logfile );
allocSize += block->d.allocSize;
#endif
size += block->size;
numBlocks++;
}
}
#ifdef ZONE_DEBUG
// subtract debug memory
size -= numBlocks * sizeof( zonedebug_t );
#else
allocSize = numBlocks * sizeof( memblock_t ); // + 32 bit alignment
#endif
Com_sprintf( buf, sizeof( buf ), "%d %s memory in %d blocks\r\n", size, name, numBlocks );
FS_Write( buf, strlen( buf ), logfile );
Com_sprintf( buf, sizeof( buf ), "%d %s memory overhead\r\n", size - allocSize, name );
FS_Write( buf, strlen( buf ), logfile );
}
/*
========================
Z_LogHeap
========================
*/
void Z_LogHeap( void ) {
Z_LogZoneHeap( mainzone, "MAIN" );
Z_LogZoneHeap( smallzone, "SMALL" );
}
// static mem blocks to reduce a lot of small zone overhead
typedef struct memstatic_s {
memblock_t b;
byte mem[2];
} memstatic_t;
memstatic_t emptystring =
{ {( sizeof( memblock_t ) + 2 + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'\0', '\0'} };
memstatic_t numberstring[] = {
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'0', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'1', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'2', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'3', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'4', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'5', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'6', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'7', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'8', '\0'} },
{ {( sizeof( memstatic_t ) + 3 ) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'9', '\0'} }
};
/*
========================
CopyString
NOTE: never write over the memory CopyString returns because
memory from a memstatic_t might be returned
========================
*/
char *CopyString( const char *in ) {
char *out;
if ( !in[0] ) {
return ( (char *)&emptystring ) + sizeof( memblock_t );
} else if ( !in[1] ) {
if ( in[0] >= '0' && in[0] <= '9' ) {
return ( (char *)&numberstring[in[0] - '0'] ) + sizeof( memblock_t );
}
}
out = S_Malloc( strlen( in ) + 1 );
strcpy( out, in );
return out;
}
/*
==============================================================================
Goals:
reproducable without history effects -- no out of memory errors on weird map to map changes
allow restarting of the client without fragmentation
minimize total pages in use at run time
minimize total pages needed during load time
Single block of memory with stack allocators coming from both ends towards the middle.
One side is designated the temporary memory allocator.
Temporary memory can be allocated and freed in any order.
A highwater mark is kept of the most in use at any time.
When there is no temporary memory allocated, the permanent and temp sides
can be switched, allowing the already touched temp memory to be used for
permanent storage.
Temp memory must never be allocated on two ends at once, or fragmentation
could occur.
If we have any in-use temp memory, additional temp allocations must come from
that side.
If not, we can choose to make either side the new temp side and push future
permanent allocations to the other side. Permanent allocations should be
kept on the side that has the current greatest wasted highwater mark.
==============================================================================
*/
#define HUNK_MAGIC 0x89537892
#define HUNK_FREE_MAGIC 0x89537893
typedef struct {
int magic;
int size;
} hunkHeader_t;
typedef struct {
int mark;
int permanent;
int temp;
int tempHighwater;
} hunkUsed_t;
typedef struct hunkblock_s {
int size;
byte printed;
struct hunkblock_s *next;
char *label;
char *file;
int line;
} hunkblock_t;
static hunkblock_t *hunkblocks;
static hunkUsed_t hunk_low, hunk_high;
static hunkUsed_t *hunk_permanent, *hunk_temp;
static byte *s_hunkData = NULL;
static int s_hunkTotal;
static int s_zoneTotal;
static int s_smallZoneTotal;
/*
=================
Com_Meminfo_f
=================
*/
void Com_Meminfo_f( void ) {
memblock_t *block;
int zoneBytes, zoneBlocks;
int smallZoneBytes, smallZoneBlocks;
int botlibBytes, rendererBytes;
int unused;
zoneBytes = 0;
botlibBytes = 0;
rendererBytes = 0;
zoneBlocks = 0;
for ( block = mainzone->blocklist.next ; ; block = block->next ) {
if ( Cmd_Argc() != 1 ) {
Com_Printf( "block:%p size:%7i tag:%3i\n",
(void *)block, block->size, block->tag);
}
if ( block->tag ) {
zoneBytes += block->size;
zoneBlocks++;
if ( block->tag == TAG_BOTLIB ) {
botlibBytes += block->size;
} else if ( block->tag == TAG_RENDERER ) {
rendererBytes += block->size;
}
}
if ( block->next == &mainzone->blocklist ) {
break; // all blocks have been hit
}
if ( (byte *)block + block->size != (byte *)block->next ) {
Com_Printf( "ERROR: block size does not touch the next block\n" );
}
if ( block->next->prev != block ) {
Com_Printf( "ERROR: next block doesn't have proper back link\n" );
}
if ( !block->tag && !block->next->tag ) {
Com_Printf( "ERROR: two consecutive free blocks\n" );
}
}
smallZoneBytes = 0;
smallZoneBlocks = 0;
for ( block = smallzone->blocklist.next ; ; block = block->next ) {
if ( block->tag ) {
smallZoneBytes += block->size;
smallZoneBlocks++;
}
if ( block->next == &smallzone->blocklist ) {
break; // all blocks have been hit
}
}
Com_Printf( "%8i bytes total hunk\n", s_hunkTotal );
Com_Printf( "%8i bytes total zone\n", s_zoneTotal );
Com_Printf( "\n" );
Com_Printf( "%8i low mark\n", hunk_low.mark );
Com_Printf( "%8i low permanent\n", hunk_low.permanent );
if ( hunk_low.temp != hunk_low.permanent ) {
Com_Printf( "%8i low temp\n", hunk_low.temp );
}
Com_Printf( "%8i low tempHighwater\n", hunk_low.tempHighwater );
Com_Printf( "\n" );
Com_Printf( "%8i high mark\n", hunk_high.mark );
Com_Printf( "%8i high permanent\n", hunk_high.permanent );
if ( hunk_high.temp != hunk_high.permanent ) {
Com_Printf( "%8i high temp\n", hunk_high.temp );
}
Com_Printf( "%8i high tempHighwater\n", hunk_high.tempHighwater );
Com_Printf( "\n" );
Com_Printf( "%8i total hunk in use\n", hunk_low.permanent + hunk_high.permanent );
unused = 0;
if ( hunk_low.tempHighwater > hunk_low.permanent ) {
unused += hunk_low.tempHighwater - hunk_low.permanent;
}
if ( hunk_high.tempHighwater > hunk_high.permanent ) {
unused += hunk_high.tempHighwater - hunk_high.permanent;
}
Com_Printf( "%8i unused highwater\n", unused );
Com_Printf( "\n" );
Com_Printf( "%8i bytes in %i zone blocks\n", zoneBytes, zoneBlocks );
Com_Printf( " %8i bytes in dynamic botlib\n", botlibBytes );
Com_Printf( " %8i bytes in dynamic renderer\n", rendererBytes );
Com_Printf( " %8i bytes in dynamic other\n", zoneBytes - ( botlibBytes + rendererBytes ) );
Com_Printf( " %8i bytes in small Zone memory\n", smallZoneBytes );
}
/*
===============
Com_TouchMemory
Touch all known used data to make sure it is paged in
===============
*/
void Com_TouchMemory( void ) {
int start, end;
int i, j;
int sum;
memblock_t *block;
Z_CheckHeap();
start = Sys_Milliseconds();
sum = 0;
j = hunk_low.permanent >> 2;
for ( i = 0 ; i < j ; i += 64 ) { // only need to touch each page
sum += ( (int *)s_hunkData )[i];
}
i = ( s_hunkTotal - hunk_high.permanent ) >> 2;
j = hunk_high.permanent >> 2;
for ( ; i < j ; i += 64 ) { // only need to touch each page
sum += ( (int *)s_hunkData )[i];
}
for ( block = mainzone->blocklist.next ; ; block = block->next ) {
if ( block->tag ) {
j = block->size >> 2;
for ( i = 0 ; i < j ; i += 64 ) { // only need to touch each page
sum += ( (int *)block )[i];
}
}
if ( block->next == &mainzone->blocklist ) {
break; // all blocks have been hit
}
}
end = Sys_Milliseconds();
Com_Printf( "Com_TouchMemory: %i msec\n", end - start );
}
/*
=================
Com_InitZoneMemory
=================
*/
void Com_InitSmallZoneMemory( void ) {
s_smallZoneTotal = 512 * 1024;
smallzone = calloc( s_smallZoneTotal, 1 );
if ( !smallzone ) {
Com_Error( ERR_FATAL, "Small zone data failed to allocate %1.1f megs", (float)s_smallZoneTotal / ( 1024 * 1024 ) );
}
Z_ClearZone( smallzone, s_smallZoneTotal );
}
/*
void Com_InitZoneMemory( void ) {
cvar_t *cv;
s_smallZoneTotal = 512 * 1024;
smallzone = malloc( s_smallZoneTotal );
if ( !smallzone ) {
Com_Error( ERR_FATAL, "Small zone data failed to allocate %1.1f megs", (float)s_smallZoneTotal / (1024*1024) );
}
Z_ClearZone( smallzone, s_smallZoneTotal );
// allocate the random block zone
cv = Cvar_Get( "com_zoneMegs", DEF_COMZONEMEGS, CVAR_LATCH | CVAR_ARCHIVE );
if ( cv->integer < 16 ) {
s_zoneTotal = 1024 * 1024 * 16;
} else {
s_zoneTotal = cv->integer * 1024 * 1024;
}
mainzone = malloc( s_zoneTotal );
if ( !mainzone ) {
Com_Error( ERR_FATAL, "Zone data failed to allocate %i megs", s_zoneTotal / (1024*1024) );
}
Z_ClearZone( mainzone, s_zoneTotal );
}
*/
void Com_InitZoneMemory( void ) {
cvar_t *cv;
// Please note: com_zoneMegs can only be set on the command line, and
// not in wolfconfig_mp.cfg or Com_StartupVariable, as they haven't been
// executed by this point. It's a chicken and egg problem. We need the
// memory manager configured to handle those places where you would
// configure the memory manager.
// allocate the random block zone
cv = Cvar_Get( "com_zoneMegs", DEF_COMZONEMEGS_S, CVAR_LATCH | CVAR_ARCHIVE );
if ( cv->integer < DEF_COMZONEMEGS ) {
s_zoneTotal = 1024 * 1024 * DEF_COMZONEMEGS;
} else {
s_zoneTotal = cv->integer * 1024 * 1024;
}
mainzone = calloc( s_zoneTotal, 1 );
if ( !mainzone ) {
Com_Error( ERR_FATAL, "Zone data failed to allocate %i megs", s_zoneTotal / ( 1024 * 1024 ) );
}
Z_ClearZone( mainzone, s_zoneTotal );
}
/*
=================
Hunk_Log
=================
*/
void Hunk_Log( void ) {
hunkblock_t *block;
char buf[4096];
int size, numBlocks;
if ( !logfile || !FS_Initialized() ) {
return;
}
size = 0;
numBlocks = 0;
Com_sprintf( buf, sizeof( buf ), "\r\n================\r\nHunk log\r\n================\r\n" );
FS_Write( buf, strlen( buf ), logfile );
for ( block = hunkblocks ; block; block = block->next ) {
#ifdef HUNK_DEBUG
Com_sprintf( buf, sizeof( buf ), "size = %8d: %s, line: %d (%s)\r\n", block->size, block->file, block->line, block->label );
FS_Write( buf, strlen( buf ), logfile );
#endif
size += block->size;
numBlocks++;
}
Com_sprintf( buf, sizeof( buf ), "%d Hunk memory\r\n", size );
FS_Write( buf, strlen( buf ), logfile );
Com_sprintf( buf, sizeof( buf ), "%d hunk blocks\r\n", numBlocks );
FS_Write( buf, strlen( buf ), logfile );
}
/*
=================
Hunk_SmallLog
=================
*/
void Hunk_SmallLog( void ) {
hunkblock_t *block, *block2;
char buf[4096];
int size, locsize, numBlocks;
if ( !logfile || !FS_Initialized() ) {
return;
}
for ( block = hunkblocks ; block; block = block->next ) {
block->printed = qfalse;
}
size = 0;
numBlocks = 0;
Com_sprintf( buf, sizeof( buf ), "\r\n================\r\nHunk Small log\r\n================\r\n" );
FS_Write( buf, strlen( buf ), logfile );
for ( block = hunkblocks; block; block = block->next ) {
if ( block->printed ) {
continue;
}
locsize = block->size;
for ( block2 = block->next; block2; block2 = block2->next ) {
if ( block->line != block2->line ) {
continue;
}
if ( Q_stricmp( block->file, block2->file ) ) {
continue;
}
size += block2->size;
locsize += block2->size;
block2->printed = qtrue;
}
#ifdef HUNK_DEBUG
Com_sprintf( buf, sizeof( buf ), "size = %8d: %s, line: %d (%s)\r\n", locsize, block->file, block->line, block->label );
FS_Write( buf, strlen( buf ), logfile );
#endif
size += block->size;
numBlocks++;
}
Com_sprintf( buf, sizeof( buf ), "%d Hunk memory\r\n", size );
FS_Write( buf, strlen( buf ), logfile );
Com_sprintf( buf, sizeof( buf ), "%d hunk blocks\r\n", numBlocks );
FS_Write( buf, strlen( buf ), logfile );
}
/*
=================
Com_InitHunkMemory
=================
*/
void Com_InitHunkMemory( void ) {
cvar_t *cv;
int nMinAlloc;
char *pMsg = NULL;
// make sure the file system has allocated and "not" freed any temp blocks
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( FS_LoadStack() != 0 ) {
Com_Error( ERR_FATAL, "Hunk initialization failed. File system load stack not zero" );
}
// allocate the stack based hunk allocator
cv = Cvar_Get( "com_hunkMegs", DEF_COMHUNKMEGS_S, CVAR_LATCH | CVAR_ARCHIVE );
// if we are not dedicated min allocation is 56, otherwise min is 1
if ( com_dedicated && com_dedicated->integer ) {
nMinAlloc = MIN_DEDICATED_COMHUNKMEGS;
pMsg = "Minimum com_hunkMegs for a dedicated server is %i, allocating %i megs.\n";
} else {
nMinAlloc = MIN_COMHUNKMEGS;
pMsg = "Minimum com_hunkMegs is %i, allocating %i megs.\n";
}
if ( cv->integer < nMinAlloc ) {
s_hunkTotal = 1024 * 1024 * nMinAlloc;
Com_Printf( pMsg, nMinAlloc, s_hunkTotal / ( 1024 * 1024 ) );
} else {
s_hunkTotal = cv->integer * 1024 * 1024;
}
s_hunkData = malloc( s_hunkTotal + 31 );
if ( !s_hunkData ) {
Com_Error( ERR_FATAL, "Hunk data failed to allocate %i megs", s_hunkTotal / ( 1024 * 1024 ) );
}
// cacheline align
s_hunkData = (byte *) ( ( (intptr_t)s_hunkData + 31 ) & ~31 );
Hunk_Clear();
Cmd_AddCommand( "meminfo", Com_Meminfo_f );
#ifdef ZONE_DEBUG
Cmd_AddCommand( "zonelog", Z_LogHeap );
#endif
#ifdef HUNK_DEBUG
Cmd_AddCommand( "hunklog", Hunk_Log );
Cmd_AddCommand( "hunksmalllog", Hunk_SmallLog );
#endif
}
/*
====================
Hunk_MemoryRemaining
====================
*/
int Hunk_MemoryRemaining( void ) {
int low, high;
low = hunk_low.permanent > hunk_low.temp ? hunk_low.permanent : hunk_low.temp;
high = hunk_high.permanent > hunk_high.temp ? hunk_high.permanent : hunk_high.temp;
return s_hunkTotal - ( low + high );
}
/*
===================
Hunk_SetMark
The server calls this after the level and game VM have been loaded
===================
*/
void Hunk_SetMark( void ) {
hunk_low.mark = hunk_low.permanent;
hunk_high.mark = hunk_high.permanent;
}
/*
=================
Hunk_ClearToMark
The client calls this before starting a vid_restart or snd_restart
=================
*/
void Hunk_ClearToMark( void ) {
hunk_low.permanent = hunk_low.temp = hunk_low.mark;
hunk_high.permanent = hunk_high.temp = hunk_high.mark;
}
/*
=================
Hunk_CheckMark
=================
*/
qboolean Hunk_CheckMark( void ) {
if ( hunk_low.mark || hunk_high.mark ) {
return qtrue;
}
return qfalse;
}
void CL_ShutdownCGame( void );
void CL_ShutdownUI( void );
void SV_ShutdownGameProgs( void );
/*
=================
Hunk_Clear
The server calls this before shutting down or loading a new map
=================
*/
void Hunk_Clear( void ) {
#ifndef DEDICATED
CL_ShutdownCGame();
CL_ShutdownUI();
#endif
SV_ShutdownGameProgs();
#ifndef DEDICATED
CIN_CloseAllVideos();
#endif
hunk_low.mark = 0;
hunk_low.permanent = 0;
hunk_low.temp = 0;
hunk_low.tempHighwater = 0;
hunk_high.mark = 0;
hunk_high.permanent = 0;
hunk_high.temp = 0;
hunk_high.tempHighwater = 0;
hunk_permanent = &hunk_low;
hunk_temp = &hunk_high;
Cvar_Set( "com_hunkused", va( "%i", hunk_low.permanent + hunk_high.permanent ) );
Com_Printf( "Hunk_Clear: reset the hunk ok\n" );
VM_Clear(); // (SA) FIXME:TODO: was commented out in wolf
#ifdef HUNK_DEBUG
hunkblocks = NULL;
#endif
}
static void Hunk_SwapBanks( void ) {
hunkUsed_t *swap;
// can't swap banks if there is any temp already allocated
if ( hunk_temp->temp != hunk_temp->permanent ) {
return;
}
// if we have a larger highwater mark on this side, start making
// our permanent allocations here and use the other side for temp
if ( hunk_temp->tempHighwater - hunk_temp->permanent >
hunk_permanent->tempHighwater - hunk_permanent->permanent ) {
swap = hunk_temp;
hunk_temp = hunk_permanent;
hunk_permanent = swap;
}
}
/*
=================
Hunk_Alloc
Allocate permanent (until the hunk is cleared) memory
=================
*/
#ifdef HUNK_DEBUG
void *Hunk_AllocDebug( int size, ha_pref preference, char *label, char *file, int line ) {
#else
void *Hunk_Alloc( int size, ha_pref preference ) {
#endif
void *buf;
if ( s_hunkData == NULL ) {
Com_Error( ERR_FATAL, "Hunk_Alloc: Hunk memory system not initialized" );
}
Hunk_SwapBanks();
#ifdef HUNK_DEBUG
size += sizeof( hunkblock_t );
#endif
// round to cacheline
size = ( size + 31 ) & ~31;
if ( hunk_low.temp + hunk_high.temp + size > s_hunkTotal ) {
#ifdef HUNK_DEBUG
Hunk_Log();
Hunk_SmallLog();
Com_Error(ERR_DROP, "Hunk_Alloc failed on %i: %s, line: %d (%s)", size, file, line, label);
#else
Com_Error(ERR_DROP, "Hunk_Alloc failed on %i", size);
#endif
}
if ( hunk_permanent == &hunk_low ) {
buf = ( void * )( s_hunkData + hunk_permanent->permanent );
hunk_permanent->permanent += size;
} else {
hunk_permanent->permanent += size;
buf = ( void * )( s_hunkData + s_hunkTotal - hunk_permanent->permanent );
}
hunk_permanent->temp = hunk_permanent->permanent;
memset( buf, 0, size );
#ifdef HUNK_DEBUG
{
hunkblock_t *block;
block = (hunkblock_t *) buf;
block->size = size - sizeof( hunkblock_t );
block->file = file;
block->label = label;
block->line = line;
block->next = hunkblocks;
hunkblocks = block;
buf = ( (byte *) buf ) + sizeof( hunkblock_t );
}
#endif
// Ridah, update the com_hunkused cvar in increments, so we don't update it too often, since this cvar call isn't very efficent
if ( ( hunk_low.permanent + hunk_high.permanent ) > com_hunkused->integer + 10000 ) {
Cvar_Set( "com_hunkused", va( "%i", hunk_low.permanent + hunk_high.permanent ) );
}
return buf;
}
/*
=================
Hunk_AllocateTempMemory
This is used by the file loading system.
Multiple files can be loaded in temporary memory.
When the files-in-use count reaches zero, all temp memory will be deleted
=================
*/
void *Hunk_AllocateTempMemory( int size ) {
void *buf;
hunkHeader_t *hdr;
// return a Z_Malloc'd block if the hunk has not been initialized
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( s_hunkData == NULL ) {
return Z_Malloc( size );
}
Hunk_SwapBanks();
size = PAD(size, sizeof(intptr_t)) + sizeof( hunkHeader_t );
if ( hunk_temp->temp + hunk_permanent->permanent + size > s_hunkTotal ) {
Com_Error( ERR_DROP, "Hunk_AllocateTempMemory: failed on %i", size );
}
if ( hunk_temp == &hunk_low ) {
buf = ( void * )( s_hunkData + hunk_temp->temp );
hunk_temp->temp += size;
} else {
hunk_temp->temp += size;
buf = ( void * )( s_hunkData + s_hunkTotal - hunk_temp->temp );
}
if ( hunk_temp->temp > hunk_temp->tempHighwater ) {
hunk_temp->tempHighwater = hunk_temp->temp;
}
hdr = (hunkHeader_t *)buf;
buf = ( void * )( hdr + 1 );
hdr->magic = HUNK_MAGIC;
hdr->size = size;
// don't bother clearing, because we are going to load a file over it
return buf;
}
/*
==================
Hunk_FreeTempMemory
==================
*/
void Hunk_FreeTempMemory( void *buf ) {
hunkHeader_t *hdr;
// free with Z_Free if the hunk has not been initialized
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( s_hunkData == NULL ) {
Z_Free( buf );
return;
}
hdr = ( (hunkHeader_t *)buf ) - 1;
if ( hdr->magic != HUNK_MAGIC ) {
Com_Error( ERR_FATAL, "Hunk_FreeTempMemory: bad magic" );
}
hdr->magic = HUNK_FREE_MAGIC;
// this only works if the files are freed in stack order,
// otherwise the memory will stay around until Hunk_ClearTempMemory
if ( hunk_temp == &hunk_low ) {
if ( hdr == ( void * )( s_hunkData + hunk_temp->temp - hdr->size ) ) {
hunk_temp->temp -= hdr->size;
} else {
Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
}
} else {
if ( hdr == ( void * )( s_hunkData + s_hunkTotal - hunk_temp->temp ) ) {
hunk_temp->temp -= hdr->size;
} else {
Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
}
}
}
/*
=================
Hunk_ClearTempMemory
The temp space is no longer needed. If we have left more
touched but unused memory on this side, have future
permanent allocs use this side.
=================
*/
void Hunk_ClearTempMemory( void ) {
if ( s_hunkData != NULL ) {
hunk_temp->temp = hunk_temp->permanent;
}
}
/*
===================================================================
EVENTS AND JOURNALING
In addition to these events, .cfg files are also copied to the
journaled file
===================================================================
*/
#define MAX_PUSHED_EVENTS 1024
static int com_pushedEventsHead = 0;
static int com_pushedEventsTail = 0;
static sysEvent_t com_pushedEvents[MAX_PUSHED_EVENTS];
/*
=================
Com_InitJournaling
=================
*/
void Com_InitJournaling( void ) {
Com_StartupVariable( "journal" );
com_journal = Cvar_Get( "journal", "0", CVAR_INIT );
if ( !com_journal->integer ) {
return;
}
if ( com_journal->integer == 1 ) {
Com_Printf( "Journaling events\n" );
com_journalFile = FS_FOpenFileWrite( "journal.dat" );
com_journalDataFile = FS_FOpenFileWrite( "journaldata.dat" );
} else if ( com_journal->integer == 2 ) {
Com_Printf( "Replaying journaled events\n" );
FS_FOpenFileRead( "journal.dat", &com_journalFile, qtrue );
FS_FOpenFileRead( "journaldata.dat", &com_journalDataFile, qtrue );
}
if ( !com_journalFile || !com_journalDataFile ) {
Cvar_Set( "com_journal", "0" );
com_journalFile = 0;
com_journalDataFile = 0;
Com_Printf( "Couldn't open journal files\n" );
}
}
/*
========================================================================
EVENT LOOP
========================================================================
*/
#define MAX_QUEUED_EVENTS 256
#define MASK_QUEUED_EVENTS ( MAX_QUEUED_EVENTS - 1 )
static sysEvent_t eventQueue[ MAX_QUEUED_EVENTS ];
static int eventHead = 0;
static int eventTail = 0;
/*
================
Com_QueueEvent
A time of 0 will get the current time
Ptr should either be null, or point to a block of data that can
be freed by the game later.
================
*/
void Com_QueueEvent( int time, sysEventType_t type, int value, int value2, int ptrLength, void *ptr )
{
sysEvent_t *ev;
ev = &eventQueue[ eventHead & MASK_QUEUED_EVENTS ];
if ( eventHead - eventTail >= MAX_QUEUED_EVENTS )
{
Com_Printf("Com_QueueEvent: overflow\n");
// we are discarding an event, but don't leak memory
if ( ev->evPtr )
{
Z_Free( ev->evPtr );
}
eventTail++;
}
eventHead++;
if ( time == 0 )
{
time = Sys_Milliseconds();
}
ev->evTime = time;
ev->evType = type;
ev->evValue = value;
ev->evValue2 = value2;
ev->evPtrLength = ptrLength;
ev->evPtr = ptr;
}
/*
================
Com_GetSystemEvent
================
*/
sysEvent_t Com_GetSystemEvent( void )
{
sysEvent_t ev;
char *s;
// return if we have data
if ( eventHead > eventTail )
{
eventTail++;
return eventQueue[ ( eventTail - 1 ) & MASK_QUEUED_EVENTS ];
}
// check for console commands
s = Sys_ConsoleInput();
if ( s )
{
char *b;
int len;
len = strlen( s ) + 1;
b = Z_Malloc( len );
strcpy( b, s );
Com_QueueEvent( 0, SE_CONSOLE, 0, 0, len, b );
}
// return if we have data
if ( eventHead > eventTail )
{
eventTail++;
return eventQueue[ ( eventTail - 1 ) & MASK_QUEUED_EVENTS ];
}
// create an empty event to return
memset( &ev, 0, sizeof( ev ) );
ev.evTime = Sys_Milliseconds();
return ev;
}
/*
=================
Com_GetRealEvent
=================
*/
sysEvent_t Com_GetRealEvent( void ) {
int r;
sysEvent_t ev;
// either get an event from the system or the journal file
if ( com_journal->integer == 2 ) {
r = FS_Read( &ev, sizeof( ev ), com_journalFile );
if ( r != sizeof( ev ) ) {
Com_Error( ERR_FATAL, "Error reading from journal file" );
}
if ( ev.evPtrLength ) {
ev.evPtr = Z_Malloc( ev.evPtrLength );
r = FS_Read( ev.evPtr, ev.evPtrLength, com_journalFile );
if ( r != ev.evPtrLength ) {
Com_Error( ERR_FATAL, "Error reading from journal file" );
}
}
} else {
ev = Com_GetSystemEvent();
// write the journal value out if needed
if ( com_journal->integer == 1 ) {
r = FS_Write( &ev, sizeof( ev ), com_journalFile );
if ( r != sizeof( ev ) ) {
Com_Error( ERR_FATAL, "Error writing to journal file" );
}
if ( ev.evPtrLength ) {
r = FS_Write( ev.evPtr, ev.evPtrLength, com_journalFile );
if ( r != ev.evPtrLength ) {
Com_Error( ERR_FATAL, "Error writing to journal file" );
}
}
}
}
return ev;
}
/*
=================
Com_InitPushEvent
=================
*/
void Com_InitPushEvent( void ) {
// clear the static buffer array
// this requires SE_NONE to be accepted as a valid but NOP event
memset( com_pushedEvents, 0, sizeof( com_pushedEvents ) );
// reset counters while we are at it
// beware: GetEvent might still return an SE_NONE from the buffer
com_pushedEventsHead = 0;
com_pushedEventsTail = 0;
}
/*
=================
Com_PushEvent
=================
*/
void Com_PushEvent( sysEvent_t *event ) {
sysEvent_t *ev;
static int printedWarning = 0;
ev = &com_pushedEvents[ com_pushedEventsHead & ( MAX_PUSHED_EVENTS - 1 ) ];
if ( com_pushedEventsHead - com_pushedEventsTail >= MAX_PUSHED_EVENTS ) {
// don't print the warning constantly, or it can give time for more...
if ( !printedWarning ) {
printedWarning = qtrue;
Com_Printf( "WARNING: Com_PushEvent overflow\n" );
}
if ( ev->evPtr ) {
Z_Free( ev->evPtr );
}
com_pushedEventsTail++;
} else {
printedWarning = qfalse;
}
*ev = *event;
com_pushedEventsHead++;
}
/*
=================
Com_GetEvent
=================
*/
sysEvent_t Com_GetEvent( void ) {
if ( com_pushedEventsHead > com_pushedEventsTail ) {
com_pushedEventsTail++;
return com_pushedEvents[ ( com_pushedEventsTail - 1 ) & ( MAX_PUSHED_EVENTS - 1 ) ];
}
return Com_GetRealEvent();
}
/*
=================
Com_RunAndTimeServerPacket
=================
*/
void Com_RunAndTimeServerPacket( netadr_t *evFrom, msg_t *buf ) {
int t1, t2, msec;
t1 = 0;
if ( com_speeds->integer ) {
t1 = Sys_Milliseconds();
}
SV_PacketEvent( *evFrom, buf );
if ( com_speeds->integer ) {
t2 = Sys_Milliseconds();
msec = t2 - t1;
if ( com_speeds->integer == 3 ) {
Com_Printf( "SV_PacketEvent time: %i\n", msec );
}
}
}
/*
=================
Com_EventLoop
Returns last event time
=================
*/
int Com_EventLoop( void ) {
sysEvent_t ev;
netadr_t evFrom;
byte bufData[MAX_MSGLEN];
msg_t buf;
MSG_Init( &buf, bufData, sizeof( bufData ) );
while ( 1 ) {
ev = Com_GetEvent();
// if no more events are available
if ( ev.evType == SE_NONE ) {
// manually send packet events for the loopback channel
while ( NET_GetLoopPacket( NS_CLIENT, &evFrom, &buf ) ) {
CL_PacketEvent( evFrom, &buf );
}
while ( NET_GetLoopPacket( NS_SERVER, &evFrom, &buf ) ) {
// if the server just shut down, flush the events
if ( com_sv_running->integer ) {
Com_RunAndTimeServerPacket( &evFrom, &buf );
}
}
return ev.evTime;
}
switch(ev.evType)
{
case SE_KEY:
CL_KeyEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_CHAR:
CL_CharEvent( ev.evValue );
break;
case SE_MOUSE:
CL_MouseEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_JOYSTICK_AXIS:
CL_JoystickEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_CONSOLE:
Cbuf_AddText( (char *)ev.evPtr );
Cbuf_AddText( "\n" );
break;
default:
Com_Error( ERR_FATAL, "Com_EventLoop: bad event type %i", ev.evType );
break;
}
// free any block data
if ( ev.evPtr ) {
Z_Free( ev.evPtr );
}
}
return 0; // never reached
}
/*
================
Com_Milliseconds
Can be used for profiling, but will be journaled accurately
================
*/
int Com_Milliseconds( void ) {
sysEvent_t ev;
// get events and push them until we get a null event with the current time
do {
ev = Com_GetRealEvent();
if ( ev.evType != SE_NONE ) {
Com_PushEvent( &ev );
}
} while ( ev.evType != SE_NONE );
return ev.evTime;
}
//============================================================================
/*
=============
Com_Error_f
Just throw a fatal error to
test error shutdown procedures
=============
*/
static void __attribute__((__noreturn__)) Com_Error_f (void) {
if ( Cmd_Argc() > 1 ) {
Com_Error( ERR_DROP, "Testing drop error" );
} else {
Com_Error( ERR_FATAL, "Testing fatal error" );
}
}
/*
=============
Com_Freeze_f
Just freeze in place for a given number of seconds to test
error recovery
=============
*/
static void Com_Freeze_f( void ) {
float s;
int start, now;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "freeze <seconds>\n" );
return;
}
s = atof( Cmd_Argv( 1 ) );
start = Com_Milliseconds();
while ( 1 ) {
now = Com_Milliseconds();
if ( ( now - start ) * 0.001 > s ) {
break;
}
}
}
/*
=================
Com_Crash_f
A way to force a bus error for development reasons
=================
*/
static void Com_Crash_f( void ) {
* ( volatile int * ) 0 = 0x12345678;
}
/*
==================
Com_Setenv_f
For controlling environment variables
==================
*/
void Com_Setenv_f(void)
{
int argc = Cmd_Argc();
char *arg1 = Cmd_Argv(1);
if(argc > 2)
{
char *arg2 = Cmd_ArgsFrom(2);
Sys_SetEnv(arg1, arg2);
}
else if(argc == 2)
{
char *env = getenv(arg1);
if(env)
Com_Printf("%s=%s\n", arg1, env);
else
Com_Printf("%s undefined\n", arg1);
}
}
/*
==================
Com_ExecuteCfg
For controlling environment variables
==================
*/
void Com_ExecuteCfg(void)
{
// DHM - Nerve
#ifndef UPDATE_SERVER
Cbuf_ExecuteText(EXEC_NOW, "exec default.cfg\n");
if ( FS_ReadFile( "language.cfg", NULL ) > 0 ) {
Cbuf_ExecuteText(EXEC_APPEND, "exec language.cfg\n");
} else if ( FS_ReadFile( "Language.cfg", NULL ) > 0 ) {
Cbuf_ExecuteText(EXEC_APPEND, "exec Language.cfg\n");
}
Cbuf_Execute(); // Always execute after exec to prevent text buffer overflowing
if(!Com_SafeMode())
{
// skip the wolfconfig_mp.cfg and autoexec.cfg if "safe" is on the command line
Cbuf_ExecuteText(EXEC_NOW, "exec " Q3CONFIG_CFG "\n");
Cbuf_Execute();
Cbuf_ExecuteText(EXEC_NOW, "exec autoexec.cfg\n");
Cbuf_Execute();
}
#endif
}
/*
==================
Com_GameRestart
Change to a new mod properly with cleaning up cvars before switching.
==================
*/
void Com_GameRestart(int checksumFeed, qboolean disconnect)
{
// make sure no recursion can be triggered
if(!com_gameRestarting && com_fullyInitialized)
{
com_gameRestarting = qtrue;
com_gameClientRestarting = com_cl_running->integer;
// Kill server if we have one
if(com_sv_running->integer)
SV_Shutdown("Game directory changed");
if(com_gameClientRestarting)
{
if(disconnect)
CL_Disconnect(qfalse);
CL_Shutdown("Game directory changed", disconnect, qfalse);
}
FS_Restart(checksumFeed);
// Clean out any user and VM created cvars
Cvar_Restart(qtrue);
Com_ExecuteCfg();
if(disconnect)
{
// We don't want to change any network settings if gamedir
// change was triggered by a connect to server because the
// new network settings might make the connection fail.
NET_Restart_f();
}
if(com_gameClientRestarting)
{
CL_Init();
CL_StartHunkUsers(qfalse);
}
com_gameRestarting = qfalse;
com_gameClientRestarting = qfalse;
}
}
/*
==================
Com_GameRestart_f
Expose possibility to change current running mod to the user
==================
*/
void Com_GameRestart_f(void)
{
if(!FS_FilenameCompare(Cmd_Argv(1), com_basegame->string))
{
// This is the standard base game. Servers and clients should
// use "" and not the standard basegame name because this messes
// up pak file negotiation and lots of other stuff
Cvar_Set("fs_game", "");
}
else
Cvar_Set("fs_game", Cmd_Argv(1));
Com_GameRestart(0, qtrue);
}
#ifndef STANDALONE
// TTimo: centralizing the cl_cdkey stuff after I discovered a buffer overflow problem with the dedicated server version
// not sure it's necessary to have different defaults for regular and dedicated, but I don't want to take the risk
#ifndef DEDICATED
char cl_cdkey[34] = " ";
#else
char cl_cdkey[34] = "123456789";
#endif
/*
=================
Com_ReadCDKey
=================
*/
qboolean CL_CDKeyValidate( const char *key, const char *checksum );
void Com_ReadCDKey( const char *filename ) {
fileHandle_t f;
char buffer[33];
char fbuffer[MAX_OSPATH];
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename);
FS_SV_FOpenFileRead( fbuffer, &f );
if ( !f ) {
Q_strncpyz( cl_cdkey, " ", 17 );
return;
}
Com_Memset( buffer, 0, sizeof( buffer ) );
FS_Read( buffer, 16, f );
FS_FCloseFile( f );
if ( CL_CDKeyValidate( buffer, NULL ) ) {
Q_strncpyz( cl_cdkey, buffer, 17 );
} else {
Q_strncpyz( cl_cdkey, " ", 17 );
}
}
/*
=================
Com_AppendCDKey
=================
*/
void Com_AppendCDKey( const char *filename ) {
fileHandle_t f;
char buffer[33];
char fbuffer[MAX_OSPATH];
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename);
FS_SV_FOpenFileRead( fbuffer, &f );
if ( !f ) {
Q_strncpyz( &cl_cdkey[16], " ", 17 );
return;
}
Com_Memset( buffer, 0, sizeof( buffer ) );
FS_Read( buffer, 16, f );
FS_FCloseFile( f );
if ( CL_CDKeyValidate( buffer, NULL ) ) {
strcat( &cl_cdkey[16], buffer );
} else {
Q_strncpyz( &cl_cdkey[16], " ", 17 );
}
}
#ifndef DEDICATED
/*
=================
Com_WriteCDKey
=================
*/
static void Com_WriteCDKey( const char *filename, const char *ikey ) {
fileHandle_t f;
char fbuffer[MAX_OSPATH];
char key[17];
#ifndef _WIN32
mode_t savedumask;
#endif
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename);
Q_strncpyz( key, ikey, 17 );
if ( !CL_CDKeyValidate( key, NULL ) ) {
return;
}
#ifndef _WIN32
savedumask = umask(0077);
#endif
f = FS_SV_FOpenFileWrite( fbuffer );
if ( !f ) {
Com_Printf ("Couldn't write CD key to %s.\n", fbuffer );
goto out;
}
FS_Write( key, 16, f );
FS_Printf( f, "\n// generated by RTCW, do not modify\r\n" );
FS_Printf( f, "// Do not give this file to ANYONE.\r\n" );
#ifdef __APPLE__
FS_Printf( f, "// Aspyr will NOT ask you to send this file to them.\r\n" );
#else
FS_Printf( f, "// id Software and Activision will NOT ask you to send this file to them.\r\n" );
#endif
FS_FCloseFile( f );
out:
#ifndef _WIN32
umask(savedumask);
#else
;
#endif
}
#endif
#endif // STANDALONE
void Com_SetRecommended( void ) {
cvar_t *cv;
qboolean goodVideo;
qboolean goodCPU;
// will use this for recommended settings as well.. do i outside the lower check so it gets done even with command line stuff
cv = Cvar_Get( "r_highQualityVideo", "1", CVAR_ARCHIVE );
goodVideo = ( cv && cv->integer );
goodCPU = Sys_GetHighQualityCPU();
if ( goodVideo && goodCPU ) {
Com_Printf( "Found high quality video and CPU\n" );
Cbuf_AddText( "exec highVidhighCPU.cfg\n" );
} else if ( goodVideo && !goodCPU ) {
Cbuf_AddText( "exec highVidlowCPU.cfg\n" );
Com_Printf( "Found high quality video and low quality CPU\n" );
} else if ( !goodVideo && goodCPU ) {
Cbuf_AddText( "exec lowVidhighCPU.cfg\n" );
Com_Printf( "Found low quality video and high quality CPU\n" );
} else {
Cbuf_AddText( "exec lowVidlowCPU.cfg\n" );
Com_Printf( "Found low quality video and low quality CPU\n" );
}
// (SA) set the cvar so the menu will reflect this on first run
// Cvar_Set("ui_glCustom", "999"); // 'recommended'
}
static void Com_DetectAltivec(void)
{
// Only detect if user hasn't forcibly disabled it.
if (com_altivec->integer) {
static qboolean altivec = qfalse;
static qboolean detected = qfalse;
if (!detected) {
altivec = ( Sys_GetProcessorFeatures( ) & CF_ALTIVEC );
detected = qtrue;
}
if (!altivec) {
Cvar_Set( "com_altivec", "0" ); // we don't have it! Disable support!
}
}
}
/*
=================
Com_DetectSSE
Find out whether we have SSE support for Q_ftol function
=================
*/
#if id386 || idx64
static void Com_DetectSSE(void)
{
#if !idx64
cpuFeatures_t feat;
feat = Sys_GetProcessorFeatures();
if(feat & CF_SSE)
{
if(feat & CF_SSE2)
Q_SnapVector = qsnapvectorsse;
else
Q_SnapVector = qsnapvectorx87;
Q_ftol = qftolsse;
#endif
Q_VMftol = qvmftolsse;
Com_Printf("SSE instruction set enabled\n");
#if !idx64
}
else
{
Q_ftol = qftolx87;
Q_VMftol = qvmftolx87;
Q_SnapVector = qsnapvectorx87;
Com_Printf("SSE instruction set not available\n");
}
#endif
}
#else
#define Com_DetectSSE()
#endif
/*
=================
Com_InitRand
Seed the random number generator, if possible with an OS supplied random seed.
=================
*/
static void Com_InitRand(void)
{
unsigned int seed;
if(Sys_RandomBytes((byte *) &seed, sizeof(seed)))
srand(seed);
else
srand(time(NULL));
}
/*
=================
Com_Init
=================
*/
void Com_Init( char *commandLine ) {
char *s;
char *t;
int qport;
// TTimo gcc warning: variable `safeMode' might be clobbered by `longjmp' or `vfork'
volatile qboolean safeMode = qtrue;
Com_Printf( "%s %s %s\n", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
if ( setjmp( abortframe ) ) {
Sys_Error( "Error during initialization" );
}
// Clear queues
Com_Memset( &eventQueue[ 0 ], 0, MAX_QUEUED_EVENTS * sizeof( sysEvent_t ) );
// initialize the weak pseudo-random number generator for use later.
Com_InitRand();
// do this before anything else decides to push events
Com_InitPushEvent();
Com_InitSmallZoneMemory();
Cvar_Init();
// prepare enough of the subsystems to handle
// cvar and command buffer management
Com_ParseCommandLine( commandLine );
// Swap_Init();
Cbuf_Init();
Com_DetectSSE();
// override anything from the config files with command line args
Com_StartupVariable( NULL );
Com_InitZoneMemory();
Cmd_Init ();
// get the developer cvar set as early as possible
com_developer = Cvar_Get("developer", "0", CVAR_TEMP);
// done early so bind command exists
CL_InitKeyCommands();
com_standalone = Cvar_Get("com_standalone", "0", CVAR_ROM);
com_basegame = Cvar_Get("com_basegame", BASEGAME, CVAR_INIT);
com_homepath = Cvar_Get("com_homepath", "", CVAR_INIT);
if(!com_basegame->string[0])
Cvar_ForceReset("com_basegame");
FS_InitFilesystem();
Com_InitJournaling();
// Add some commands here already so users can use them from config files
Cmd_AddCommand ("setenv", Com_Setenv_f);
if (com_developer && com_developer->integer)
{
Cmd_AddCommand ("error", Com_Error_f);
Cmd_AddCommand ("crash", Com_Crash_f);
Cmd_AddCommand ("freeze", Com_Freeze_f);
}
Cmd_AddCommand ("quit", Com_Quit_f);
Cmd_AddCommand ("changeVectors", MSG_ReportChangeVectors_f );
Cmd_AddCommand ("writeconfig", Com_WriteConfig_f );
Cmd_SetCommandCompletionFunc( "writeconfig", Cmd_CompleteCfgName );
Cmd_AddCommand("game_restart", Com_GameRestart_f);
Com_ExecuteCfg();
// override anything from the config files with command line args
Com_StartupVariable( NULL );
// get dedicated here for proper hunk megs initialization
#ifdef UPDATE_SERVER
com_dedicated = Cvar_Get( "dedicated", "1", CVAR_LATCH );
Cvar_CheckRange( com_dedicated, 1, 2, qtrue );
#elif DEDICATED
// TTimo: default to internet dedicated, not LAN dedicated
com_dedicated = Cvar_Get( "dedicated", "2", CVAR_INIT );
Cvar_CheckRange( com_dedicated, 2, 2, qtrue );
#else
com_dedicated = Cvar_Get( "dedicated", "0", CVAR_LATCH );
Cvar_CheckRange( com_dedicated, 0, 2, qtrue );
#endif
// allocate the stack based hunk allocator
Com_InitHunkMemory();
// if any archived cvars are modified after this, we will trigger a writing
// of the config file
cvar_modifiedFlags &= ~CVAR_ARCHIVE;
//
// init commands and vars
//
com_altivec = Cvar_Get ("com_altivec", "1", CVAR_ARCHIVE);
com_maxfps = Cvar_Get( "com_maxfps", "76", CVAR_ARCHIVE | CVAR_LATCH );
com_blood = Cvar_Get( "com_blood", "1", CVAR_ARCHIVE );
com_logfile = Cvar_Get( "logfile", "0", CVAR_TEMP );
com_timescale = Cvar_Get( "timescale", "1", CVAR_CHEAT | CVAR_SYSTEMINFO );
com_fixedtime = Cvar_Get( "fixedtime", "0", CVAR_CHEAT );
com_showtrace = Cvar_Get( "com_showtrace", "0", CVAR_CHEAT );
com_speeds = Cvar_Get( "com_speeds", "0", 0 );
com_timedemo = Cvar_Get( "timedemo", "0", CVAR_CHEAT );
com_cameraMode = Cvar_Get( "com_cameraMode", "0", CVAR_CHEAT );
cl_paused = Cvar_Get( "cl_paused", "0", CVAR_ROM );
sv_paused = Cvar_Get( "sv_paused", "0", CVAR_ROM );
cl_packetdelay = Cvar_Get ("cl_packetdelay", "0", CVAR_CHEAT);
sv_packetdelay = Cvar_Get ("sv_packetdelay", "0", CVAR_CHEAT);
com_sv_running = Cvar_Get( "sv_running", "0", CVAR_ROM );
com_cl_running = Cvar_Get( "cl_running", "0", CVAR_ROM );
com_buildScript = Cvar_Get( "com_buildScript", "0", 0 );
com_ansiColor = Cvar_Get( "com_ansiColor", "0", CVAR_ARCHIVE );
com_unfocused = Cvar_Get( "com_unfocused", "0", CVAR_ROM );
com_maxfpsUnfocused = Cvar_Get( "com_maxfpsUnfocused", "0", CVAR_ARCHIVE );
com_minimized = Cvar_Get( "com_minimized", "0", CVAR_ROM );
com_maxfpsMinimized = Cvar_Get( "com_maxfpsMinimized", "0", CVAR_ARCHIVE );
com_abnormalExit = Cvar_Get( "com_abnormalExit", "0", CVAR_ROM );
com_busyWait = Cvar_Get("com_busyWait", "0", CVAR_ARCHIVE);
Cvar_Get("com_errorMessage", "", CVAR_ROM | CVAR_NORESTART);
#ifdef CINEMATICS_INTRO
com_introPlayed = Cvar_Get( "com_introplayed", "0", CVAR_ARCHIVE );
#endif
com_recommendedSet = Cvar_Get( "com_recommendedSet", "0", CVAR_ARCHIVE );
s = va( "%s %s %s", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
t = va( "%s %s %s", OLDVERSION, PLATFORM_STRING, PRODUCT_DATE );
com_fsgame = Cvar_Get( "fs_game", "", CVAR_INIT | CVAR_SYSTEMINFO );
com_legacyversion = Cvar_Get( "com_legacyversion", "0", CVAR_ARCHIVE );
if ( strcmp(com_fsgame->string,"banimod") == 0 || strcmp(com_fsgame->string,"bani") == 0 || com_legacyversion->integer ) {
com_version = Cvar_Get( "version", t, CVAR_ROM | CVAR_SERVERINFO );
} else {
com_version = Cvar_Get( "version", s, CVAR_ROM | CVAR_SERVERINFO );
}
com_gamename = Cvar_Get("com_gamename", GAMENAME_FOR_MASTER, CVAR_SERVERINFO | CVAR_INIT);
com_protocol = Cvar_Get("com_protocol", va("%i", PROTOCOL_VERSION), CVAR_SERVERINFO | CVAR_INIT);
#ifdef LEGACY_PROTOCOL
com_legacyprotocol = Cvar_Get("com_legacyprotocol", va("%i", PROTOCOL_LEGACY_VERSION), CVAR_INIT);
// Keep for compatibility with old mods / mods that haven't updated yet.
if(com_legacyprotocol->integer > 0)
Cvar_Get("protocol", com_legacyprotocol->string, CVAR_ROM);
else
#endif
Cvar_Get("protocol", com_protocol->string, CVAR_ROM);
com_hunkused = Cvar_Get( "com_hunkused", "0", 0 );
Sys_Init();
Sys_InitPIDFile( FS_GetCurrentGameDir() );
// Pick a random port value
Com_RandomBytes( (byte*)&qport, sizeof(int) );
Netchan_Init( qport & 0xffff );
VM_Init();
SV_Init();
com_dedicated->modified = qfalse;
#ifndef DEDICATED
CL_Init();
#endif
// set com_frameTime so that if a map is started on the
// command line it will still be able to count on com_frameTime
// being random enough for a serverid
com_frameTime = Com_Milliseconds();
// add + commands from command line
if ( !Com_AddStartupCommands() ) {
// if the user didn't give any commands, run default action
}
// start in full screen ui mode
Cvar_Set( "r_uiFullScreen", "1" );
CL_StartHunkUsers( qfalse );
// NERVE - SMF - force recommendedSet and don't do vid_restart if in safe mode
if ( !com_recommendedSet->integer && !safeMode ) {
Com_SetRecommended();
Cbuf_ExecuteText( EXEC_APPEND, "vid_restart\n" );
}
Cvar_Set( "com_recommendedSet", "1" );
if ( !com_dedicated->integer ) {
#ifdef CINEMATICS_LOGO
Cbuf_AddText( "cinematic " CINEMATICS_LOGO "\n" );
#endif
#ifdef CINEMATICS_INTRO
if ( !com_introPlayed->integer ) {
Cvar_Set( com_introPlayed->name, "1" );
Cvar_Set( "nextmap", "cinematic " CINEMATICS_INTRO );
}
#endif
}
com_fullyInitialized = qtrue;
// always set the cvar, but only print the info if it makes sense.
Com_DetectAltivec();
#if idppc
Com_Printf ("Altivec support is %s\n", com_altivec->integer ? "enabled" : "disabled");
#endif
com_pipefile = Cvar_Get( "com_pipefile", "", CVAR_ARCHIVE|CVAR_LATCH );
if( com_pipefile->string[0] )
{
pipefile = FS_FCreateOpenPipeFile( com_pipefile->string );
}
Com_Printf ("--- Common Initialization Complete ---\n");
}
/*
===============
Com_ReadFromPipe
Read whatever is in com_pipefile, if anything, and execute it
===============
*/
void Com_ReadFromPipe( void )
{
static char buf[MAX_STRING_CHARS];
static int accu = 0;
int read;
if( !pipefile )
return;
while( ( read = FS_Read( buf + accu, sizeof( buf ) - accu - 1, pipefile ) ) > 0 )
{
char *brk = NULL;
int i;
for( i = accu; i < accu + read; ++i )
{
if( buf[ i ] == '\0' )
buf[ i ] = '\n';
if( buf[ i ] == '\n' || buf[ i ] == '\r' )
brk = &buf[ i + 1 ];
}
buf[ accu + read ] = '\0';
accu += read;
if( brk )
{
char tmp = *brk;
*brk = '\0';
Cbuf_ExecuteText( EXEC_APPEND, buf );
*brk = tmp;
accu -= brk - buf;
memmove( buf, brk, accu + 1 );
}
else if( accu >= sizeof( buf ) - 1 ) // full
{
Cbuf_ExecuteText( EXEC_APPEND, buf );
accu = 0;
}
}
}
//==================================================================
void Com_WriteConfigToFile( const char *filename ) {
fileHandle_t f;
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf( "Couldn't write %s.\n", filename );
return;
}
FS_Printf( f, "// generated by RTCW, do not modify\n" );
Key_WriteBindings( f );
Cvar_WriteVariables( f );
FS_FCloseFile( f );
}
/*
===============
Com_WriteConfiguration
Writes key bindings and archived cvars to config file if modified
===============
*/
void Com_WriteConfiguration( void ) {
#if !defined(DEDICATED) && !defined(STANDALONE)
cvar_t *fs;
#endif
// if we are quiting without fully initializing, make sure
// we don't write out anything
if ( !com_fullyInitialized ) {
return;
}
if ( !( cvar_modifiedFlags & CVAR_ARCHIVE ) ) {
return;
}
cvar_modifiedFlags &= ~CVAR_ARCHIVE;
Com_WriteConfigToFile( Q3CONFIG_CFG );
// not needed for dedicated or standalone
#if !defined(DEDICATED) && !defined(STANDALONE)
fs = Cvar_Get( "fs_game", "", CVAR_INIT | CVAR_SYSTEMINFO );
if(!com_standalone->integer)
{
if (UI_usesUniqueCDKey() && fs && fs->string[0] != 0) {
Com_WriteCDKey( fs->string, &cl_cdkey[16] );
} else {
Com_WriteCDKey( BASEGAME, cl_cdkey );
}
}
#endif
}
/*
===============
Com_WriteConfig_f
Write the config file to a specific name
===============
*/
void Com_WriteConfig_f( void ) {
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: writeconfig <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
Com_Printf( "Writing %s.\n", filename );
Com_WriteConfigToFile( filename );
}
/*
================
Com_ModifyMsec
================
*/
int Com_ModifyMsec( int msec ) {
int clampTime;
//
// modify time for debugging values
//
if ( com_fixedtime->integer ) {
msec = com_fixedtime->integer;
} else if ( com_timescale->value ) {
msec *= com_timescale->value;
// } else if (com_cameraMode->integer) {
// msec *= com_timescale->value;
}
// don't let it scale below 1 msec
if ( msec < 1 && com_timescale->value ) {
msec = 1;
}
if ( com_dedicated->integer ) {
// dedicated servers don't want to clamp for a much longer
// period, because it would mess up all the client's views
// of time.
if ( com_sv_running->integer && msec > 500 && msec < 500000 ) {
Com_Printf( "Hitch warning: %i msec frame time\n", msec );
}
clampTime = 5000;
} else
if ( !com_sv_running->integer ) {
// clients of remote servers do not want to clamp time, because
// it would skew their view of the server's time temporarily
clampTime = 5000;
} else {
// for local single player gaming
// we may want to clamp the time to prevent players from
// flying off edges when something hitches.
clampTime = 200;
}
if ( msec > clampTime ) {
msec = clampTime;
}
return msec;
}
/*
=================
Com_TimeVal
=================
*/
int Com_TimeVal(int minMsec)
{
int timeVal;
timeVal = Sys_Milliseconds() - com_frameTime;
if(timeVal >= minMsec)
timeVal = 0;
else
timeVal = minMsec - timeVal;
return timeVal;
}
/*
=================
Com_Frame
=================
*/
void Com_Frame( void ) {
int msec, minMsec;
int timeVal, timeValSV;
static int lastTime = 0, bias = 0;
int timeBeforeFirstEvents;
int timeBeforeServer;
int timeBeforeEvents;
int timeBeforeClient;
int timeAfter;
if ( setjmp( abortframe ) ) {
return; // an ERR_DROP was thrown
}
timeBeforeFirstEvents = 0;
timeBeforeServer = 0;
timeBeforeEvents = 0;
timeBeforeClient = 0;
timeAfter = 0;
// DHM - Nerve :: Don't write config on Update Server
#ifndef UPDATE_SERVER
// write config file if anything changed
Com_WriteConfiguration();
#endif
//
// main event loop
//
if ( com_speeds->integer ) {
timeBeforeFirstEvents = Sys_Milliseconds();
}
// Figure out how much time we have
if(!com_timedemo->integer)
{
if(com_dedicated->integer)
minMsec = SV_FrameMsec();
else
{
if(com_minimized->integer && com_maxfpsMinimized->integer > 0)
minMsec = 1000 / com_maxfpsMinimized->integer;
else if(com_unfocused->integer && com_maxfpsUnfocused->integer > 0)
minMsec = 1000 / com_maxfpsUnfocused->integer;
else if(com_maxfps->integer > 0)
minMsec = 1000 / com_maxfps->integer;
else
minMsec = 1;
timeVal = com_frameTime - lastTime;
bias += timeVal - minMsec;
if(bias > minMsec)
bias = minMsec;
// Adjust minMsec if previous frame took too long to render so
// that framerate is stable at the requested value.
minMsec -= bias;
}
}
else
minMsec = 1;
do
{
if(com_sv_running->integer)
{
timeValSV = SV_SendQueuedPackets();
timeVal = Com_TimeVal(minMsec);
if(timeValSV < timeVal)
timeVal = timeValSV;
}
else
timeVal = Com_TimeVal(minMsec);
if(com_busyWait->integer || timeVal < 1)
NET_Sleep(0);
else
NET_Sleep(timeVal - 1);
} while(Com_TimeVal(minMsec));
lastTime = com_frameTime;
com_frameTime = Com_EventLoop();
msec = com_frameTime - lastTime;
Cbuf_Execute();
if (com_altivec->modified)
{
Com_DetectAltivec();
com_altivec->modified = qfalse;
}
// mess with msec if needed
msec = Com_ModifyMsec(msec);
//
// server side
//
if ( com_speeds->integer ) {
timeBeforeServer = Sys_Milliseconds();
}
SV_Frame( msec );
// if "dedicated" has been modified, start up
// or shut down the client system.
// Do this after the server may have started,
// but before the client tries to auto-connect
if ( com_dedicated->modified ) {
// get the latched value
Cvar_Get( "dedicated", "0", 0 );
com_dedicated->modified = qfalse;
if ( !com_dedicated->integer ) {
SV_Shutdown( "dedicated set to 0" );
CL_FlushMemory();
}
}
#ifndef DEDICATED
//
// client system
//
//
// run event loop a second time to get server to client packets
// without a frame of latency
//
if ( com_speeds->integer ) {
timeBeforeEvents = Sys_Milliseconds ();
}
Com_EventLoop();
Cbuf_Execute ();
//
// client side
//
if ( com_speeds->integer ) {
timeBeforeClient = Sys_Milliseconds ();
}
CL_Frame( msec );
if ( com_speeds->integer ) {
timeAfter = Sys_Milliseconds ();
}
#else
if ( com_speeds->integer ) {
timeAfter = Sys_Milliseconds ();
timeBeforeEvents = timeAfter;
timeBeforeClient = timeAfter;
}
#endif
NET_FlushPacketQueue();
//
// report timing information
//
if ( com_speeds->integer ) {
int all, sv, ev, cl;
all = timeAfter - timeBeforeServer;
sv = timeBeforeEvents - timeBeforeServer;
ev = timeBeforeServer - timeBeforeFirstEvents + timeBeforeClient - timeBeforeEvents;
cl = timeAfter - timeBeforeClient;
sv -= time_game;
cl -= time_frontend + time_backend;
Com_Printf( "frame:%i all:%3i sv:%3i ev:%3i cl:%3i gm:%3i rf:%3i bk:%3i\n",
com_frameNumber, all, sv, ev, cl, time_game, time_frontend, time_backend );
}
//
// trace optimization tracking
//
if ( com_showtrace->integer ) {
extern int c_traces, c_brush_traces, c_patch_traces;
extern int c_pointcontents;
Com_Printf( "%4i traces (%ib %ip) %4i points\n", c_traces,
c_brush_traces, c_patch_traces, c_pointcontents );
c_traces = 0;
c_brush_traces = 0;
c_patch_traces = 0;
c_pointcontents = 0;
}
Com_ReadFromPipe( );
com_frameNumber++;
}
/*
=================
Com_Shutdown
=================
*/
void Com_Shutdown( void ) {
// write config file if anything changed
Com_WriteConfiguration();
if ( logfile ) {
FS_FCloseFile( logfile );
logfile = 0;
}
if ( com_journalFile ) {
FS_FCloseFile( com_journalFile );
com_journalFile = 0;
}
if( pipefile ) {
FS_FCloseFile( pipefile );
FS_HomeRemove( com_pipefile->string );
}
}
/*
===========================================
command line completion
===========================================
*/
/*
==================
Field_Clear
==================
*/
void Field_Clear( field_t *edit ) {
memset( edit->buffer, 0, MAX_EDIT_LINE );
edit->cursor = 0;
edit->scroll = 0;
}
static const char *completionString;
static char shortestMatch[MAX_TOKEN_CHARS];
static int matchCount;
// field we are working on, passed to Field_AutoComplete(&g_consoleCommand for instance)
static field_t *completionField;
/*
===============
FindMatches
===============
*/
static void FindMatches( const char *s ) {
int i;
if ( Q_stricmpn( s, completionString, strlen( completionString ) ) ) {
return;
}
matchCount++;
if ( matchCount == 1 ) {
Q_strncpyz( shortestMatch, s, sizeof( shortestMatch ) );
return;
}
// cut shortestMatch to the amount common with s
for ( i = 0 ; shortestMatch[i] ; i++ ) {
if ( i >= strlen( s ) ) {
shortestMatch[i] = 0;
break;
}
if ( tolower( shortestMatch[i] ) != tolower( s[i] ) ) {
shortestMatch[i] = 0;
}
}
}
/*
===============
PrintMatches
===============
*/
static void PrintMatches( const char *s ) {
if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
Com_Printf( " %s\n", s );
}
}
/*
===============
PrintCvarMatches
===============
*/
static void PrintCvarMatches( const char *s ) {
char value[ TRUNCATE_LENGTH ];
if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
Com_TruncateLongString( value, Cvar_VariableString( s ) );
Com_Printf( " %s = \"%s\"\n", s, value );
}
}
/*
===============
Field_FindFirstSeparator
===============
*/
static char *Field_FindFirstSeparator( char *s )
{
int i;
for( i = 0; i < strlen( s ); i++ )
{
if( s[ i ] == ';' )
return &s[ i ];
}
return NULL;
}
/*
===============
Field_Complete
===============
*/
static qboolean Field_Complete( void )
{
int completionOffset;
if( matchCount == 0 )
return qtrue;
completionOffset = strlen( completionField->buffer ) - strlen( completionString );
Q_strncpyz( &completionField->buffer[ completionOffset ], shortestMatch,
sizeof( completionField->buffer ) - completionOffset );
completionField->cursor = strlen( completionField->buffer );
if( matchCount == 1 )
{
Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " );
completionField->cursor++;
return qtrue;
}
Com_Printf( "]%s\n", completionField->buffer );
return qfalse;
}
#ifndef DEDICATED
/*
===============
Field_CompleteKeyname
===============
*/
void Field_CompleteKeyname( void )
{
matchCount = 0;
shortestMatch[ 0 ] = 0;
Key_KeynameCompletion( FindMatches );
if( !Field_Complete( ) )
Key_KeynameCompletion( PrintMatches );
}
#endif
/*
===============
Field_CompleteFilename
===============
*/
void Field_CompleteFilename( const char *dir,
const char *ext, qboolean stripExt, qboolean allowNonPureFilesOnDisk )
{
matchCount = 0;
shortestMatch[ 0 ] = 0;
FS_FilenameCompletion( dir, ext, stripExt, FindMatches, allowNonPureFilesOnDisk );
if( !Field_Complete( ) )
FS_FilenameCompletion( dir, ext, stripExt, PrintMatches, allowNonPureFilesOnDisk );
}
/*
===============
Field_CompleteCommand
===============
*/
void Field_CompleteCommand( char *cmd,
qboolean doCommands, qboolean doCvars )
{
int completionArgument = 0;
// Skip leading whitespace and quotes
cmd = Com_SkipCharset( cmd, " \"" );
Cmd_TokenizeStringIgnoreQuotes( cmd );
completionArgument = Cmd_Argc( );
// If there is trailing whitespace on the cmd
if( *( cmd + strlen( cmd ) - 1 ) == ' ' )
{
completionString = "";
completionArgument++;
}
else
completionString = Cmd_Argv( completionArgument - 1 );
#ifndef DEDICATED
// Unconditionally add a '\' to the start of the buffer
if( completionField->buffer[ 0 ] &&
completionField->buffer[ 0 ] != '\\' )
{
if( completionField->buffer[ 0 ] != '/' )
{
// Buffer is full, refuse to complete
if( strlen( completionField->buffer ) + 1 >=
sizeof( completionField->buffer ) )
return;
memmove( &completionField->buffer[ 1 ],
&completionField->buffer[ 0 ],
strlen( completionField->buffer ) + 1 );
completionField->cursor++;
}
completionField->buffer[ 0 ] = '\\';
}
#endif
if( completionArgument > 1 )
{
const char *baseCmd = Cmd_Argv( 0 );
char *p;
#ifndef DEDICATED
// This should always be true
if( baseCmd[ 0 ] == '\\' || baseCmd[ 0 ] == '/' )
baseCmd++;
#endif
if( ( p = Field_FindFirstSeparator( cmd ) ) )
Field_CompleteCommand( p + 1, qtrue, qtrue ); // Compound command
else
Cmd_CompleteArgument( baseCmd, cmd, completionArgument );
}
else
{
if( completionString[0] == '\\' || completionString[0] == '/' )
completionString++;
matchCount = 0;
shortestMatch[ 0 ] = 0;
if( strlen( completionString ) == 0 )
return;
if( doCommands )
Cmd_CommandCompletion( FindMatches );
if( doCvars )
Cvar_CommandCompletion( FindMatches );
if( !Field_Complete( ) )
{
// run through again, printing matches
if( doCommands )
Cmd_CommandCompletion( PrintMatches );
if( doCvars )
Cvar_CommandCompletion( PrintCvarMatches );
}
}
}
/*
===============
Field_AutoComplete
Perform Tab expansion
===============
*/
void Field_AutoComplete( field_t *field )
{
completionField = field;
Field_CompleteCommand( completionField->buffer, qtrue, qtrue );
}
/*
==================
Com_RandomBytes
fills string array with len random bytes, peferably from the OS randomizer
==================
*/
void Com_RandomBytes( byte *string, int len )
{
int i;
if( Sys_RandomBytes( string, len ) )
return;
Com_Printf( "Com_RandomBytes: using weak randomization\n" );
for( i = 0; i < len; i++ )
string[i] = (unsigned char)( rand() % 256 );
}
/*
==================
Com_IsVoipTarget
Returns non-zero if given clientNum is enabled in voipTargets, zero otherwise.
If clientNum is negative return if any bit is set.
==================
*/
qboolean Com_IsVoipTarget(uint8_t *voipTargets, int voipTargetsSize, int clientNum)
{
int index;
if(clientNum < 0)
{
for(index = 0; index < voipTargetsSize; index++)
{
if(voipTargets[index])
return qtrue;
}
return qfalse;
}
index = clientNum >> 3;
if(index < voipTargetsSize)
return (voipTargets[index] & (1 << (clientNum & 0x07)));
return qfalse;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3231_1 |
crossvul-cpp_data_bad_3086_1 | /*
* Copyright (C) 2014-2016 Firejail Authors
*
* This file is part of firejail 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <net/if.h>
#include "firejail.h"
//***********************************
// interface bandwidth linked list
//***********************************
typedef struct ifbw_t {
struct ifbw_t *next;
char *txt;
} IFBW;
IFBW *ifbw = NULL;
#if 0
static void ifbw_print(void) {
IFBW *ptr = ifbw;
while (ptr) {
printf("#%s#\n", ptr->txt);
ptr = ptr->next;
}
}
#endif
static void ifbw_add(IFBW *ptr) {
assert(ptr);
if (ifbw != NULL)
ptr->next = ifbw;
ifbw = ptr;
}
IFBW *ifbw_find(const char *dev) {
assert(dev);
int len = strlen(dev);
assert(len);
if (ifbw == NULL)
return NULL;
IFBW *ptr = ifbw;
while (ptr) {
if (strncmp(ptr->txt, dev, len) == 0 && ptr->txt[len] == ':')
return ptr;
ptr = ptr->next;
}
return NULL;
}
void ifbw_remove(IFBW *r) {
if (ifbw == NULL)
return;
// remove the first element
if (ifbw == r) {
ifbw = ifbw->next;
return;
}
// walk the list
IFBW *ptr = ifbw->next;
IFBW *prev = ifbw;
while (ptr) {
if (ptr == r) {
prev->next = ptr->next;
return;
}
prev = ptr;
ptr = ptr->next;
}
return;
}
int fibw_count(void) {
int rv = 0;
IFBW *ptr = ifbw;
while (ptr) {
rv++;
ptr = ptr->next;
}
return rv;
}
//***********************************
// run file handling
//***********************************
static void bandwidth_create_run_file(pid_t pid) {
char *fname;
if (asprintf(&fname, "%s/%d-bandwidth", RUN_FIREJAIL_BANDWIDTH_DIR, (int) pid) == -1)
errExit("asprintf");
// if the file already exists, do nothing
struct stat s;
if (stat(fname, &s) == 0) {
free(fname);
return;
}
// create an empty file and set mod and ownership
/* coverity[toctou] */
FILE *fp = fopen(fname, "w");
if (fp) {
SET_PERMS_STREAM(fp, 0, 0, 0644);
fclose(fp);
}
else {
fprintf(stderr, "Error: cannot create bandwidth file\n");
exit(1);
}
free(fname);
}
// delete bandwidth file
void bandwidth_del_run_file(pid_t pid) {
char *fname;
if (asprintf(&fname, "%s/%d-bandwidth", RUN_FIREJAIL_BANDWIDTH_DIR, (int) pid) == -1)
errExit("asprintf");
unlink(fname);
free(fname);
}
void network_del_run_file(pid_t pid) {
char *fname;
if (asprintf(&fname, "%s/%d-netmap", RUN_FIREJAIL_NETWORK_DIR, (int) pid) == -1)
errExit("asprintf");
unlink(fname);
free(fname);
}
void network_set_run_file(pid_t pid) {
char *fname;
if (asprintf(&fname, "%s/%d-netmap", RUN_FIREJAIL_NETWORK_DIR, (int) pid) == -1)
errExit("asprintf");
// create an empty file and set mod and ownership
FILE *fp = fopen(fname, "w");
if (fp) {
if (cfg.bridge0.configured)
fprintf(fp, "%s:%s\n", cfg.bridge0.dev, cfg.bridge0.devsandbox);
if (cfg.bridge1.configured)
fprintf(fp, "%s:%s\n", cfg.bridge1.dev, cfg.bridge1.devsandbox);
if (cfg.bridge2.configured)
fprintf(fp, "%s:%s\n", cfg.bridge2.dev, cfg.bridge2.devsandbox);
if (cfg.bridge3.configured)
fprintf(fp, "%s:%s\n", cfg.bridge3.dev, cfg.bridge3.devsandbox);
SET_PERMS_STREAM(fp, 0, 0, 0644);
fclose(fp);
}
else {
fprintf(stderr, "Error: cannot create network map file\n");
exit(1);
}
free(fname);
}
static void read_bandwidth_file(pid_t pid) {
assert(ifbw == NULL);
char *fname;
if (asprintf(&fname, "%s/%d-bandwidth", RUN_FIREJAIL_BANDWIDTH_DIR, (int) pid) == -1)
errExit("asprintf");
FILE *fp = fopen(fname, "r");
if (fp) {
char buf[1024];
while (fgets(buf, 1024,fp)) {
// remove '\n'
char *ptr = strchr(buf, '\n');
if (ptr)
*ptr = '\0';
if (strlen(buf) == 0)
continue;
// create a new IFBW entry
IFBW *ifbw_new = malloc(sizeof(IFBW));
if (!ifbw_new)
errExit("malloc");
memset(ifbw_new, 0, sizeof(IFBW));
ifbw_new->txt = strdup(buf);
if (!ifbw_new->txt)
errExit("strdup");
// add it to the linked list
ifbw_add(ifbw_new);
}
fclose(fp);
}
}
static void write_bandwidth_file(pid_t pid) {
if (ifbw == NULL)
return; // nothing to do
char *fname;
if (asprintf(&fname, "%s/%d-bandwidth", RUN_FIREJAIL_BANDWIDTH_DIR, (int) pid) == -1)
errExit("asprintf");
FILE *fp = fopen(fname, "w");
if (fp) {
IFBW *ptr = ifbw;
while (ptr) {
if (fprintf(fp, "%s\n", ptr->txt) < 0)
goto errout;
ptr = ptr->next;
}
fclose(fp);
}
else
goto errout;
return;
errout:
fprintf(stderr, "Error: cannot write bandwidth file %s\n", fname);
exit(1);
}
//***********************************
// add or remove interfaces
//***********************************
// remove interface from run file
void bandwidth_remove(pid_t pid, const char *dev) {
bandwidth_create_run_file(pid);
// read bandwidth file
read_bandwidth_file(pid);
// find the element and remove it
IFBW *elem = ifbw_find(dev);
if (elem) {
ifbw_remove(elem);
write_bandwidth_file(pid) ;
}
// remove the file if there are no entries in the list
if (ifbw == NULL) {
bandwidth_del_run_file(pid);
}
}
// add interface to run file
void bandwidth_set(pid_t pid, const char *dev, int down, int up) {
// create bandwidth directory & file in case they are not in the filesystem yet
bandwidth_create_run_file(pid);
// create the new text entry
char *txt;
if (asprintf(&txt, "%s: RX %dKB/s, TX %dKB/s", dev, down, up) == -1)
errExit("asprintf");
// read bandwidth file
read_bandwidth_file(pid);
// look for an existing entry and replace the text
IFBW *ptr = ifbw_find(dev);
if (ptr) {
assert(ptr->txt);
free(ptr->txt);
ptr->txt = txt;
}
// ... or add a new entry
else {
IFBW *ifbw_new = malloc(sizeof(IFBW));
if (!ifbw_new)
errExit("malloc");
memset(ifbw_new, 0, sizeof(IFBW));
ifbw_new->txt = txt;
// add it to the linked list
ifbw_add(ifbw_new);
}
write_bandwidth_file(pid) ;
}
//***********************************
// command execution
//***********************************
void bandwidth_pid(pid_t pid, const char *command, const char *dev, int down, int up) {
EUID_ASSERT();
//************************
// verify sandbox
//************************
EUID_ROOT();
char *comm = pid_proc_comm(pid);
EUID_USER();
if (!comm) {
fprintf(stderr, "Error: cannot find sandbox\n");
exit(1);
}
// check for firejail sandbox
if (strcmp(comm, "firejail") != 0) {
fprintf(stderr, "Error: cannot find sandbox\n");
exit(1);
}
free(comm);
// check network namespace
char *name;
if (asprintf(&name, "/run/firejail/network/%d-netmap", pid) == -1)
errExit("asprintf");
struct stat s;
if (stat(name, &s) == -1) {
fprintf(stderr, "Error: the sandbox doesn't use a new network namespace\n");
exit(1);
}
//************************
// join the network namespace
//************************
pid_t child;
if (find_child(pid, &child) == -1) {
fprintf(stderr, "Error: cannot join the network namespace\n");
exit(1);
}
EUID_ROOT();
if (join_namespace(child, "net")) {
fprintf(stderr, "Error: cannot join the network namespace\n");
exit(1);
}
// set run file
if (strcmp(command, "set") == 0)
bandwidth_set(pid, dev, down, up);
else if (strcmp(command, "clear") == 0)
bandwidth_remove(pid, dev);
//************************
// build command
//************************
char *devname = NULL;
if (dev) {
// read network map file
char *fname;
if (asprintf(&fname, "%s/%d-netmap", RUN_FIREJAIL_NETWORK_DIR, (int) pid) == -1)
errExit("asprintf");
FILE *fp = fopen(fname, "r");
if (!fp) {
fprintf(stderr, "Error: cannot read network map file %s\n", fname);
exit(1);
}
char buf[1024];
int len = strlen(dev);
while (fgets(buf, 1024, fp)) {
// remove '\n'
char *ptr = strchr(buf, '\n');
if (ptr)
*ptr = '\0';
if (*buf == '\0')
break;
if (strncmp(buf, dev, len) == 0 && buf[len] == ':') {
devname = strdup(buf + len + 1);
if (!devname)
errExit("strdup");
// check device in namespace
if (if_nametoindex(devname) == 0) {
fprintf(stderr, "Error: cannot find network device %s\n", devname);
exit(1);
}
break;
}
}
free(fname);
fclose(fp);
}
// build fshaper.sh command
char *cmd = NULL;
if (devname) {
if (strcmp(command, "set") == 0) {
if (asprintf(&cmd, "%s/firejail/fshaper.sh --%s %s %d %d",
LIBDIR, command, devname, down, up) == -1)
errExit("asprintf");
}
else {
if (asprintf(&cmd, "%s/firejail/fshaper.sh --%s %s",
LIBDIR, command, devname) == -1)
errExit("asprintf");
}
}
else {
if (asprintf(&cmd, "%s/firejail/fshaper.sh --%s", LIBDIR, command) == -1)
errExit("asprintf");
}
assert(cmd);
// wipe out environment variables
environ = NULL;
//************************
// build command
//************************
// elevate privileges
if (setreuid(0, 0))
errExit("setreuid");
if (setregid(0, 0))
errExit("setregid");
if (!cfg.shell)
cfg.shell = guess_shell();
if (!cfg.shell) {
fprintf(stderr, "Error: no POSIX shell found, please use --shell command line option\n");
exit(1);
}
char *arg[4];
arg[0] = cfg.shell;
arg[1] = "-c";
arg[2] = cmd;
arg[3] = NULL;
clearenv();
execvp(arg[0], arg);
// it will never get here
errExit("execvp");
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3086_1 |
crossvul-cpp_data_good_3152_1 | /*
* Copyright (C) 2014-2016 Firejail Authors
*
* This file is part of firejail 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "firejail.h"
#include <sys/mount.h>
#include <linux/limits.h>
#include <glob.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <grp.h>
#include <ftw.h>
static void skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
// zsh
if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) {
// copy skel files
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.zshrc", &s) == 0) {
copy_file("/etc/skel/.zshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.zshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
// csh
else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) {
// copy skel files
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.cshrc", &s) == 0) {
copy_file("/etc/skel/.cshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.cshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
// bash etc.
else {
// copy skel files
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.bashrc", &s) == 0) {
copy_file("/etc/skel/.bashrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.bashrc");
}
free(fname);
}
}
static int store_xauthority(void) {
// put a copy of .Xauthority in XAUTHORITY_FILE
fs_build_mnt_dir();
char *src;
char *dest = RUN_XAUTHORITY_FILE;
// create an empty file
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0600);
fclose(fp);
}
if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Warning: invalid .Xauthority file\n");
return 0;
}
copy_file_as_user(src, dest, getuid(), getgid(), 0600);
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
static int store_asoundrc(void) {
// put a copy of .Xauthority in XAUTHORITY_FILE
fs_build_mnt_dir();
char *src;
char *dest = RUN_ASOUNDRC_FILE;
// create an empty file
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0644);
fclose(fp);
}
if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
// make sure the real path of the file is inside the home directory
/* coverity[toctou] */
char* rp = realpath(src, NULL);
if (!rp) {
fprintf(stderr, "Error: Cannot access %s\n", src);
exit(1);
}
if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n");
exit(1);
}
free(rp);
}
copy_file_as_user(src, dest, getuid(), getgid(), 0644);
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
static void copy_xauthority(void) {
// copy XAUTHORITY_FILE in the new home directory
char *src = RUN_XAUTHORITY_FILE ;
char *dest;
if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
// if destination is a symbolic link, exit the sandbox!!!
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR);
fs_logger2("clone", dest);
// delete the temporary file
unlink(src);
}
static void copy_asoundrc(void) {
// copy XAUTHORITY_FILE in the new home directory
char *src = RUN_ASOUNDRC_FILE ;
char *dest;
if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
// if destination is a symbolic link, exit the sandbox!!!
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR);
fs_logger2("clone", dest);
// delete the temporary file
unlink(src);
}
// private mode (--private=homedir):
// mount homedir on top of /home/user,
// tmpfs on top of /root in nonroot mode,
// set skel files,
// restore .Xauthority
void fs_private_homedir(void) {
char *homedir = cfg.homedir;
char *private_homedir = cfg.home_private;
assert(homedir);
assert(private_homedir);
int xflag = store_xauthority();
int aflag = store_asoundrc();
uid_t u = getuid();
gid_t g = getgid();
struct stat s;
if (stat(homedir, &s) == -1) {
fprintf(stderr, "Error: cannot find user home directory\n");
exit(1);
}
// mount bind private_homedir on top of homedir
if (arg_debug)
printf("Mount-bind %s on top of %s\n", private_homedir, homedir);
if (mount(private_homedir, homedir, NULL, MS_NOSUID | MS_NODEV | MS_BIND | MS_REC, NULL) < 0)
errExit("mount bind");
fs_logger3("mount-bind", private_homedir, cfg.homedir);
fs_logger2("whitelist", cfg.homedir);
// preserve mode and ownership
// if (chown(homedir, s.st_uid, s.st_gid) == -1)
// errExit("mount-bind chown");
// if (chmod(homedir, s.st_mode) == -1)
// errExit("mount-bind chmod");
if (u != 0) {
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting home directory");
fs_logger("tmpfs /root");
}
else {
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
fs_logger("tmpfs /home");
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
// private mode (--private):
// mount tmpfs over /home/user,
// tmpfs on top of /root in nonroot mode,
// set skel files,
// restore .Xauthority
void fs_private(void) {
char *homedir = cfg.homedir;
assert(homedir);
uid_t u = getuid();
gid_t g = getgid();
int xflag = store_xauthority();
int aflag = store_asoundrc();
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
fs_logger("tmpfs /home");
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting root directory");
fs_logger("tmpfs /root");
if (u != 0) {
// create /home/user
if (arg_debug)
printf("Create a new user directory\n");
if (mkdir(homedir, S_IRWXU) == -1) {
if (mkpath_as_root(homedir) == -1)
errExit("mkpath");
if (mkdir(homedir, S_IRWXU) == -1)
errExit("mkdir");
}
if (chown(homedir, u, g) < 0)
errExit("chown");
fs_logger2("mkdir", homedir);
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
// check new private home directory (--private= option) - exit if it fails
void fs_check_private_dir(void) {
EUID_ASSERT();
invalid_filename(cfg.home_private);
// Expand the home directory
char *tmp = expand_home(cfg.home_private, cfg.homedir);
cfg.home_private = realpath(tmp, NULL);
free(tmp);
if (!cfg.home_private
|| !is_dir(cfg.home_private)
|| is_link(cfg.home_private)
|| strstr(cfg.home_private, "..")) {
fprintf(stderr, "Error: invalid private directory\n");
exit(1);
}
// check home directory and chroot home directory have the same owner
struct stat s2;
int rv = stat(cfg.home_private, &s2);
if (rv < 0) {
fprintf(stderr, "Error: cannot find %s directory\n", cfg.home_private);
exit(1);
}
struct stat s1;
rv = stat(cfg.homedir, &s1);
if (rv < 0) {
fprintf(stderr, "Error: cannot find %s directory, full path name required\n", cfg.homedir);
exit(1);
}
if (s1.st_uid != s2.st_uid) {
printf("Error: --private directory should be owned by the current user\n");
exit(1);
}
}
//***********************************************************************************
// --private-home
//***********************************************************************************
#define PRIVATE_COPY_LIMIT (500 * 1024 *1024)
static int size_limit_reached = 0;
static unsigned file_cnt = 0;
static unsigned size_cnt = 0;
static char *check_dir_or_file(const char *name);
int fs_copydir(const char *path, const struct stat *st, int ftype, struct FTW *sftw) {
(void) st;
(void) sftw;
if (size_limit_reached)
return 0;
struct stat s;
char *dest;
if (asprintf(&dest, "%s%s", RUN_HOME_DIR, path + strlen(cfg.homedir)) == -1)
errExit("asprintf");
// don't copy it if we already have the file
if (stat(dest, &s) == 0) {
free(dest);
return 0;
}
// extract mode and ownership
if (stat(path, &s) != 0) {
free(dest);
return 0;
}
// check uid
if (s.st_uid != firejail_uid || s.st_gid != firejail_gid) {
free(dest);
return 0;
}
if ((s.st_size + size_cnt) > PRIVATE_COPY_LIMIT) {
size_limit_reached = 1;
free(dest);
return 0;
}
file_cnt++;
size_cnt += s.st_size;
if(ftype == FTW_F)
copy_file(path, dest, firejail_uid, firejail_gid, s.st_mode);
else if (ftype == FTW_D) {
if (mkdir(dest, s.st_mode) == -1)
errExit("mkdir");
if (chmod(dest, s.st_mode) < 0) {
fprintf(stderr, "Error: cannot change mode for %s\n", path);
exit(1);
}
if (chown(dest, firejail_uid, firejail_gid) < 0) {
fprintf(stderr, "Error: cannot change ownership for %s\n", path);
exit(1);
}
#if 0
struct stat s2;
if (stat(dest, &s2) == 0) {
printf("%s\t", dest);
printf((S_ISDIR(s.st_mode)) ? "d" : "-");
printf((s.st_mode & S_IRUSR) ? "r" : "-");
printf((s.st_mode & S_IWUSR) ? "w" : "-");
printf((s.st_mode & S_IXUSR) ? "x" : "-");
printf((s.st_mode & S_IRGRP) ? "r" : "-");
printf((s.st_mode & S_IWGRP) ? "w" : "-");
printf((s.st_mode & S_IXGRP) ? "x" : "-");
printf((s.st_mode & S_IROTH) ? "r" : "-");
printf((s.st_mode & S_IWOTH) ? "w" : "-");
printf((s.st_mode & S_IXOTH) ? "x" : "-");
printf("\n");
}
#endif
fs_logger2("clone", path);
}
free(dest);
return(0);
}
static void duplicate(char *name) {
char *fname = check_dir_or_file(name);
if (arg_debug)
printf("Private home: duplicating %s\n", fname);
assert(strncmp(fname, cfg.homedir, strlen(cfg.homedir)) == 0);
struct stat s;
if (stat(fname, &s) == -1) {
free(fname);
return;
}
if(nftw(fname, fs_copydir, 1, FTW_PHYS) != 0) {
fprintf(stderr, "Error: unable to copy template dir\n");
exit(1);
}
fs_logger_print(); // save the current log
free(fname);
}
static char *check_dir_or_file(const char *name) {
assert(name);
struct stat s;
// basic checks
invalid_filename(name);
if (arg_debug)
printf("Private home: checking %s\n", name);
// expand home directory
char *fname = expand_home(name, cfg.homedir);
if (!fname) {
fprintf(stderr, "Error: file %s not found.\n", name);
exit(1);
}
// If it doesn't start with '/', it must be relative to homedir
if (fname[0] != '/') {
char* tmp;
if (asprintf(&tmp, "%s/%s", cfg.homedir, fname) == -1)
errExit("asprintf");
free(fname);
fname = tmp;
}
// check the file is in user home directory
char *rname = realpath(fname, NULL);
if (!rname) {
fprintf(stderr, "Error: invalid file %s\n", name);
exit(1);
}
if (strncmp(rname, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: file %s is not in user home directory\n", name);
exit(1);
}
// a full home directory is not allowed
if (strcmp(rname, cfg.homedir) == 0) {
fprintf(stderr, "Error: invalid directory %s\n", rname);
exit(1);
}
// only top files and directories in user home are allowed
char *ptr = rname + strlen(cfg.homedir);
if (*ptr == '\0') {
fprintf(stderr, "Error: invalid file %s\n", name);
exit(1);
}
ptr++;
ptr = strchr(ptr, '/');
if (ptr) {
if (*ptr != '\0') {
fprintf(stderr, "Error: only top files and directories in user home are allowed\n");
exit(1);
}
}
if (stat(fname, &s) == -1) {
fprintf(stderr, "Error: file %s not found.\n", fname);
exit(1);
}
// check uid
uid_t uid = getuid();
gid_t gid = getgid();
if (s.st_uid != uid || s.st_gid != gid) {
fprintf(stderr, "Error: only files or directories created by the current user are allowed.\n");
exit(1);
}
// dir or regular file
if (S_ISDIR(s.st_mode) || S_ISREG(s.st_mode)) {
free(fname);
return rname; // regular exit from the function
}
fprintf(stderr, "Error: invalid file type, %s.\n", fname);
exit(1);
}
// check directory list specified by user (--private-home option) - exit if it fails
void fs_check_home_list(void) {
if (strstr(cfg.home_private_keep, "..")) {
fprintf(stderr, "Error: invalid private-home list\n");
exit(1);
}
char *dlist = strdup(cfg.home_private_keep);
if (!dlist)
errExit("strdup");
char *ptr = strtok(dlist, ",");
char *tmp = check_dir_or_file(ptr);
free(tmp);
while ((ptr = strtok(NULL, ",")) != NULL) {
tmp = check_dir_or_file(ptr);
free(tmp);
}
free(dlist);
}
// private mode (--private-home=list):
// mount homedir on top of /home/user,
// tmpfs on top of /root in nonroot mode,
// tmpfs on top of /tmp in root mode,
// set skel files,
// restore .Xauthority
void fs_private_home_list(void) {
char *homedir = cfg.homedir;
char *private_list = cfg.home_private_keep;
assert(homedir);
assert(private_list);
int xflag = store_xauthority();
int aflag = store_asoundrc();
uid_t u = firejail_uid;
gid_t g = firejail_gid;
struct stat s;
if (stat(homedir, &s) == -1) {
fprintf(stderr, "Error: cannot find user home directory\n");
exit(1);
}
// create /run/firejail/mnt/home directory
fs_build_mnt_dir();
int rv = mkdir(RUN_HOME_DIR, 0755);
if (rv == -1)
errExit("mkdir");
if (chown(RUN_HOME_DIR, u, g) < 0)
errExit("chown");
if (chmod(RUN_HOME_DIR, 0755) < 0)
errExit("chmod");
ASSERT_PERMS(RUN_HOME_DIR, u, g, 0755);
fs_logger_print(); // save the current log
// copy the list of files in the new home directory
// using a new child process without root privileges
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
if (arg_debug)
printf("Copying files in the new home:\n");
// drop privileges
if (setgroups(0, NULL) < 0)
errExit("setgroups");
if (setgid(getgid()) < 0)
errExit("setgid/getgid");
if (setuid(getuid()) < 0)
errExit("setuid/getuid");
// copy the list of files in the new home directory
char *dlist = strdup(cfg.home_private_keep);
if (!dlist)
errExit("strdup");
char *ptr = strtok(dlist, ",");
duplicate(ptr);
while ((ptr = strtok(NULL, ",")) != NULL)
duplicate(ptr);
if (!arg_quiet) {
if (size_limit_reached)
fprintf(stderr, "Warning: private-home copy limit of %u MB reached, not all the files were copied\n",
PRIVATE_COPY_LIMIT / (1024 *1024));
else
printf("Private home: %u files, total size %u bytes\n", file_cnt, size_cnt);
}
fs_logger_print(); // save the current log
free(dlist);
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
if (arg_debug)
printf("Mount-bind %s on top of %s\n", RUN_HOME_DIR, homedir);
if (mount(RUN_HOME_DIR, homedir, NULL, MS_BIND|MS_REC, NULL) < 0)
errExit("mount bind");
if (u != 0) {
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting home directory");
}
else {
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3152_1 |
crossvul-cpp_data_good_3228_1 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: files.c
*
* desc: handle based filesystem for Quake III Arena
*
* $Archive: /MissionPack/code/qcommon/files.c $
*
*****************************************************************************/
#include "q_shared.h"
#include "qcommon.h"
#include "unzip.h"
/*
=============================================================================
QUAKE3 FILESYSTEM
All of Quake's data access is through a hierarchical file system, but the contents of
the file system can be transparently merged from several sources.
A "qpath" is a reference to game file data. MAX_ZPATH is 256 characters, which must include
a terminating zero. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any
references outside the quake directory system.
The "base path" is the path to the directory holding all the game directories and usually
the executable. It defaults to ".", but can be overridden with a "+set fs_basepath c:\quake3"
command line to allow code debugging in a different directory. Basepath cannot
be modified at all after startup. Any files that are created (demos, screenshots,
etc) will be created relative to the base path, so base path should usually be writable.
The "home path" is the path used for all write access. On win32 systems we have "base path"
== "home path", but on *nix systems the base installation is usually readonly, and
"home path" points to ~/.q3a or similar
The user can also install custom mods and content in "home path", so it should be searched
along with "home path" and "cd path" for game content.
The "base game" is the directory under the paths where data comes from by default, and
can be either "baseq3" or "demoq3".
The "current game" may be the same as the base game, or it may be the name of another
directory under the paths that should be searched for files before looking in the base game.
This is the basis for addons.
Clients automatically set the game directory after receiving a gamestate from a server,
so only servers need to worry about +set fs_game.
No other directories outside of the base game and current game will ever be referenced by
filesystem functions.
To save disk space and speed loading, directory trees can be collapsed into zip files.
The files use a ".pk3" extension to prevent users from unzipping them accidentally, but
otherwise the are simply normal uncompressed zip files. A game directory can have multiple
zip files of the form "pak0.pk3", "pak1.pk3", etc. Zip files are searched in decending order
from the highest number to the lowest, and will always take precedence over the filesystem.
This allows a pk3 distributed as a patch to override all existing data.
Because we will have updated executables freely available online, there is no point to
trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
should be exactly the same executables as release versions, but with different data that
automatically restricts where game media can come from to prevent add-ons from working.
File search order: when FS_FOpenFileRead gets called it will go through the fs_searchpaths
structure and stop on the first successful hit. fs_searchpaths is built with successive
calls to FS_AddGameDirectory
Additionaly, we search in several subdirectories:
current game is the current mode
base game is a variable to allow mods based on other mods
(such as baseq3 + missionpack content combination in a mod for instance)
BASEGAME is the hardcoded base game ("baseq3")
e.g. the qpath "sound/newstuff/test.wav" would be searched for in the following places:
home path + current game's zip files
home path + current game's directory
base path + current game's zip files
base path + current game's directory
cd path + current game's zip files
cd path + current game's directory
home path + base game's zip file
home path + base game's directory
base path + base game's zip file
base path + base game's directory
cd path + base game's zip file
cd path + base game's directory
home path + BASEGAME's zip file
home path + BASEGAME's directory
base path + BASEGAME's zip file
base path + BASEGAME's directory
cd path + BASEGAME's zip file
cd path + BASEGAME's directory
server download, to be written to home path + current game's directory
The filesystem can be safely shutdown and reinitialized with different
basedir / cddir / game combinations, but all other subsystems that rely on it
(sound, video) must also be forced to restart.
Because the same files are loaded by both the clip model (CM_) and renderer (TR_)
subsystems, a simple single-file caching scheme is used. The CM_ subsystems will
load the file with a request to cache. Only one file will be kept cached at a time,
so any models that are going to be referenced by both subsystems should alternate
between the CM_ load function and the ref load function.
TODO: A qpath that starts with a leading slash will always refer to the base game, even if another
game is currently active. This allows character models, skins, and sounds to be downloaded
to a common directory no matter which game is active.
How to prevent downloading zip files?
Pass pk3 file names in systeminfo, and download before FS_Restart()?
Aborting a download disconnects the client from the server.
How to mark files as downloadable? Commercial add-ons won't be downloadable.
Non-commercial downloads will want to download the entire zip file.
the game would have to be reset to actually read the zip in
Auto-update information
Path separators
Casing
separate server gamedir and client gamedir, so if the user starts
a local game after having connected to a network game, it won't stick
with the network game.
allow menu options for game selection?
Read / write config to floppy option.
Different version coexistance?
When building a pak file, make sure a q3config.cfg isn't present in it,
or configs will never get loaded from disk!
todo:
downloading (outside fs?)
game directory passing and restarting
=============================================================================
*/
// every time a new demo pk3 file is built, this checksum must be updated.
// the easiest way to get it is to just run the game and see what it spits out
#define DEMO_PAK0_CHECKSUM 2985612116u
static const unsigned int pak_checksums[] = {
1566731103u,
298122907u,
412165236u,
2991495316u,
1197932710u,
4087071573u,
3709064859u,
908855077u,
977125798u
};
static const unsigned int missionpak_checksums[] =
{
2430342401u,
511014160u,
2662638993u,
1438664554u
};
// if this is defined, the executable positively won't work with any paks other
// than the demo pak, even if productid is present. This is only used for our
// last demo release to prevent the mac and linux users from using the demo
// executable with the production windows pak before the mac/linux products
// hit the shelves a little later
// NOW defined in build files
//#define PRE_RELEASE_TADEMO
#define MAX_ZPATH 256
#define MAX_SEARCH_PATHS 4096
#define MAX_FILEHASH_SIZE 1024
typedef struct fileInPack_s {
char *name; // name of the file
unsigned long pos; // file info position in zip
unsigned long len; // uncompress file size
struct fileInPack_s* next; // next file in the hash
} fileInPack_t;
typedef struct {
char pakPathname[MAX_OSPATH]; // c:\quake3\baseq3
char pakFilename[MAX_OSPATH]; // c:\quake3\baseq3\pak0.pk3
char pakBasename[MAX_OSPATH]; // pak0
char pakGamename[MAX_OSPATH]; // baseq3
unzFile handle; // handle to zip file
int checksum; // regular checksum
int pure_checksum; // checksum for pure
int numfiles; // number of files in pk3
int referenced; // referenced file flags
int hashSize; // hash table size (power of 2)
fileInPack_t* *hashTable; // hash table
fileInPack_t* buildBuffer; // buffer with the filenames etc.
} pack_t;
typedef struct {
char path[MAX_OSPATH]; // c:\quake3
char fullpath[MAX_OSPATH]; // c:\quake3\baseq3
char gamedir[MAX_OSPATH]; // baseq3
} directory_t;
typedef struct searchpath_s {
struct searchpath_s *next;
pack_t *pack; // only one of pack / dir will be non NULL
directory_t *dir;
} searchpath_t;
static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators
static cvar_t *fs_debug;
static cvar_t *fs_homepath;
#ifdef __APPLE__
// Also search the .app bundle for .pk3 files
static cvar_t *fs_apppath;
#endif
static cvar_t *fs_steampath;
static cvar_t *fs_basepath;
static cvar_t *fs_basegame;
static cvar_t *fs_gamedirvar;
static searchpath_t *fs_searchpaths;
static int fs_readCount; // total bytes read
static int fs_loadCount; // total files read
static int fs_loadStack; // total files in memory
static int fs_packFiles = 0; // total number of files in packs
static int fs_checksumFeed;
typedef union qfile_gus {
FILE* o;
unzFile z;
} qfile_gut;
typedef struct qfile_us {
qfile_gut file;
qboolean unique;
} qfile_ut;
typedef struct {
qfile_ut handleFiles;
qboolean handleSync;
int fileSize;
int zipFilePos;
int zipFileLen;
qboolean zipFile;
qboolean streamed;
char name[MAX_ZPATH];
} fileHandleData_t;
static fileHandleData_t fsh[MAX_FILE_HANDLES];
// TTimo - https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
// wether we did a reorder on the current search path when joining the server
static qboolean fs_reordered;
// never load anything from pk3 files that are not present at the server when pure
static int fs_numServerPaks = 0;
static int fs_serverPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverPakNames[MAX_SEARCH_PATHS]; // pk3 names
// only used for autodownload, to make sure the client has at least
// all the pk3 files that are referenced at the server side
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS]; // pk3 names
// last valid game folder used
char lastValidBase[MAX_OSPATH];
char lastValidComBaseGame[MAX_OSPATH];
char lastValidFsBaseGame[MAX_OSPATH];
char lastValidGame[MAX_OSPATH];
#ifdef FS_MISSING
FILE* missingFiles = NULL;
#endif
/* C99 defines __func__ */
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2 || _MSC_VER >= 1300
# define __func__ __FUNCTION__
# else
# define __func__ "(unknown)"
# endif
#endif
/*
==============
FS_Initialized
==============
*/
qboolean FS_Initialized( void ) {
return (fs_searchpaths != NULL);
}
/*
=================
FS_PakIsPure
=================
*/
qboolean FS_PakIsPure( pack_t *pack ) {
int i;
if ( fs_numServerPaks ) {
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
// FIXME: also use hashed file names
// NOTE TTimo: a pk3 with same checksum but different name would be validated too
// I don't see this as allowing for any exploit, it would only happen if the client does manips of its file names 'not a bug'
if ( pack->checksum == fs_serverPaks[i] ) {
return qtrue; // on the aproved list
}
}
return qfalse; // not on the pure server pak list
}
return qtrue;
}
/*
=================
FS_LoadStack
return load stack
=================
*/
int FS_LoadStack( void )
{
return fs_loadStack;
}
/*
================
return a hash value for the filename
================
*/
static long FS_HashFileName( const char *fname, int hashSize ) {
int i;
long hash;
char letter;
hash = 0;
i = 0;
while (fname[i] != '\0') {
letter = tolower(fname[i]);
if (letter =='.') break; // don't include extension
if (letter =='\\') letter = '/'; // damn path names
if (letter == PATH_SEP) letter = '/'; // damn path names
hash+=(long)(letter)*(i+119);
i++;
}
hash = (hash ^ (hash >> 10) ^ (hash >> 20));
hash &= (hashSize-1);
return hash;
}
static fileHandle_t FS_HandleForFile(void) {
int i;
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o == NULL ) {
return i;
}
}
Com_Error( ERR_DROP, "FS_HandleForFile: none free" );
return 0;
}
static FILE *FS_FileForHandle( fileHandle_t f ) {
if ( f < 1 || f >= MAX_FILE_HANDLES ) {
Com_Error( ERR_DROP, "FS_FileForHandle: out of range" );
}
if (fsh[f].zipFile == qtrue) {
Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" );
}
if ( ! fsh[f].handleFiles.file.o ) {
Com_Error( ERR_DROP, "FS_FileForHandle: NULL" );
}
return fsh[f].handleFiles.file.o;
}
void FS_ForceFlush( fileHandle_t f ) {
FILE *file;
file = FS_FileForHandle(f);
setvbuf( file, NULL, _IONBF, 0 );
}
/*
================
FS_fplength
================
*/
long FS_fplength(FILE *h)
{
long pos;
long end;
pos = ftell(h);
fseek(h, 0, SEEK_END);
end = ftell(h);
fseek(h, pos, SEEK_SET);
return end;
}
/*
================
FS_filelength
If this is called on a non-unique FILE (from a pak file),
it will return the size of the pak file, not the expected
size of the file.
================
*/
long FS_filelength(fileHandle_t f)
{
FILE *h;
h = FS_FileForHandle(f);
if(h == NULL)
return -1;
else
return FS_fplength(h);
}
/*
====================
FS_ReplaceSeparators
Fix things up differently for win/unix/mac
====================
*/
static void FS_ReplaceSeparators( char *path ) {
char *s;
qboolean lastCharWasSep = qfalse;
for ( s = path ; *s ; s++ ) {
if ( *s == '/' || *s == '\\' ) {
if ( !lastCharWasSep ) {
*s = PATH_SEP;
lastCharWasSep = qtrue;
} else {
memmove (s, s + 1, strlen (s));
}
} else {
lastCharWasSep = qfalse;
}
}
}
/*
===================
FS_BuildOSPath
Qpath may have either forward or backwards slashes
===================
*/
char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) {
char temp[MAX_OSPATH];
static char ospath[2][MAX_OSPATH];
static int toggle;
toggle ^= 1; // flip-flop to allow two returns without clash
if( !game || !game[0] ) {
game = fs_gamedir;
}
Com_sprintf( temp, sizeof(temp), "/%s/%s", game, qpath );
FS_ReplaceSeparators( temp );
Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp );
return ospath[toggle];
}
/*
============
FS_CreatePath
Creates any directories needed to store the given filename
============
*/
qboolean FS_CreatePath (char *OSPath) {
char *ofs;
char path[MAX_OSPATH];
// make absolutely sure that it can't back up the path
// FIXME: is c: allowed???
if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) {
Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath );
return qtrue;
}
Q_strncpyz( path, OSPath, sizeof( path ) );
FS_ReplaceSeparators( path );
// Skip creation of the root directory as it will always be there
ofs = strchr( path, PATH_SEP );
if ( ofs != NULL ) {
ofs++;
}
for (; ofs != NULL && *ofs ; ofs++) {
if (*ofs == PATH_SEP) {
// create the directory
*ofs = 0;
if (!Sys_Mkdir (path)) {
Com_Error( ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"",
path );
}
*ofs = PATH_SEP;
}
}
return qfalse;
}
/*
=================
FS_CheckFilenameIsMutable
ERR_FATAL if trying to maniuplate a file with the platform library, QVM, or pk3 extension
=================
*/
static void FS_CheckFilenameIsMutable( const char *filename,
const char *function )
{
// Check if the filename ends with the library, QVM, or pk3 extension
if( COM_CompareExtension( filename, DLL_EXT )
|| COM_CompareExtension( filename, ".qvm" )
|| COM_CompareExtension( filename, ".pk3" ) )
{
Com_Error( ERR_FATAL, "%s: Not allowed to manipulate '%s' due "
"to %s extension", function, filename, COM_GetExtension( filename ) );
}
}
/*
===========
FS_Remove
===========
*/
void FS_Remove( const char *osPath ) {
FS_CheckFilenameIsMutable( osPath, __func__ );
remove( osPath );
}
/*
===========
FS_HomeRemove
===========
*/
void FS_HomeRemove( const char *homePath ) {
FS_CheckFilenameIsMutable( homePath, __func__ );
remove( FS_BuildOSPath( fs_homepath->string,
fs_gamedir, homePath ) );
}
/*
================
FS_FileInPathExists
Tests if path and file exists
================
*/
qboolean FS_FileInPathExists(const char *testpath)
{
FILE *filep;
filep = Sys_FOpen(testpath, "rb");
if(filep)
{
fclose(filep);
return qtrue;
}
return qfalse;
}
/*
================
FS_FileExists
Tests if the file exists in the current gamedir, this DOES NOT
search the paths. This is to determine if opening a file to write
(which always goes into the current gamedir) will cause any overwrites.
NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards
================
*/
qboolean FS_FileExists(const char *file)
{
return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file));
}
/*
================
FS_SV_FileExists
Tests if the file exists
================
*/
qboolean FS_SV_FileExists( const char *file )
{
char *testpath;
testpath = FS_BuildOSPath( fs_homepath->string, file, "");
testpath[strlen(testpath)-1] = '\0';
return FS_FileInPathExists(testpath);
}
/*
===========
FS_SV_FOpenFileWrite
===========
*/
fileHandle_t FS_SV_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileWrite: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_SV_FOpenFileRead
Search for a file somewhere below the home path then base path
in that order
===========
*/
long FS_SV_FOpenFileRead(const char *filename, fileHandle_t *fp)
{
char *ospath;
fileHandle_t f = 0;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
S_ClearSoundBuffer();
// search homepath
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
// remove trailing slash
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o)
{
// If fs_homepath == fs_basepath, don't bother
if (Q_stricmp(fs_homepath->string,fs_basepath->string))
{
// search basepath
ospath = FS_BuildOSPath( fs_basepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
// Check fs_steampath too
if (!fsh[f].handleFiles.file.o && fs_steampath->string[0])
{
ospath = FS_BuildOSPath( fs_steampath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_steampath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
if ( !fsh[f].handleFiles.file.o )
{
f = 0;
}
}
*fp = f;
if (f) {
return FS_filelength(f);
}
return -1;
}
/*
===========
FS_SV_Rename
===========
*/
void FS_SV_Rename( const char *from, const char *to, qboolean safe ) {
char *from_ospath, *to_ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
// don't let sound stutter
S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, from, "" );
to_ospath = FS_BuildOSPath( fs_homepath->string, to, "" );
from_ospath[strlen(from_ospath)-1] = '\0';
to_ospath[strlen(to_ospath)-1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath );
}
if ( safe ) {
FS_CheckFilenameIsMutable( to_ospath, __func__ );
}
rename(from_ospath, to_ospath);
}
/*
===========
FS_Rename
===========
*/
void FS_Rename( const char *from, const char *to ) {
char *from_ospath, *to_ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
// don't let sound stutter
S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from );
to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to );
if ( fs_debug->integer ) {
Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath );
}
FS_CheckFilenameIsMutable( to_ospath, __func__ );
rename(from_ospath, to_ospath);
}
/*
==============
FS_FCloseFile
If the FILE pointer is an open pak file, leave it open.
For some reason, other dll's can't just cal fclose()
on files returned by FS_FOpenFile...
==============
*/
void FS_FCloseFile( fileHandle_t f ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if (fsh[f].zipFile == qtrue) {
unzCloseCurrentFile( fsh[f].handleFiles.file.z );
if ( fsh[f].handleFiles.unique ) {
unzClose( fsh[f].handleFiles.file.z );
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
return;
}
// we didn't find it as a pak, so close it as a unique file
if (fsh[f].handleFiles.file.o) {
fclose (fsh[f].handleFiles.file.o);
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
}
/*
===========
FS_FOpenFileWrite
===========
*/
fileHandle_t FS_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileWrite: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
// enabling the following line causes a recursive function call loop
// when running with +set logfile 1 +set developer 1
//Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_FOpenFileAppend
===========
*/
fileHandle_t FS_FOpenFileAppend( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileAppend: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "ab" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_FCreateOpenPipeFile
===========
*/
fileHandle_t FS_FCreateOpenPipeFile( const char *filename ) {
char *ospath;
FILE *fifo;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FCreateOpenPipeFile: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
fifo = Sys_Mkfifo( ospath );
if( fifo ) {
fsh[f].handleFiles.file.o = fifo;
fsh[f].handleSync = qfalse;
}
else
{
Com_Printf( S_COLOR_YELLOW "WARNING: Could not create new com_pipefile at %s. "
"com_pipefile will not be used.\n", ospath );
f = 0;
}
return f;
}
/*
===========
FS_FilenameCompare
Ignore case and seprator char distinctions
===========
*/
qboolean FS_FilenameCompare( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if (c1 >= 'a' && c1 <= 'z') {
c1 -= ('a' - 'A');
}
if (c2 >= 'a' && c2 <= 'z') {
c2 -= ('a' - 'A');
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if (c1 != c2) {
return qtrue; // strings not equal
}
} while (c1);
return qfalse; // strings are equal
}
/*
===========
FS_IsExt
Return qtrue if ext matches file extension filename
===========
*/
qboolean FS_IsExt(const char *filename, const char *ext, int namelen)
{
int extlen;
extlen = strlen(ext);
if(extlen > namelen)
return qfalse;
filename += namelen - extlen;
return !Q_stricmp(filename, ext);
}
/*
===========
FS_IsDemoExt
Return qtrue if filename has a demo extension
===========
*/
qboolean FS_IsDemoExt(const char *filename, int namelen)
{
char *ext_test;
int index, protocol;
ext_test = strrchr(filename, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMOEXT, ARRAY_LEN(DEMOEXT) - 1))
{
protocol = atoi(ext_test + ARRAY_LEN(DEMOEXT));
if(protocol == com_protocol->integer)
return qtrue;
#ifdef LEGACY_PROTOCOL
if(protocol == com_legacyprotocol->integer)
return qtrue;
#endif
for(index = 0; demo_protocols[index]; index++)
{
if(demo_protocols[index] == protocol)
return qtrue;
}
}
return qfalse;
}
/*
===========
FS_FOpenFileReadDir
Tries opening file "filename" in searchpath "search"
Returns filesize and an open FILE pointer.
===========
*/
extern qboolean com_fullyInitialized;
long FS_FOpenFileReadDir(const char *filename, searchpath_t *search, fileHandle_t *file, qboolean uniqueFILE, qboolean unpure)
{
long hash;
pack_t *pak;
fileInPack_t *pakFile;
directory_t *dir;
char *netpath;
FILE *filep;
int len;
if(filename == NULL)
Com_Error(ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed");
// qpaths are not supposed to have a leading slash
if(filename[0] == '/' || filename[0] == '\\')
filename++;
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if(strstr(filename, ".." ) || strstr(filename, "::"))
{
if(file == NULL)
return qfalse;
*file = 0;
return -1;
}
// make sure the q3key file is only readable by the quake3.exe at initialization
// any other time the key should only be accessed in memory using the provided functions
if(com_fullyInitialized && strstr(filename, "q3key"))
{
if(file == NULL)
return qfalse;
*file = 0;
return -1;
}
if(file == NULL)
{
// just wants to see if file is there
// is the element a pak file?
if(search->pack)
{
hash = FS_HashFileName(filename, search->pack->hashSize);
if(search->pack->hashTable[hash])
{
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do
{
// case and separator insensitive comparisons
if(!FS_FilenameCompare(pakFile->name, filename))
{
// found it!
if(pakFile->len)
return pakFile->len;
else
{
// It's not nice, but legacy code depends
// on positive value if file exists no matter
// what size
return 1;
}
}
pakFile = pakFile->next;
} while(pakFile != NULL);
}
}
else if(search->dir)
{
dir = search->dir;
netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
filep = Sys_FOpen(netpath, "rb");
if(filep)
{
len = FS_fplength(filep);
fclose(filep);
if(len)
return len;
else
return 1;
}
}
return 0;
}
*file = FS_HandleForFile();
fsh[*file].handleFiles.unique = uniqueFILE;
// is the element a pak file?
if(search->pack)
{
hash = FS_HashFileName(filename, search->pack->hashSize);
if(search->pack->hashTable[hash])
{
// disregard if it doesn't match one of the allowed pure pak files
if(!unpure && !FS_PakIsPure(search->pack))
{
*file = 0;
return -1;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do
{
// case and separator insensitive comparisons
if(!FS_FilenameCompare(pakFile->name, filename))
{
// found it!
// mark the pak as having been referenced and mark specifics on cgame and ui
// shaders, txt, arena files by themselves do not count as a reference as
// these are loaded from all pk3s
// from every pk3 file..
len = strlen(filename);
if (!(pak->referenced & FS_GENERAL_REF))
{
if(!FS_IsExt(filename, ".shader", len) &&
!FS_IsExt(filename, ".txt", len) &&
!FS_IsExt(filename, ".cfg", len) &&
!FS_IsExt(filename, ".config", len) &&
!FS_IsExt(filename, ".bot", len) &&
!FS_IsExt(filename, ".arena", len) &&
!FS_IsExt(filename, ".menu", len) &&
Q_stricmp(filename, "vm/qagame.qvm") != 0 &&
!strstr(filename, "levelshots"))
{
pak->referenced |= FS_GENERAL_REF;
}
}
if(strstr(filename, "cgame.qvm"))
pak->referenced |= FS_CGAME_REF;
if(strstr(filename, "ui.qvm"))
pak->referenced |= FS_UI_REF;
if(uniqueFILE)
{
// open a new file on the pakfile
fsh[*file].handleFiles.file.z = unzOpen(pak->pakFilename);
if(fsh[*file].handleFiles.file.z == NULL)
Com_Error(ERR_FATAL, "Couldn't open %s", pak->pakFilename);
}
else
fsh[*file].handleFiles.file.z = pak->handle;
Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
fsh[*file].zipFile = qtrue;
// set the file position in the zip file (also sets the current file info)
unzSetOffset(fsh[*file].handleFiles.file.z, pakFile->pos);
// open the file in the zip
unzOpenCurrentFile(fsh[*file].handleFiles.file.z);
fsh[*file].zipFilePos = pakFile->pos;
fsh[*file].zipFileLen = pakFile->len;
if(fs_debug->integer)
{
Com_Printf("FS_FOpenFileRead: %s (found in '%s')\n",
filename, pak->pakFilename);
}
return pakFile->len;
}
pakFile = pakFile->next;
} while(pakFile != NULL);
}
}
else if(search->dir)
{
// check a file in the directory tree
// if we are running restricted, the only files we
// will allow to come from the directory are .cfg files
len = strlen(filename);
// FIXME TTimo I'm not sure about the fs_numServerPaks test
// if you are using FS_ReadFile to find out if a file exists,
// this test can make the search fail although the file is in the directory
// I had the problem on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8
// turned out I used FS_FileExists instead
if(!unpure && fs_numServerPaks)
{
if(!FS_IsExt(filename, ".cfg", len) && // for config files
!FS_IsExt(filename, ".menu", len) && // menu files
!FS_IsExt(filename, ".game", len) && // menu files
!FS_IsExt(filename, ".dat", len) && // for journal files
!FS_IsDemoExt(filename, len)) // demos
{
*file = 0;
return -1;
}
}
dir = search->dir;
netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
filep = Sys_FOpen(netpath, "rb");
if (filep == NULL)
{
*file = 0;
return -1;
}
Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
fsh[*file].zipFile = qfalse;
if(fs_debug->integer)
{
Com_Printf("FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename,
dir->path, PATH_SEP, dir->gamedir);
}
fsh[*file].handleFiles.file.o = filep;
return FS_fplength(filep);
}
*file = 0;
return -1;
}
/*
===========
FS_FOpenFileRead
Finds the file in the search path.
Returns filesize and an open FILE pointer.
Used for streaming data out of either a
separate file or a ZIP file.
===========
*/
long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE)
{
searchpath_t *search;
long len;
qboolean isLocalConfig;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
isLocalConfig = !strcmp(filename, "autoexec.cfg") || !strcmp(filename, Q3CONFIG_CFG);
for(search = fs_searchpaths; search; search = search->next)
{
// autoexec.cfg and q3config.cfg can only be loaded outside of pk3 files.
if (isLocalConfig && search->pack)
continue;
len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse);
if(file == NULL)
{
if(len > 0)
return len;
}
else
{
if(len >= 0 && *file)
return len;
}
}
#ifdef FS_MISSING
if(missingFiles)
fprintf(missingFiles, "%s\n", filename);
#endif
if(file)
{
*file = 0;
return -1;
}
else
{
// When file is NULL, we're querying the existance of the file
// If we've got here, it doesn't exist
return 0;
}
}
/*
=================
FS_FindVM
Find a suitable VM file in search path order.
In each searchpath try:
- open DLL file if DLL loading enabled
- open QVM file
Enable search for DLL by setting enableDll to FSVM_ENABLEDLL
write found DLL or QVM to "found" and return VMI_NATIVE if DLL, VMI_COMPILED if QVM
Return the searchpath in "startSearch".
=================
*/
int FS_FindVM(void **startSearch, char *found, int foundlen, const char *name, int enableDll)
{
searchpath_t *search, *lastSearch;
directory_t *dir;
pack_t *pack;
char dllName[MAX_OSPATH], qvmName[MAX_OSPATH];
char *netpath;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
if(enableDll)
Com_sprintf(dllName, sizeof(dllName), "%s" ARCH_STRING DLL_EXT, name);
Com_sprintf(qvmName, sizeof(qvmName), "vm/%s.qvm", name);
lastSearch = *startSearch;
if(*startSearch == NULL)
search = fs_searchpaths;
else
search = lastSearch->next;
while(search)
{
if(search->dir && !fs_numServerPaks)
{
dir = search->dir;
if(enableDll)
{
netpath = FS_BuildOSPath(dir->path, dir->gamedir, dllName);
if(FS_FileInPathExists(netpath))
{
Q_strncpyz(found, netpath, foundlen);
*startSearch = search;
return VMI_NATIVE;
}
}
if(FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, qfalse) > 0)
{
*startSearch = search;
return VMI_COMPILED;
}
}
else if(search->pack)
{
pack = search->pack;
if(lastSearch && lastSearch->pack)
{
// make sure we only try loading one VM file per game dir
// i.e. if VM from pak7.pk3 fails we won't try one from pak6.pk3
if(!FS_FilenameCompare(lastSearch->pack->pakPathname, pack->pakPathname))
{
search = search->next;
continue;
}
}
if(FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, qfalse) > 0)
{
*startSearch = search;
return VMI_COMPILED;
}
}
search = search->next;
}
return -1;
}
/*
=================
FS_Read
Properly handles partial reads
=================
*/
int FS_Read2( void *buffer, int len, fileHandle_t f ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !f ) {
return 0;
}
if (fsh[f].streamed) {
int r;
fsh[f].streamed = qfalse;
r = FS_Read( buffer, len, f );
fsh[f].streamed = qtrue;
return r;
} else {
return FS_Read( buffer, len, f);
}
}
int FS_Read( void *buffer, int len, fileHandle_t f ) {
int block, remaining;
int read;
byte *buf;
int tries;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !f ) {
return 0;
}
buf = (byte *)buffer;
fs_readCount += len;
if (fsh[f].zipFile == qfalse) {
remaining = len;
tries = 0;
while (remaining) {
block = remaining;
read = fread (buf, 1, block, fsh[f].handleFiles.file.o);
if (read == 0) {
// we might have been trying to read from a CD, which
// sometimes returns a 0 read on windows
if (!tries) {
tries = 1;
} else {
return len-remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read");
}
}
if (read == -1) {
Com_Error (ERR_FATAL, "FS_Read: -1 bytes read");
}
remaining -= read;
buf += read;
}
return len;
} else {
return unzReadCurrentFile(fsh[f].handleFiles.file.z, buffer, len);
}
}
/*
=================
FS_Write
Properly handles partial writes
=================
*/
int FS_Write( const void *buffer, int len, fileHandle_t h ) {
int block, remaining;
int written;
byte *buf;
int tries;
FILE *f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !h ) {
return 0;
}
f = FS_FileForHandle(h);
buf = (byte *)buffer;
remaining = len;
tries = 0;
while (remaining) {
block = remaining;
written = fwrite (buf, 1, block, f);
if (written == 0) {
if (!tries) {
tries = 1;
} else {
Com_Printf( "FS_Write: 0 bytes written\n" );
return 0;
}
}
if (written == -1) {
Com_Printf( "FS_Write: -1 bytes written\n" );
return 0;
}
remaining -= written;
buf += written;
}
if ( fsh[h].handleSync ) {
fflush( f );
}
return len;
}
void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start (argptr,fmt);
Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
va_end (argptr);
FS_Write(msg, strlen(msg), h);
}
#define PK3_SEEK_BUFFER_SIZE 65536
/*
=================
FS_Seek
=================
*/
int FS_Seek( fileHandle_t f, long offset, int origin ) {
int _origin;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
return -1;
}
if (fsh[f].streamed) {
int r;
fsh[f].streamed = qfalse;
r = FS_Seek( f, offset, origin );
fsh[f].streamed = qtrue;
return r;
}
if (fsh[f].zipFile == qtrue) {
//FIXME: this is really, really crappy
//(but better than what was here before)
byte buffer[PK3_SEEK_BUFFER_SIZE];
int remainder;
int currentPosition = FS_FTell( f );
// change negative offsets into FS_SEEK_SET
if ( offset < 0 ) {
switch( origin ) {
case FS_SEEK_END:
remainder = fsh[f].zipFileLen + offset;
break;
case FS_SEEK_CUR:
remainder = currentPosition + offset;
break;
case FS_SEEK_SET:
default:
remainder = 0;
break;
}
if ( remainder < 0 ) {
remainder = 0;
}
origin = FS_SEEK_SET;
} else {
if ( origin == FS_SEEK_END ) {
remainder = fsh[f].zipFileLen - currentPosition + offset;
} else {
remainder = offset;
}
}
switch( origin ) {
case FS_SEEK_SET:
if ( remainder == currentPosition ) {
return offset;
}
unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
unzOpenCurrentFile(fsh[f].handleFiles.file.z);
//fallthrough
case FS_SEEK_END:
case FS_SEEK_CUR:
while( remainder > PK3_SEEK_BUFFER_SIZE ) {
FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f );
remainder -= PK3_SEEK_BUFFER_SIZE;
}
FS_Read( buffer, remainder, f );
return offset;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
return -1;
}
} else {
FILE *file;
file = FS_FileForHandle(f);
switch( origin ) {
case FS_SEEK_CUR:
_origin = SEEK_CUR;
break;
case FS_SEEK_END:
_origin = SEEK_END;
break;
case FS_SEEK_SET:
_origin = SEEK_SET;
break;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
break;
}
return fseek( file, offset, _origin );
}
}
/*
======================================================================================
CONVENIENCE FUNCTIONS FOR ENTIRE FILES
======================================================================================
*/
int FS_FileIsInPAK(const char *filename, int *pChecksum ) {
searchpath_t *search;
pack_t *pak;
fileInPack_t *pakFile;
long hash = 0;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !filename ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed" );
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
return -1;
}
//
// search through the path, one element at a time
//
for ( search = fs_searchpaths ; search ; search = search->next ) {
//
if (search->pack) {
hash = FS_HashFileName(filename, search->pack->hashSize);
}
// is the element a pak file?
if ( search->pack && search->pack->hashTable[hash] ) {
// disregard if it doesn't match one of the allowed pure pak files
if ( !FS_PakIsPure(search->pack) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
if (pChecksum) {
*pChecksum = pak->pure_checksum;
}
return 1;
}
pakFile = pakFile->next;
} while(pakFile != NULL);
}
}
return -1;
}
/*
============
FS_ReadFileDir
Filename are relative to the quake search path
a null buffer will just return the file length without loading
If searchPath is non-NULL search only in that specific search path
============
*/
long FS_ReadFileDir(const char *qpath, void *searchPath, qboolean unpure, void **buffer)
{
fileHandle_t h;
searchpath_t *search;
byte* buf;
qboolean isConfig;
long len;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !qpath || !qpath[0] ) {
Com_Error( ERR_FATAL, "FS_ReadFile with empty name" );
}
buf = NULL; // quiet compiler warning
// if this is a .cfg file and we are playing back a journal, read
// it from the journal file
if ( strstr( qpath, ".cfg" ) ) {
isConfig = qtrue;
if ( com_journal && com_journal->integer == 2 ) {
int r;
Com_DPrintf( "Loading %s from journal file.\n", qpath );
r = FS_Read( &len, sizeof( len ), com_journalDataFile );
if ( r != sizeof( len ) ) {
if (buffer != NULL) *buffer = NULL;
return -1;
}
// if the file didn't exist when the journal was created
if (!len) {
if (buffer == NULL) {
return 1; // hack for old journal files
}
*buffer = NULL;
return -1;
}
if (buffer == NULL) {
return len;
}
buf = Hunk_AllocateTempMemory(len+1);
*buffer = buf;
r = FS_Read( buf, len, com_journalDataFile );
if ( r != len ) {
Com_Error( ERR_FATAL, "Read from journalDataFile failed" );
}
fs_loadCount++;
fs_loadStack++;
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
return len;
}
} else {
isConfig = qfalse;
}
search = searchPath;
if(search == NULL)
{
// look for it in the filesystem or pack files
len = FS_FOpenFileRead(qpath, &h, qfalse);
}
else
{
// look for it in a specific search path only
len = FS_FOpenFileReadDir(qpath, search, &h, qfalse, unpure);
}
if ( h == 0 ) {
if ( buffer ) {
*buffer = NULL;
}
// if we are journalling and it is a config file, write a zero to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing zero for %s to journal file.\n", qpath );
len = 0;
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return -1;
}
if ( !buffer ) {
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing len for %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
FS_FCloseFile( h);
return len;
}
fs_loadCount++;
fs_loadStack++;
buf = Hunk_AllocateTempMemory(len+1);
*buffer = buf;
FS_Read (buf, len, h);
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
FS_FCloseFile( h );
// if we are journalling and it is a config file, write it to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Write( buf, len, com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return len;
}
/*
============
FS_ReadFile
Filename are relative to the quake search path
a null buffer will just return the file length without loading
============
*/
long FS_ReadFile(const char *qpath, void **buffer)
{
return FS_ReadFileDir(qpath, NULL, qfalse, buffer);
}
/*
=============
FS_FreeFile
=============
*/
void FS_FreeFile( void *buffer ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !buffer ) {
Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" );
}
fs_loadStack--;
Hunk_FreeTempMemory( buffer );
// if all of our temp files are free, clear all of our space
if ( fs_loadStack == 0 ) {
Hunk_ClearTempMemory();
}
}
/*
============
FS_WriteFile
Filename are relative to the quake search path
============
*/
void FS_WriteFile( const char *qpath, const void *buffer, int size ) {
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !qpath || !buffer ) {
Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" );
}
f = FS_FOpenFileWrite( qpath );
if ( !f ) {
Com_Printf( "Failed to open %s\n", qpath );
return;
}
FS_Write( buffer, size, f );
FS_FCloseFile( f );
}
/*
==========================================================================
ZIP FILE LOADING
==========================================================================
*/
/*
=================
FS_LoadZipFile
Creates a new pak_t in the search chain for the contents
of a zip file.
=================
*/
static pack_t *FS_LoadZipFile(const char *zipfile, const char *basename)
{
fileInPack_t *buildBuffer;
pack_t *pack;
unzFile uf;
int err;
unz_global_info gi;
char filename_inzip[MAX_ZPATH];
unz_file_info file_info;
int i, len;
long hash;
int fs_numHeaderLongs;
int *fs_headerLongs;
char *namePtr;
fs_numHeaderLongs = 0;
uf = unzOpen(zipfile);
err = unzGetGlobalInfo (uf,&gi);
if (err != UNZ_OK)
return NULL;
len = 0;
unzGoToFirstFile(uf);
for (i = 0; i < gi.number_entry; i++)
{
err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
if (err != UNZ_OK) {
break;
}
len += strlen(filename_inzip) + 1;
unzGoToNextFile(uf);
}
buildBuffer = Z_Malloc( (gi.number_entry * sizeof( fileInPack_t )) + len );
namePtr = ((char *) buildBuffer) + gi.number_entry * sizeof( fileInPack_t );
fs_headerLongs = Z_Malloc( ( gi.number_entry + 1 ) * sizeof(int) );
fs_headerLongs[ fs_numHeaderLongs++ ] = LittleLong( fs_checksumFeed );
// get the hash table size from the number of files in the zip
// because lots of custom pk3 files have less than 32 or 64 files
for (i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1) {
if (i > gi.number_entry) {
break;
}
}
pack = Z_Malloc( sizeof( pack_t ) + i * sizeof(fileInPack_t *) );
pack->hashSize = i;
pack->hashTable = (fileInPack_t **) (((char *) pack) + sizeof( pack_t ));
for(i = 0; i < pack->hashSize; i++) {
pack->hashTable[i] = NULL;
}
Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) );
Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) );
// strip .pk3 if needed
if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) {
pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0;
}
pack->handle = uf;
pack->numfiles = gi.number_entry;
unzGoToFirstFile(uf);
for (i = 0; i < gi.number_entry; i++)
{
err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
if (err != UNZ_OK) {
break;
}
if (file_info.uncompressed_size > 0) {
fs_headerLongs[fs_numHeaderLongs++] = LittleLong(file_info.crc);
}
Q_strlwr( filename_inzip );
hash = FS_HashFileName(filename_inzip, pack->hashSize);
buildBuffer[i].name = namePtr;
strcpy( buildBuffer[i].name, filename_inzip );
namePtr += strlen(filename_inzip) + 1;
// store the file position in the zip
buildBuffer[i].pos = unzGetOffset(uf);
buildBuffer[i].len = file_info.uncompressed_size;
buildBuffer[i].next = pack->hashTable[hash];
pack->hashTable[hash] = &buildBuffer[i];
unzGoToNextFile(uf);
}
pack->checksum = Com_BlockChecksum( &fs_headerLongs[ 1 ], sizeof(*fs_headerLongs) * ( fs_numHeaderLongs - 1 ) );
pack->pure_checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs );
pack->checksum = LittleLong( pack->checksum );
pack->pure_checksum = LittleLong( pack->pure_checksum );
Z_Free(fs_headerLongs);
pack->buildBuffer = buildBuffer;
return pack;
}
/*
=================
FS_FreePak
Frees a pak structure and releases all associated resources
=================
*/
static void FS_FreePak(pack_t *thepak)
{
unzClose(thepak->handle);
Z_Free(thepak->buildBuffer);
Z_Free(thepak);
}
/*
=================
FS_GetZipChecksum
Compares whether the given pak file matches a referenced checksum
=================
*/
qboolean FS_CompareZipChecksum(const char *zipfile)
{
pack_t *thepak;
int index, checksum;
thepak = FS_LoadZipFile(zipfile, "");
if(!thepak)
return qfalse;
checksum = thepak->checksum;
FS_FreePak(thepak);
for(index = 0; index < fs_numServerReferencedPaks; index++)
{
if(checksum == fs_serverReferencedPaks[index])
return qtrue;
}
return qfalse;
}
/*
=================================================================================
DIRECTORY SCANNING FUNCTIONS
=================================================================================
*/
#define MAX_FOUND_FILES 0x1000
static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) {
int len, at, newdep;
newdep = 0;
zpath[0] = 0;
len = 0;
at = 0;
while(zname[at] != 0)
{
if (zname[at]=='/' || zname[at]=='\\') {
len = at;
newdep++;
}
at++;
}
strcpy(zpath, zname);
zpath[len] = 0;
*depth = newdep;
return len;
}
/*
==================
FS_AddFileToList
==================
*/
static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) {
int i;
if ( nfiles == MAX_FOUND_FILES - 1 ) {
return nfiles;
}
for ( i = 0 ; i < nfiles ; i++ ) {
if ( !Q_stricmp( name, list[i] ) ) {
return nfiles; // allready in list
}
}
list[nfiles] = CopyString( name );
nfiles++;
return nfiles;
}
/*
===============
FS_ListFilteredFiles
Returns a uniqued list of files that match the given criteria
from all search paths
===============
*/
char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles, qboolean allowNonPureFilesOnDisk ) {
int nfiles;
char **listCopy;
char *list[MAX_FOUND_FILES];
searchpath_t *search;
int i;
int pathLength;
int extensionLength;
int length, pathDepth, temp;
pack_t *pak;
fileInPack_t *buildBuffer;
char zpath[MAX_ZPATH];
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !path ) {
*numfiles = 0;
return NULL;
}
if ( !extension ) {
extension = "";
}
pathLength = strlen( path );
if ( path[pathLength-1] == '\\' || path[pathLength-1] == '/' ) {
pathLength--;
}
extensionLength = strlen( extension );
nfiles = 0;
FS_ReturnPath(path, zpath, &pathDepth);
//
// search through the path, one element at a time, adding to list
//
for (search = fs_searchpaths ; search ; search = search->next) {
// is the element a pak file?
if (search->pack) {
//ZOID: If we are pure, don't search for files on paks that
// aren't on the pure list
if ( !FS_PakIsPure(search->pack) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
buildBuffer = pak->buildBuffer;
for (i = 0; i < pak->numfiles; i++) {
char *name;
int zpathLen, depth;
// check for directory match
name = buildBuffer[i].name;
//
if (filter) {
// case insensitive
if (!Com_FilterPath( filter, name, qfalse ))
continue;
// unique the match
nfiles = FS_AddFileToList( name, list, nfiles );
}
else {
zpathLen = FS_ReturnPath(name, zpath, &depth);
if ( (depth-pathDepth)>2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) {
continue;
}
// check for extension match
length = strlen( name );
if ( length < extensionLength ) {
continue;
}
if ( Q_stricmp( name + length - extensionLength, extension ) ) {
continue;
}
// unique the match
temp = pathLength;
if (pathLength) {
temp++; // include the '/'
}
nfiles = FS_AddFileToList( name + temp, list, nfiles );
}
}
} else if (search->dir) { // scan for files in the filesystem
char *netpath;
int numSysFiles;
char **sysFiles;
char *name;
// don't scan directories for files if we are pure or restricted
if ( fs_numServerPaks && !allowNonPureFilesOnDisk ) {
continue;
} else {
netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path );
sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse );
for ( i = 0 ; i < numSysFiles ; i++ ) {
// unique the match
name = sysFiles[i];
nfiles = FS_AddFileToList( name, list, nfiles );
}
Sys_FreeFileList( sysFiles );
}
}
}
// return a copy of the list
*numfiles = nfiles;
if ( !nfiles ) {
return NULL;
}
listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
for ( i = 0 ; i < nfiles ; i++ ) {
listCopy[i] = list[i];
}
listCopy[i] = NULL;
return listCopy;
}
/*
=================
FS_ListFiles
=================
*/
char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) {
return FS_ListFilteredFiles( path, extension, NULL, numfiles, qfalse );
}
/*
=================
FS_FreeFileList
=================
*/
void FS_FreeFileList( char **list ) {
int i;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !list ) {
return;
}
for ( i = 0 ; list[i] ; i++ ) {
Z_Free( list[i] );
}
Z_Free( list );
}
/*
================
FS_GetFileList
================
*/
int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
int nFiles, i, nTotal, nLen;
char **pFiles = NULL;
*listbuf = 0;
nFiles = 0;
nTotal = 0;
if (Q_stricmp(path, "$modlist") == 0) {
return FS_GetModList(listbuf, bufsize);
}
pFiles = FS_ListFiles(path, extension, &nFiles);
for (i =0; i < nFiles; i++) {
nLen = strlen(pFiles[i]) + 1;
if (nTotal + nLen + 1 < bufsize) {
strcpy(listbuf, pFiles[i]);
listbuf += nLen;
nTotal += nLen;
}
else {
nFiles = i;
break;
}
}
FS_FreeFileList(pFiles);
return nFiles;
}
/*
=======================
Sys_ConcatenateFileLists
mkv: Naive implementation. Concatenates three lists into a
new list, and frees the old lists from the heap.
bk001129 - from cvs1.17 (mkv)
FIXME TTimo those two should move to common.c next to Sys_ListFiles
=======================
*/
static unsigned int Sys_CountFileList(char **list)
{
int i = 0;
if (list)
{
while (*list)
{
list++;
i++;
}
}
return i;
}
static char** Sys_ConcatenateFileLists( char **list0, char **list1 )
{
int totalLength = 0;
char** cat = NULL, **dst, **src;
totalLength += Sys_CountFileList(list0);
totalLength += Sys_CountFileList(list1);
/* Create new list. */
dst = cat = Z_Malloc( ( totalLength + 1 ) * sizeof( char* ) );
/* Copy over lists. */
if (list0)
{
for (src = list0; *src; src++, dst++)
*dst = *src;
}
if (list1)
{
for (src = list1; *src; src++, dst++)
*dst = *src;
}
// Terminate the list
*dst = NULL;
// Free our old lists.
// NOTE: not freeing their content, it's been merged in dst and still being used
if (list0) Z_Free( list0 );
if (list1) Z_Free( list1 );
return cat;
}
/*
================
FS_GetModDescription
================
*/
void FS_GetModDescription( const char *modDir, char *description, int descriptionLen ) {
fileHandle_t descHandle;
char descPath[MAX_QPATH];
int nDescLen;
FILE *file;
Com_sprintf( descPath, sizeof ( descPath ), "%s/description.txt", modDir );
nDescLen = FS_SV_FOpenFileRead( descPath, &descHandle );
if ( nDescLen > 0 && descHandle ) {
file = FS_FileForHandle(descHandle);
Com_Memset( description, 0, descriptionLen );
nDescLen = fread(description, 1, descriptionLen, file);
if (nDescLen >= 0) {
description[nDescLen] = '\0';
}
FS_FCloseFile(descHandle);
} else {
Q_strncpyz( description, modDir, descriptionLen );
}
}
/*
================
FS_GetModList
Returns a list of mod directory names
A mod directory is a peer to baseq3 with a pk3 in it
The directories are searched in base path, cd path and home path
================
*/
int FS_GetModList( char *listbuf, int bufsize ) {
int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen;
char **pFiles = NULL;
char **pPaks = NULL;
char *name, *path;
char description[MAX_OSPATH];
int dummy;
char **pFiles0 = NULL;
char **pFiles1 = NULL;
char **pFiles2 = NULL;
char **pFiles3 = NULL;
qboolean bDrop = qfalse;
*listbuf = 0;
nMods = nTotal = 0;
pFiles0 = Sys_ListFiles( fs_homepath->string, NULL, NULL, &dummy, qtrue );
pFiles1 = Sys_ListFiles( fs_basepath->string, NULL, NULL, &dummy, qtrue );
pFiles2 = Sys_ListFiles( fs_steampath->string, NULL, NULL, &dummy, qtrue );
// we searched for mods in the three paths
// it is likely that we have duplicate names now, which we will cleanup below
pFiles3 = Sys_ConcatenateFileLists( pFiles0, pFiles1 );
pFiles = Sys_ConcatenateFileLists( pFiles2, pFiles3 );
nPotential = Sys_CountFileList(pFiles);
for ( i = 0 ; i < nPotential ; i++ ) {
name = pFiles[i];
// NOTE: cleaner would involve more changes
// ignore duplicate mod directories
if (i!=0) {
bDrop = qfalse;
for(j=0; j<i; j++)
{
if (Q_stricmp(pFiles[j],name)==0) {
// this one can be dropped
bDrop = qtrue;
break;
}
}
}
if (bDrop) {
continue;
}
// we drop "baseq3" "." and ".."
if (Q_stricmp(name, com_basegame->string) && Q_stricmpn(name, ".", 1)) {
// now we need to find some .pk3 files to validate the mod
// NOTE TTimo: (actually I'm not sure why .. what if it's a mod under developement with no .pk3?)
// we didn't keep the information when we merged the directory names, as to what OS Path it was found under
// so it could be in base path, cd path or home path
// we will try each three of them here (yes, it's a bit messy)
path = FS_BuildOSPath( fs_basepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse);
Sys_FreeFileList( pPaks ); // we only use Sys_ListFiles to check wether .pk3 files are present
/* try on home path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_homepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
/* try on steam path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_steampath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
if (nPaks > 0) {
nLen = strlen(name) + 1;
// nLen is the length of the mod path
// we need to see if there is a description available
FS_GetModDescription( name, description, sizeof( description ) );
nDescLen = strlen(description) + 1;
if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) {
strcpy(listbuf, name);
listbuf += nLen;
strcpy(listbuf, description);
listbuf += nDescLen;
nTotal += nLen + nDescLen;
nMods++;
}
else {
break;
}
}
}
}
Sys_FreeFileList( pFiles );
return nMods;
}
//============================================================================
/*
================
FS_Dir_f
================
*/
void FS_Dir_f( void ) {
char *path;
char *extension;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) {
Com_Printf( "usage: dir <directory> [extension]\n" );
return;
}
if ( Cmd_Argc() == 2 ) {
path = Cmd_Argv( 1 );
extension = "";
} else {
path = Cmd_Argv( 1 );
extension = Cmd_Argv( 2 );
}
Com_Printf( "Directory of %s %s\n", path, extension );
Com_Printf( "---------------\n" );
dirnames = FS_ListFiles( path, extension, &ndirs );
for ( i = 0; i < ndirs; i++ ) {
Com_Printf( "%s\n", dirnames[i] );
}
FS_FreeFileList( dirnames );
}
/*
===========
FS_ConvertPath
===========
*/
void FS_ConvertPath( char *s ) {
while (*s) {
if ( *s == '\\' || *s == ':' ) {
*s = '/';
}
s++;
}
}
/*
===========
FS_PathCmp
Ignore case and seprator char distinctions
===========
*/
int FS_PathCmp( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if (c1 >= 'a' && c1 <= 'z') {
c1 -= ('a' - 'A');
}
if (c2 >= 'a' && c2 <= 'z') {
c2 -= ('a' - 'A');
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if (c1 < c2) {
return -1; // strings not equal
}
if (c1 > c2) {
return 1;
}
} while (c1);
return 0; // strings are equal
}
/*
================
FS_SortFileList
================
*/
void FS_SortFileList(char **filelist, int numfiles) {
int i, j, k, numsortedfiles;
char **sortedlist;
sortedlist = Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ) );
sortedlist[0] = NULL;
numsortedfiles = 0;
for (i = 0; i < numfiles; i++) {
for (j = 0; j < numsortedfiles; j++) {
if (FS_PathCmp(filelist[i], sortedlist[j]) < 0) {
break;
}
}
for (k = numsortedfiles; k > j; k--) {
sortedlist[k] = sortedlist[k-1];
}
sortedlist[j] = filelist[i];
numsortedfiles++;
}
Com_Memcpy(filelist, sortedlist, numfiles * sizeof( *filelist ) );
Z_Free(sortedlist);
}
/*
================
FS_NewDir_f
================
*/
void FS_NewDir_f( void ) {
char *filter;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 ) {
Com_Printf( "usage: fdir <filter>\n" );
Com_Printf( "example: fdir *q3dm*.bsp\n");
return;
}
filter = Cmd_Argv( 1 );
Com_Printf( "---------------\n" );
dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs, qfalse );
FS_SortFileList(dirnames, ndirs);
for ( i = 0; i < ndirs; i++ ) {
FS_ConvertPath(dirnames[i]);
Com_Printf( "%s\n", dirnames[i] );
}
Com_Printf( "%d files listed\n", ndirs );
FS_FreeFileList( dirnames );
}
/*
============
FS_Path_f
============
*/
void FS_Path_f( void ) {
searchpath_t *s;
int i;
Com_Printf ("We are looking in the current search path:\n");
for (s = fs_searchpaths; s; s = s->next) {
if (s->pack) {
Com_Printf ("%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles);
if ( fs_numServerPaks ) {
if ( !FS_PakIsPure(s->pack) ) {
Com_Printf( " not on the pure list\n" );
} else {
Com_Printf( " on the pure list\n" );
}
}
} else {
Com_Printf ("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir );
}
}
Com_Printf( "\n" );
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o ) {
Com_Printf( "handle %i: %s\n", i, fsh[i].name );
}
}
}
/*
============
FS_TouchFile_f
============
*/
void FS_TouchFile_f( void ) {
fileHandle_t f;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: touchFile <file>\n" );
return;
}
FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse );
if ( f ) {
FS_FCloseFile( f );
}
}
/*
============
FS_Which
============
*/
qboolean FS_Which(const char *filename, void *searchPath)
{
searchpath_t *search = searchPath;
if(FS_FOpenFileReadDir(filename, search, NULL, qfalse, qfalse) > 0)
{
if(search->pack)
{
Com_Printf("File \"%s\" found in \"%s\"\n", filename, search->pack->pakFilename);
return qtrue;
}
else if(search->dir)
{
Com_Printf( "File \"%s\" found at \"%s\"\n", filename, search->dir->fullpath);
return qtrue;
}
}
return qfalse;
}
/*
============
FS_Which_f
============
*/
void FS_Which_f( void ) {
searchpath_t *search;
char *filename;
filename = Cmd_Argv(1);
if ( !filename[0] ) {
Com_Printf( "Usage: which <file>\n" );
return;
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// just wants to see if file is there
for(search = fs_searchpaths; search; search = search->next)
{
if(FS_Which(filename, search))
return;
}
Com_Printf("File not found: \"%s\"\n", filename);
}
//===========================================================================
static int QDECL paksort( const void *a, const void *b ) {
char *aa, *bb;
aa = *(char **)a;
bb = *(char **)b;
return FS_PathCmp( aa, bb );
}
/*
================
FS_AddGameDirectory
Sets fs_gamedir, adds the directory to the head of the path,
then loads the zip headers
================
*/
void FS_AddGameDirectory( const char *path, const char *dir ) {
searchpath_t *sp;
searchpath_t *search;
pack_t *pak;
char curpath[MAX_OSPATH + 1], *pakfile;
int numfiles;
char **pakfiles;
int pakfilesi;
char **pakfilestmp;
int numdirs;
char **pakdirs;
int pakdirsi;
char **pakdirstmp;
int pakwhich;
int len;
// Unique
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->dir && !Q_stricmp(sp->dir->path, path) && !Q_stricmp(sp->dir->gamedir, dir)) {
return; // we've already got this one
}
}
Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) );
// find all pak files in this directory
Q_strncpyz(curpath, FS_BuildOSPath(path, dir, ""), sizeof(curpath));
curpath[strlen(curpath) - 1] = '\0'; // strip the trailing slash
// Get .pk3 files
pakfiles = Sys_ListFiles(curpath, ".pk3", NULL, &numfiles, qfalse);
qsort( pakfiles, numfiles, sizeof(char*), paksort );
if ( fs_numServerPaks ) {
numdirs = 0;
pakdirs = NULL;
} else {
// Get top level directories (we'll filter them later since the Sys_ListFiles filtering is terrible)
pakdirs = Sys_ListFiles(curpath, "/", NULL, &numdirs, qfalse);
qsort( pakdirs, numdirs, sizeof(char *), paksort );
}
pakfilesi = 0;
pakdirsi = 0;
while((pakfilesi < numfiles) || (pakdirsi < numdirs))
{
// Check if a pakfile or pakdir comes next
if (pakfilesi >= numfiles) {
// We've used all the pakfiles, it must be a pakdir.
pakwhich = 0;
}
else if (pakdirsi >= numdirs) {
// We've used all the pakdirs, it must be a pakfile.
pakwhich = 1;
}
else {
// Could be either, compare to see which name comes first
// Need tmp variables for appropriate indirection for paksort()
pakfilestmp = &pakfiles[pakfilesi];
pakdirstmp = &pakdirs[pakdirsi];
pakwhich = (paksort(pakfilestmp, pakdirstmp) < 0);
}
if (pakwhich) {
// The next .pk3 file is before the next .pk3dir
pakfile = FS_BuildOSPath(path, dir, pakfiles[pakfilesi]);
if ((pak = FS_LoadZipFile(pakfile, pakfiles[pakfilesi])) == 0) {
// This isn't a .pk3! Next!
pakfilesi++;
continue;
}
Q_strncpyz(pak->pakPathname, curpath, sizeof(pak->pakPathname));
// store the game name for downloading
Q_strncpyz(pak->pakGamename, dir, sizeof(pak->pakGamename));
fs_packFiles += pak->numfiles;
search = Z_Malloc(sizeof(searchpath_t));
search->pack = pak;
search->next = fs_searchpaths;
fs_searchpaths = search;
pakfilesi++;
}
else {
// The next .pk3dir is before the next .pk3 file
// But wait, this could be any directory, we're filtering to only ending with ".pk3dir" here.
len = strlen(pakdirs[pakdirsi]);
if (!FS_IsExt(pakdirs[pakdirsi], ".pk3dir", len)) {
// This isn't a .pk3dir! Next!
pakdirsi++;
continue;
}
pakfile = FS_BuildOSPath(path, dir, pakdirs[pakdirsi]);
// add the directory to the search path
search = Z_Malloc(sizeof(searchpath_t));
search->dir = Z_Malloc(sizeof(*search->dir));
Q_strncpyz(search->dir->path, curpath, sizeof(search->dir->path)); // c:\quake3\baseq3
Q_strncpyz(search->dir->fullpath, pakfile, sizeof(search->dir->fullpath)); // c:\quake3\baseq3\mypak.pk3dir
Q_strncpyz(search->dir->gamedir, pakdirs[pakdirsi], sizeof(search->dir->gamedir)); // mypak.pk3dir
search->next = fs_searchpaths;
fs_searchpaths = search;
pakdirsi++;
}
}
// done
Sys_FreeFileList( pakfiles );
Sys_FreeFileList( pakdirs );
//
// add the directory to the search path
//
search = Z_Malloc (sizeof(searchpath_t));
search->dir = Z_Malloc( sizeof( *search->dir ) );
Q_strncpyz(search->dir->path, path, sizeof(search->dir->path));
Q_strncpyz(search->dir->fullpath, curpath, sizeof(search->dir->fullpath));
Q_strncpyz(search->dir->gamedir, dir, sizeof(search->dir->gamedir));
search->next = fs_searchpaths;
fs_searchpaths = search;
}
/*
================
FS_idPak
================
*/
qboolean FS_idPak(char *pak, char *base, int numPaks)
{
int i;
for (i = 0; i < NUM_ID_PAKS; i++) {
if ( !FS_FilenameCompare(pak, va("%s/pak%d", base, i)) ) {
break;
}
}
if (i < numPaks) {
return qtrue;
}
return qfalse;
}
/*
================
FS_CheckDirTraversal
Check whether the string contains stuff like "../" to prevent directory traversal bugs
and return qtrue if it does.
================
*/
qboolean FS_CheckDirTraversal(const char *checkdir)
{
if(strstr(checkdir, "../") || strstr(checkdir, "..\\"))
return qtrue;
return qfalse;
}
/*
================
FS_ComparePaks
----------------
dlstring == qtrue
Returns a list of pak files that we should download from the server. They all get stored
in the current gamedir and an FS_Restart will be fired up after we download them all.
The string is the format:
@remotename@localname [repeat]
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS];
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS];
----------------
dlstring == qfalse
we are not interested in a download string format, we want something human-readable
(this is used for diagnostics while connecting to a pure server)
================
*/
qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring ) {
searchpath_t *sp;
qboolean havepak;
char *origpos = neededpaks;
int i;
if (!fs_numServerReferencedPaks)
return qfalse; // Server didn't send any pack information along
*neededpaks = 0;
for ( i = 0 ; i < fs_numServerReferencedPaks ; i++ )
{
// Ok, see if we have this pak file
havepak = qfalse;
// never autodownload any of the id paks
if(FS_idPak(fs_serverReferencedPakNames[i], BASEGAME, NUM_ID_PAKS)
#ifndef STANDALONE
|| FS_idPak(fs_serverReferencedPakNames[i], BASETA, NUM_TA_PAKS)
#endif
)
{
continue;
}
// Make sure the server cannot make us write to non-quake3 directories.
if(FS_CheckDirTraversal(fs_serverReferencedPakNames[i]))
{
Com_Printf("WARNING: Invalid download name %s\n", fs_serverReferencedPakNames[i]);
continue;
}
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i] ) {
havepak = qtrue; // This is it!
break;
}
}
if ( !havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i] ) {
// Don't got it
if (dlstring)
{
// We need this to make sure we won't hit the end of the buffer or the server could
// overwrite non-pk3 files on clients by writing so much crap into neededpaks that
// Q_strcat cuts off the .pk3 extension.
origpos += strlen(origpos);
// Remote name
Q_strcat( neededpaks, len, "@");
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Local name
Q_strcat( neededpaks, len, "@");
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
{
char st[MAX_ZPATH];
// We already have one called this, we need to download it to another name
// Make something up with the checksum in it
Com_sprintf( st, sizeof( st ), "%s.%08x.pk3", fs_serverReferencedPakNames[i], fs_serverReferencedPaks[i] );
Q_strcat( neededpaks, len, st );
}
else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
}
// Find out whether it might have overflowed the buffer and don't add this file to the
// list if that is the case.
if(strlen(origpos) + (origpos - neededpaks) >= len - 1)
{
*origpos = '\0';
break;
}
}
else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
{
Q_strcat( neededpaks, len, " (local file exists with wrong checksum)");
}
Q_strcat( neededpaks, len, "\n");
}
}
}
if ( *neededpaks ) {
return qtrue;
}
return qfalse; // We have them all
}
/*
================
FS_Shutdown
Frees all resources.
================
*/
void FS_Shutdown( qboolean closemfp ) {
searchpath_t *p, *next;
int i;
for(i = 0; i < MAX_FILE_HANDLES; i++) {
if (fsh[i].fileSize) {
FS_FCloseFile(i);
}
}
// free everything
for(p = fs_searchpaths; p; p = next)
{
next = p->next;
if(p->pack)
FS_FreePak(p->pack);
if (p->dir)
Z_Free(p->dir);
Z_Free(p);
}
// any FS_ calls will now be an error until reinitialized
fs_searchpaths = NULL;
Cmd_RemoveCommand( "path" );
Cmd_RemoveCommand( "dir" );
Cmd_RemoveCommand( "fdir" );
Cmd_RemoveCommand( "touchFile" );
Cmd_RemoveCommand( "which" );
#ifdef FS_MISSING
if (closemfp) {
fclose(missingFiles);
}
#endif
}
#ifndef STANDALONE
void Com_AppendCDKey( const char *filename );
void Com_ReadCDKey( const char *filename );
#endif
/*
================
FS_ReorderPurePaks
NOTE TTimo: the reordering that happens here is not reflected in the cvars (\cvarlist *pak*)
this can lead to misleading situations, see https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
================
*/
static void FS_ReorderPurePaks( void )
{
searchpath_t *s;
int i;
searchpath_t **p_insert_index, // for linked list reordering
**p_previous; // when doing the scan
fs_reordered = qfalse;
// only relevant when connected to pure server
if ( !fs_numServerPaks )
return;
p_insert_index = &fs_searchpaths; // we insert in order at the beginning of the list
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
p_previous = p_insert_index; // track the pointer-to-current-item
for (s = *p_insert_index; s; s = s->next) {
// the part of the list before p_insert_index has been sorted already
if (s->pack && fs_serverPaks[i] == s->pack->checksum) {
fs_reordered = qtrue;
// move this element to the insert list
*p_previous = s->next;
s->next = *p_insert_index;
*p_insert_index = s;
// increment insert list
p_insert_index = &s->next;
break; // iterate to next server pack
}
p_previous = &s->next;
}
}
}
/*
================
FS_Startup
================
*/
static void FS_Startup( const char *gameName )
{
const char *homePath;
Com_Printf( "----- FS_Startup -----\n" );
fs_packFiles = 0;
fs_debug = Cvar_Get( "fs_debug", "0", 0 );
fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT|CVAR_PROTECTED );
fs_basegame = Cvar_Get ("fs_basegame", "", CVAR_INIT );
homePath = Sys_DefaultHomePath();
if (!homePath || !homePath[0]) {
homePath = fs_basepath->string;
}
fs_homepath = Cvar_Get ("fs_homepath", homePath, CVAR_INIT|CVAR_PROTECTED );
fs_gamedirvar = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
// add search path elements in reverse priority order
fs_steampath = Cvar_Get ("fs_steampath", Sys_SteamPath(), CVAR_INIT|CVAR_PROTECTED );
if (fs_steampath->string[0]) {
FS_AddGameDirectory( fs_steampath->string, gameName );
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory( fs_basepath->string, gameName );
}
// fs_homepath is somewhat particular to *nix systems, only add if relevant
#ifdef __APPLE__
fs_apppath = Cvar_Get ("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT|CVAR_PROTECTED );
// Make MacOSX also include the base path included with the .app bundle
if (fs_apppath->string[0])
FS_AddGameDirectory(fs_apppath->string, gameName);
#endif
// NOTE: same filtering below for mods and basegame
if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string)) {
FS_CreatePath ( fs_homepath->string );
FS_AddGameDirectory ( fs_homepath->string, gameName );
}
// check for additional base game so mods can be based upon other mods
if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) ) {
if (fs_steampath->string[0]) {
FS_AddGameDirectory(fs_steampath->string, fs_basegame->string);
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory(fs_basepath->string, fs_basegame->string);
}
if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string)) {
FS_AddGameDirectory(fs_homepath->string, fs_basegame->string);
}
}
// check for additional game folder for mods
if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) ) {
if (fs_steampath->string[0]) {
FS_AddGameDirectory(fs_steampath->string, fs_gamedirvar->string);
}
if (fs_basepath->string[0]) {
FS_AddGameDirectory(fs_basepath->string, fs_gamedirvar->string);
}
if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string)) {
FS_AddGameDirectory(fs_homepath->string, fs_gamedirvar->string);
}
}
#ifndef STANDALONE
if(!com_standalone->integer)
{
cvar_t *fs;
Com_ReadCDKey(BASEGAME);
fs = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
if (fs && fs->string[0] != 0) {
Com_AppendCDKey( fs->string );
}
}
#endif
// add our commands
Cmd_AddCommand ("path", FS_Path_f);
Cmd_AddCommand ("dir", FS_Dir_f );
Cmd_AddCommand ("fdir", FS_NewDir_f );
Cmd_AddCommand ("touchFile", FS_TouchFile_f );
Cmd_AddCommand ("which", FS_Which_f );
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=506
// reorder the pure pk3 files according to server order
FS_ReorderPurePaks();
// print the current search paths
FS_Path_f();
fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified
Com_Printf( "----------------------\n" );
#ifdef FS_MISSING
if (missingFiles == NULL) {
missingFiles = Sys_FOpen( "\\missing.txt", "ab" );
}
#endif
Com_Printf( "%d files in pk3 files\n", fs_packFiles );
}
#ifndef STANDALONE
/*
===================
FS_CheckPak0
Check whether any of the original id pak files is present,
and start up in standalone mode, if there are none and a
different com_basegame was set.
Note: If you're building a game that doesn't depend on the
Q3 media pak0.pk3, you'll want to remove this by defining
STANDALONE in q_shared.h
===================
*/
static void FS_CheckPak0( void )
{
searchpath_t *path;
pack_t *curpack;
qboolean founddemo = qfalse;
unsigned int foundPak = 0, foundTA = 0;
for( path = fs_searchpaths; path; path = path->next )
{
const char* pakBasename = path->pack->pakBasename;
if(!path->pack)
continue;
curpack = path->pack;
if(!Q_stricmpn( curpack->pakGamename, "demoq3", MAX_OSPATH )
&& !Q_stricmpn( pakBasename, "pak0", MAX_OSPATH ))
{
if(curpack->checksum == DEMO_PAK0_CHECKSUM)
founddemo = qtrue;
}
else if(!Q_stricmpn( curpack->pakGamename, BASEGAME, MAX_OSPATH )
&& strlen(pakBasename) == 4 && !Q_stricmpn( pakBasename, "pak", 3 )
&& pakBasename[3] >= '0' && pakBasename[3] <= '0' + NUM_ID_PAKS - 1)
{
if( curpack->checksum != pak_checksums[pakBasename[3]-'0'] )
{
if(pakBasename[3] == '0')
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/pak0.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-copy pak0.pk3 from your\n"
"legitimate Q3 CDROM.\n"
"**************************************************\n\n\n",
curpack->checksum );
}
else
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/pak%d.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-install the point release\n"
"**************************************************\n\n\n",
pakBasename[3]-'0', curpack->checksum );
}
}
foundPak |= 1<<(pakBasename[3]-'0');
}
else if(!Q_stricmpn(curpack->pakGamename, BASETA, MAX_OSPATH)
&& strlen(pakBasename) == 4 && !Q_stricmpn(pakBasename, "pak", 3)
&& pakBasename[3] >= '0' && pakBasename[3] <= '0' + NUM_TA_PAKS - 1)
{
if(curpack->checksum != missionpak_checksums[pakBasename[3]-'0'])
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASETA "/pak%d.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-install Team Arena\n"
"**************************************************\n\n\n",
pakBasename[3]-'0', curpack->checksum );
}
foundTA |= 1 << (pakBasename[3]-'0');
}
else
{
int index;
// Finally check whether this pak's checksum is listed because the user tried
// to trick us by renaming the file, and set foundPak's highest bit to indicate this case.
for(index = 0; index < ARRAY_LEN(pak_checksums); index++)
{
if(curpack->checksum == pak_checksums[index])
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: %s is renamed pak file %s%cpak%d.pk3\n"
"Running in standalone mode won't work\n"
"Please rename, or remove this file\n"
"**************************************************\n\n\n",
curpack->pakFilename, BASEGAME, PATH_SEP, index);
foundPak |= 0x80000000;
}
}
for(index = 0; index < ARRAY_LEN(missionpak_checksums); index++)
{
if(curpack->checksum == missionpak_checksums[index])
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: %s is renamed pak file %s%cpak%d.pk3\n"
"Running in standalone mode won't work\n"
"Please rename, or remove this file\n"
"**************************************************\n\n\n",
curpack->pakFilename, BASETA, PATH_SEP, index);
foundTA |= 0x80000000;
}
}
}
}
if(!foundPak && !foundTA && Q_stricmp(com_basegame->string, BASEGAME))
{
Cvar_Set("com_standalone", "1");
}
else
Cvar_Set("com_standalone", "0");
if(!com_standalone->integer)
{
if(!(foundPak & 0x01))
{
if(founddemo)
{
Com_Printf( "\n\n"
"**************************************************\n"
"WARNING: It looks like you're using pak0.pk3\n"
"from the demo. This may work fine, but it is not\n"
"guaranteed or supported.\n"
"**************************************************\n\n\n" );
foundPak |= 0x01;
}
}
}
if(!com_standalone->integer && (foundPak & 0x1ff) != 0x1ff)
{
char errorText[MAX_STRING_CHARS] = "";
if((foundPak & 0x01) != 0x01)
{
Q_strcat(errorText, sizeof(errorText),
"\"pak0.pk3\" is missing. Please copy it "
"from your legitimate Q3 CDROM. ");
}
if((foundPak & 0x1fe) != 0x1fe)
{
Q_strcat(errorText, sizeof(errorText),
"Point Release files are missing. Please "
"re-install the 1.32 point release. ");
}
Q_strcat(errorText, sizeof(errorText),
va("Also check that your ioq3 executable is in "
"the correct place and that every file "
"in the \"%s\" directory is present and readable", BASEGAME));
Com_Error(ERR_FATAL, "%s", errorText);
}
if(!com_standalone->integer && foundTA && (foundTA & 0x0f) != 0x0f)
{
char errorText[MAX_STRING_CHARS] = "";
if((foundTA & 0x01) != 0x01)
{
Com_sprintf(errorText, sizeof(errorText),
"\"" BASETA "%cpak0.pk3\" is missing. Please copy it "
"from your legitimate Quake 3 Team Arena CDROM. ", PATH_SEP);
}
if((foundTA & 0x0e) != 0x0e)
{
Q_strcat(errorText, sizeof(errorText),
"Team Arena Point Release files are missing. Please "
"re-install the latest Team Arena point release.");
}
Com_Error(ERR_FATAL, "%s", errorText);
}
}
#endif
/*
=====================
FS_LoadedPakChecksums
Returns a space separated string containing the checksums of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) );
}
return info;
}
/*
=====================
FS_LoadedPakNames
Returns a space separated string containing the names of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
if (*info) {
Q_strcat(info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
return info;
}
/*
=====================
FS_LoadedPakPureChecksums
Returns a space separated string containing the pure checksums of all loaded pk3 files.
Servers with sv_pure use these checksums to compare with the checksums the clients send
back to the server.
=====================
*/
const char *FS_LoadedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) );
}
return info;
}
/*
=====================
FS_ReferencedPakChecksums
Returns a space separated string containing the checksums of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) {
Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) );
}
}
}
return info;
}
/*
=====================
FS_ReferencedPakPureChecksums
Returns a space separated string containing the pure checksums of all referenced pk3 files.
Servers with sv_pure set will get this string back from clients for pure validation
The string has a specific order, "cgame ui @ ref1 ref2 ref3 ..."
=====================
*/
const char *FS_ReferencedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
int nFlags, numPaks, checksum;
info[0] = 0;
checksum = fs_checksumFeed;
numPaks = 0;
for (nFlags = FS_CGAME_REF; nFlags; nFlags = nFlags >> 1) {
if (nFlags & FS_GENERAL_REF) {
// add a delimter between must haves and general refs
//Q_strcat(info, sizeof(info), "@ ");
info[strlen(info)+1] = '\0';
info[strlen(info)+2] = '\0';
info[strlen(info)] = '@';
info[strlen(info)] = ' ';
}
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file and has it been referenced based on flag?
if ( search->pack && (search->pack->referenced & nFlags)) {
Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) );
if (nFlags & (FS_CGAME_REF | FS_UI_REF)) {
break;
}
checksum ^= search->pack->pure_checksum;
numPaks++;
}
}
}
// last checksum is the encoded number of referenced pk3s
checksum ^= numPaks;
Q_strcat( info, sizeof( info ), va("%i ", checksum ) );
return info;
}
/*
=====================
FS_ReferencedPakNames
Returns a space separated string containing the names of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
// we want to return ALL pk3's from the fs_game path
// and referenced one's from baseq3
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) {
if (*info) {
Q_strcat(info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakGamename );
Q_strcat( info, sizeof( info ), "/" );
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
}
}
return info;
}
/*
=====================
FS_ClearPakReferences
=====================
*/
void FS_ClearPakReferences( int flags ) {
searchpath_t *search;
if ( !flags ) {
flags = -1;
}
for ( search = fs_searchpaths; search; search = search->next ) {
// is the element a pak file and has it been referenced?
if ( search->pack ) {
search->pack->referenced &= ~flags;
}
}
}
/*
=====================
FS_PureServerSetLoadedPaks
If the string is empty, all data sources will be allowed.
If not empty, only pk3 files that match one of the space
separated checksums will be checked for files, with the
exception of .cfg and .dat files.
=====================
*/
void FS_PureServerSetLoadedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
fs_numServerPaks = c;
for ( i = 0 ; i < c ; i++ ) {
fs_serverPaks[i] = atoi( Cmd_Argv( i ) );
}
if (fs_numServerPaks) {
Com_DPrintf( "Connected to a pure server.\n" );
}
else
{
if (fs_reordered)
{
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
// force a restart to make sure the search order will be correct
Com_DPrintf( "FS search reorder is required\n" );
FS_Restart(fs_checksumFeed);
return;
}
}
for ( i = 0 ; i < c ; i++ ) {
if (fs_serverPakNames[i]) {
Z_Free(fs_serverPakNames[i]);
}
fs_serverPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if ( d > MAX_SEARCH_PATHS ) {
d = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < d ; i++ ) {
fs_serverPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
}
/*
=====================
FS_PureServerSetReferencedPaks
The checksums and names of the pk3 files referenced at the server
are sent to the client and stored here. The client will use these
checksums to see if any pk3 files need to be auto-downloaded.
=====================
*/
void FS_PureServerSetReferencedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d = 0;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < c ; i++ ) {
fs_serverReferencedPaks[i] = atoi( Cmd_Argv( i ) );
}
for (i = 0 ; i < ARRAY_LEN(fs_serverReferencedPakNames); i++)
{
if(fs_serverReferencedPakNames[i])
Z_Free(fs_serverReferencedPakNames[i]);
fs_serverReferencedPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if(d > c)
d = c;
for ( i = 0 ; i < d ; i++ ) {
fs_serverReferencedPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
// ensure that there are as many checksums as there are pak names.
if(d < c)
c = d;
fs_numServerReferencedPaks = c;
}
/*
================
FS_InitFilesystem
Called only at inital startup, not when the filesystem
is resetting due to a game change
================
*/
void FS_InitFilesystem( void ) {
// allow command line parms to override our defaults
// we have to specially handle this, because normal command
// line variable sets don't happen until after the filesystem
// has already been initialized
Com_StartupVariable("fs_basepath");
Com_StartupVariable("fs_homepath");
Com_StartupVariable("fs_game");
if(!FS_FilenameCompare(Cvar_VariableString("fs_game"), com_basegame->string))
Cvar_Set("fs_game", "");
// try to start up normally
FS_Startup(com_basegame->string);
#ifndef STANDALONE
FS_CheckPak0( );
#endif
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
}
Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
Q_strncpyz(lastValidComBaseGame, com_basegame->string, sizeof(lastValidComBaseGame));
Q_strncpyz(lastValidFsBaseGame, fs_basegame->string, sizeof(lastValidFsBaseGame));
Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
}
/*
================
FS_Restart
================
*/
void FS_Restart( int checksumFeed ) {
const char *lastGameDir;
// free anything we currently have loaded
FS_Shutdown(qfalse);
// set the checksum feed
fs_checksumFeed = checksumFeed;
// clear pak references
FS_ClearPakReferences(0);
// try to start up normally
FS_Startup(com_basegame->string);
#ifndef STANDALONE
FS_CheckPak0( );
#endif
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
// this might happen when connecting to a pure server not using BASEGAME/pak0.pk3
// (for instance a TA demo server)
if (lastValidBase[0]) {
FS_PureServerSetLoadedPaks("", "");
Cvar_Set("fs_basepath", lastValidBase);
Cvar_Set("com_basegame", lastValidComBaseGame);
Cvar_Set("fs_basegame", lastValidFsBaseGame);
Cvar_Set("fs_game", lastValidGame);
lastValidBase[0] = '\0';
lastValidComBaseGame[0] = '\0';
lastValidFsBaseGame[0] = '\0';
lastValidGame[0] = '\0';
FS_Restart(checksumFeed);
Com_Error( ERR_DROP, "Invalid game folder" );
return;
}
Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
}
lastGameDir = ( lastValidGame[0] ) ? lastValidGame : lastValidComBaseGame;
if ( Q_stricmp( FS_GetCurrentGameDir(), lastGameDir ) ) {
Sys_RemovePIDFile( lastGameDir );
Sys_InitPIDFile( FS_GetCurrentGameDir() );
// skip the q3config.cfg if "safe" is on the command line
if ( !Com_SafeMode() ) {
Cbuf_AddText ("exec " Q3CONFIG_CFG "\n");
}
}
Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
Q_strncpyz(lastValidComBaseGame, com_basegame->string, sizeof(lastValidComBaseGame));
Q_strncpyz(lastValidFsBaseGame, fs_basegame->string, sizeof(lastValidFsBaseGame));
Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
}
/*
=================
FS_ConditionalRestart
Restart if necessary
Return qtrue if restarting due to game directory changed, qfalse otherwise
=================
*/
qboolean FS_ConditionalRestart(int checksumFeed, qboolean disconnect)
{
if(fs_gamedirvar->modified)
{
if(FS_FilenameCompare(lastValidGame, fs_gamedirvar->string) &&
(*lastValidGame || FS_FilenameCompare(fs_gamedirvar->string, com_basegame->string)) &&
(*fs_gamedirvar->string || FS_FilenameCompare(lastValidGame, com_basegame->string)))
{
Com_GameRestart(checksumFeed, disconnect);
return qtrue;
}
else
fs_gamedirvar->modified = qfalse;
}
if(checksumFeed != fs_checksumFeed)
FS_Restart(checksumFeed);
else if(fs_numServerPaks && !fs_reordered)
FS_ReorderPurePaks();
return qfalse;
}
/*
========================================================================================
Handle based file calls for virtual machines
========================================================================================
*/
int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
int r;
qboolean sync;
sync = qfalse;
switch( mode ) {
case FS_READ:
r = FS_FOpenFileRead( qpath, f, qtrue );
break;
case FS_WRITE:
*f = FS_FOpenFileWrite( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
case FS_APPEND_SYNC:
sync = qtrue;
case FS_APPEND:
*f = FS_FOpenFileAppend( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
default:
Com_Error( ERR_FATAL, "FS_FOpenFileByMode: bad mode" );
return -1;
}
if (!f) {
return r;
}
if ( *f ) {
fsh[*f].fileSize = r;
fsh[*f].streamed = qfalse;
if (mode == FS_READ) {
fsh[*f].streamed = qtrue;
}
}
fsh[*f].handleSync = sync;
return r;
}
int FS_FTell( fileHandle_t f ) {
int pos;
if (fsh[f].zipFile == qtrue) {
pos = unztell(fsh[f].handleFiles.file.z);
} else {
pos = ftell(fsh[f].handleFiles.file.o);
}
return pos;
}
void FS_Flush( fileHandle_t f ) {
fflush(fsh[f].handleFiles.file.o);
}
void FS_FilenameCompletion( const char *dir, const char *ext,
qboolean stripExt, void(*callback)(const char *s), qboolean allowNonPureFilesOnDisk ) {
char **filenames;
int nfiles;
int i;
char filename[ MAX_STRING_CHARS ];
filenames = FS_ListFilteredFiles( dir, ext, NULL, &nfiles, allowNonPureFilesOnDisk );
FS_SortFileList( filenames, nfiles );
for( i = 0; i < nfiles; i++ ) {
FS_ConvertPath( filenames[ i ] );
Q_strncpyz( filename, filenames[ i ], MAX_STRING_CHARS );
if( stripExt ) {
COM_StripExtension(filename, filename, sizeof(filename));
}
callback( filename );
}
FS_FreeFileList( filenames );
}
const char *FS_GetCurrentGameDir(void)
{
if(fs_gamedirvar->string[0])
return fs_gamedirvar->string;
return com_basegame->string;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3228_1 |
crossvul-cpp_data_bad_3231_3 | /*
===========================================================================
Return to Castle Wolfenstein single player GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein single player GPL Source Code (RTCW SP Source Code).
RTCW SP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW SP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
// common.c -- misc functions used in client and server
#include "q_shared.h"
#include "qcommon.h"
#include <setjmp.h>
#ifndef _WIN32
#include <netinet/in.h>
#include <sys/stat.h> // umask
#else
#include <winsock.h>
#endif
int demo_protocols[] =
{ 59, 58, 57, 0 };
#define MAXPRINTMSG 4096
#define MAX_NUM_ARGVS 50
#define MIN_DEDICATED_COMHUNKMEGS 1
#define MIN_COMHUNKMEGS 128
#define DEF_COMHUNKMEGS 256
#define DEF_COMZONEMEGS 32
#define DEF_COMHUNKMEGS_S XSTRING(DEF_COMHUNKMEGS)
#define DEF_COMZONEMEGS_S XSTRING(DEF_COMZONEMEGS)
int com_argc;
char *com_argv[MAX_NUM_ARGVS + 1];
jmp_buf abortframe; // an ERR_DROP occured, exit the entire frame
FILE *debuglogfile;
static fileHandle_t pipefile;
static fileHandle_t logfile;
fileHandle_t com_journalFile; // events are written here
fileHandle_t com_journalDataFile; // config files are written here
cvar_t *com_speeds;
cvar_t *com_developer;
cvar_t *com_dedicated;
cvar_t *com_timescale;
cvar_t *com_fixedtime;
cvar_t *com_journal;
cvar_t *com_maxfps;
cvar_t *com_altivec;
cvar_t *com_timedemo;
cvar_t *com_sv_running;
cvar_t *com_cl_running;
cvar_t *com_logfile; // 1 = buffer log, 2 = flush after each print
cvar_t *com_pipefile;
cvar_t *com_showtrace;
cvar_t *com_version;
cvar_t *com_blood;
cvar_t *com_buildScript; // for automated data building scripts
#ifdef CINEMATICS_INTRO
cvar_t *com_introPlayed;
#endif
cvar_t *cl_paused;
cvar_t *sv_paused;
cvar_t *cl_packetdelay;
cvar_t *sv_packetdelay;
cvar_t *com_cameraMode;
cvar_t *com_recommendedSet;
cvar_t *com_ansiColor;
cvar_t *com_unfocused;
cvar_t *com_maxfpsUnfocused;
cvar_t *com_minimized;
cvar_t *com_maxfpsMinimized;
cvar_t *com_abnormalExit;
cvar_t *com_standalone;
cvar_t *com_gamename;
cvar_t *com_protocol;
#ifdef LEGACY_PROTOCOL
cvar_t *com_legacyprotocol;
#endif
cvar_t *com_basegame;
cvar_t *com_homepath;
cvar_t *com_busyWait;
#if idx64
int (*Q_VMftol)(void);
#elif id386
long (QDECL *Q_ftol)(float f);
int (QDECL *Q_VMftol)(void);
void (QDECL *Q_SnapVector)(vec3_t vec);
#endif
// Rafael Notebook
cvar_t *cl_notebook;
cvar_t *com_hunkused; // Ridah
// com_speeds times
int time_game;
int time_frontend; // renderer frontend time
int time_backend; // renderer backend time
int com_frameTime;
int com_frameNumber;
qboolean com_errorEntered = qfalse;
qboolean com_fullyInitialized = qfalse;
qboolean com_gameRestarting = qfalse;
qboolean com_gameClientRestarting = qfalse;
char com_errorMessage[MAXPRINTMSG];
void Com_WriteConfig_f( void );
void CIN_CloseAllVideos( void );
//============================================================================
static char *rd_buffer;
static int rd_buffersize;
static void ( *rd_flush )( char *buffer );
void Com_BeginRedirect( char *buffer, int buffersize, void ( *flush )( char *) ) {
if ( !buffer || !buffersize || !flush ) {
return;
}
rd_buffer = buffer;
rd_buffersize = buffersize;
rd_flush = flush;
*rd_buffer = 0;
}
void Com_EndRedirect( void ) {
if ( rd_flush ) {
rd_flush( rd_buffer );
}
rd_buffer = NULL;
rd_buffersize = 0;
rd_flush = NULL;
}
/*
=============
Com_Printf
Both client and server can use this, and it will output
to the apropriate place.
A raw string should NEVER be passed as fmt, because of "%f" type crashers.
=============
*/
void QDECL Com_Printf( const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
static qboolean opening_qconsole = qfalse;
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof (msg), fmt, argptr );
va_end( argptr );
if ( rd_buffer ) {
if ( ( strlen( msg ) + strlen( rd_buffer ) ) > ( rd_buffersize - 1 ) ) {
rd_flush( rd_buffer );
*rd_buffer = 0;
}
Q_strcat( rd_buffer, rd_buffersize, msg );
// show_bug.cgi?id=51
// only flush the rcon buffer when it's necessary, avoid fragmenting
//rd_flush(rd_buffer);
//*rd_buffer = 0;
return;
}
#ifndef DEDICATED
CL_ConsolePrint( msg );
#endif
// echo to dedicated console and early console
Sys_Print( msg );
// logfile
if ( com_logfile && com_logfile->integer ) {
// TTimo: only open the qconsole.log if the filesystem is in an initialized state
// also, avoid recursing in the qconsole.log opening (i.e. if fs_debug is on)
if ( !logfile && FS_Initialized() && !opening_qconsole ) {
struct tm *newtime;
time_t aclock;
opening_qconsole = qtrue;
time( &aclock );
newtime = localtime( &aclock );
logfile = FS_FOpenFileWrite( "rtcwconsole.log" ); //----(SA) changed name for Wolf
if(logfile)
{
Com_Printf( "logfile opened on %s\n", asctime( newtime ) );
if ( com_logfile->integer > 1 )
{
// force it to not buffer so we get valid
// data even if we are crashing
FS_ForceFlush(logfile);
}
}
else
{
Com_Printf("Opening rtcwconsole.log failed!\n");
Cvar_SetValue("logfile", 0);
}
opening_qconsole = qfalse;
}
if ( logfile && FS_Initialized() ) {
FS_Write( msg, strlen( msg ), logfile );
}
}
}
/*
================
Com_DPrintf
A Com_Printf that only shows up if the "developer" cvar is set
================
*/
void QDECL Com_DPrintf( const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
if ( !com_developer || !com_developer->integer ) {
return; // don't confuse non-developers with techie stuff...
}
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof ( msg ), fmt, argptr );
va_end( argptr );
Com_Printf( "%s", msg );
}
/*
=============
Com_Error
Both client and server can use this, and it will
do the appropriate thing.
=============
*/
void QDECL Com_Error( int code, const char *fmt, ... ) {
va_list argptr;
static int lastErrorTime;
static int errorCount;
int currentTime;
qboolean restartClient;
if(com_errorEntered)
Sys_Error("recursive error after: %s", com_errorMessage);
com_errorEntered = qtrue;
Cvar_Set("com_errorCode", va("%i", code));
// when we are running automated scripts, make sure we
// know if anything failed
if ( com_buildScript && com_buildScript->integer ) {
// ERR_ENDGAME is not really an error, don't die if building a script
if ( code != ERR_ENDGAME ) {
code = ERR_FATAL;
}
}
// if we are getting a solid stream of ERR_DROP, do an ERR_FATAL
currentTime = Sys_Milliseconds();
if ( currentTime - lastErrorTime < 100 ) {
if ( ++errorCount > 3 ) {
code = ERR_FATAL;
}
} else {
errorCount = 0;
}
lastErrorTime = currentTime;
va_start( argptr,fmt );
Q_vsnprintf (com_errorMessage, sizeof(com_errorMessage),fmt,argptr);
va_end( argptr );
if ( code != ERR_DISCONNECT && code != ERR_NEED_CD && code != ERR_ENDGAME ) {
Cvar_Set( "com_errorMessage", com_errorMessage );
}
restartClient = com_gameClientRestarting && !( com_cl_running && com_cl_running->integer );
com_gameRestarting = qfalse;
com_gameClientRestarting = qfalse;
if (code == ERR_DISCONNECT || code == ERR_SERVERDISCONNECT) {
VM_Forced_Unload_Start();
SV_Shutdown( "Server disconnected" );
if ( restartClient ) {
CL_Init();
}
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
// make sure we can get at our local stuff
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else if ( code == ERR_ENDGAME ) { //----(SA) added
VM_Forced_Unload_Start();
SV_Shutdown( "endgame" );
if ( restartClient ) {
CL_Init();
}
if ( com_cl_running && com_cl_running->integer ) {
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
#ifndef DEDICATED
CL_EndgameMenu();
#endif
}
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else if (code == ERR_DROP) {
Com_Printf( "********************\nERROR: %s\n********************\n", com_errorMessage );
VM_Forced_Unload_Start();
SV_Shutdown (va("Server crashed: %s", com_errorMessage));
if ( restartClient ) {
CL_Init();
}
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else if ( code == ERR_NEED_CD ) {
VM_Forced_Unload_Start();
SV_Shutdown( "Server didn't have CD" );
if ( restartClient ) {
CL_Init();
}
if ( com_cl_running && com_cl_running->integer ) {
CL_Disconnect( qtrue );
CL_FlushMemory();
VM_Forced_Unload_Done();
CL_CDDialog();
} else {
Com_Printf( "Server didn't have CD\n" );
VM_Forced_Unload_Done();
}
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp( abortframe, -1 );
} else {
VM_Forced_Unload_Start();
CL_Shutdown(va("Client fatal crashed: %s", com_errorMessage), qtrue, qtrue);
SV_Shutdown(va("Server fatal crashed: %s", com_errorMessage));
VM_Forced_Unload_Done();
}
Com_Shutdown();
Sys_Error( "%s", com_errorMessage );
}
/*
=============
Com_Quit_f
Both client and server can use this, and it will
do the apropriate things.
=============
*/
void Com_Quit_f( void ) {
// don't try to shutdown if we are in a recursive error
char *p = Cmd_Args( );
if ( !com_errorEntered ) {
// Some VMs might execute "quit" command directly,
// which would trigger an unload of active VM error.
// Sys_Quit will kill this process anyways, so
// a corrupt call stack makes no difference
VM_Forced_Unload_Start();
SV_Shutdown(p[0] ? p : "Server quit");
CL_Shutdown(p[0] ? p : "Client quit", qtrue, qtrue);
VM_Forced_Unload_Done();
Com_Shutdown();
FS_Shutdown( qtrue );
}
Sys_Quit();
}
/*
============================================================================
COMMAND LINE FUNCTIONS
+ characters seperate the commandLine string into multiple console
command lines.
All of these are valid:
quake3 +set test blah +map test
quake3 set test blah+map test
quake3 set test blah + map test
============================================================================
*/
#define MAX_CONSOLE_LINES 32
int com_numConsoleLines;
char *com_consoleLines[MAX_CONSOLE_LINES];
/*
==================
Com_ParseCommandLine
Break it up into multiple console lines
==================
*/
void Com_ParseCommandLine( char *commandLine ) {
com_consoleLines[0] = commandLine;
com_numConsoleLines = 1;
while ( *commandLine ) {
// look for a + separating character
// if commandLine came from a file, we might have real line seperators
if ( *commandLine == '+' || *commandLine == '\n' ) {
if ( com_numConsoleLines == MAX_CONSOLE_LINES ) {
return;
}
com_consoleLines[com_numConsoleLines] = commandLine + 1;
com_numConsoleLines++;
*commandLine = 0;
}
commandLine++;
}
}
/*
===================
Com_SafeMode
Check for "safe" on the command line, which will
skip loading of wolfconfig.cfg
===================
*/
qboolean Com_SafeMode( void ) {
int i;
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
Cmd_TokenizeString( com_consoleLines[i] );
if ( !Q_stricmp( Cmd_Argv( 0 ), "safe" )
|| !Q_stricmp( Cmd_Argv( 0 ), "cvar_restart" ) ) {
com_consoleLines[i][0] = 0;
return qtrue;
}
}
return qfalse;
}
/*
===============
Com_StartupVariable
Searches for command line parameters that are set commands.
If match is not NULL, only that cvar will be looked for.
That is necessary because cddir and basedir need to be set
before the filesystem is started, but all other sets should
be after execing the config and default.
===============
*/
void Com_StartupVariable( const char *match ) {
int i;
char *s;
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
Cmd_TokenizeString( com_consoleLines[i] );
if ( strcmp( Cmd_Argv( 0 ), "set" ) ) {
continue;
}
s = Cmd_Argv( 1 );
if(!match || !strcmp(s, match))
{
if(Cvar_Flags(s) == CVAR_NONEXISTENT)
Cvar_Get(s, Cmd_ArgsFrom(2), CVAR_USER_CREATED);
else
Cvar_Set2(s, Cmd_ArgsFrom(2), qfalse);
}
}
}
/*
=================
Com_AddStartupCommands
Adds command line parameters as script statements
Commands are seperated by + signs
Returns qtrue if any late commands were added, which
will keep the demoloop from immediately starting
=================
*/
qboolean Com_AddStartupCommands( void ) {
int i;
qboolean added;
added = qfalse;
// quote every token, so args with semicolons can work
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
if ( !com_consoleLines[i] || !com_consoleLines[i][0] ) {
continue;
}
// set commands already added with Com_StartupVariable
if ( !Q_stricmpn( com_consoleLines[i], "set ", 4 ) ) {
continue;
}
added = qtrue;
Cbuf_AddText( com_consoleLines[i] );
Cbuf_AddText( "\n" );
}
return added;
}
//============================================================================
void Info_Print( const char *s ) {
char key[BIG_INFO_KEY];
char value[BIG_INFO_VALUE];
char *o;
int l;
if ( *s == '\\' ) {
s++;
}
while ( *s )
{
o = key;
while ( *s && *s != '\\' )
*o++ = *s++;
l = o - key;
if ( l < 20 ) {
memset( o, ' ', 20 - l );
key[20] = 0;
} else {
*o = 0;
}
Com_Printf( "%s ", key );
if ( !*s ) {
Com_Printf( "MISSING VALUE\n" );
return;
}
o = value;
s++;
while ( *s && *s != '\\' )
*o++ = *s++;
*o = 0;
if ( *s ) {
s++;
}
Com_Printf( "%s\n", value );
}
}
/*
============
Com_StringContains
============
*/
char *Com_StringContains( char *str1, char *str2, int casesensitive ) {
int len, i, j;
len = strlen( str1 ) - strlen( str2 );
for ( i = 0; i <= len; i++, str1++ ) {
for ( j = 0; str2[j]; j++ ) {
if ( casesensitive ) {
if ( str1[j] != str2[j] ) {
break;
}
} else {
if ( toupper( str1[j] ) != toupper( str2[j] ) ) {
break;
}
}
}
if ( !str2[j] ) {
return str1;
}
}
return NULL;
}
/*
============
Com_Filter
============
*/
int Com_Filter( char *filter, char *name, int casesensitive ) {
char buf[MAX_TOKEN_CHARS];
char *ptr;
int i, found;
while ( *filter ) {
if ( *filter == '*' ) {
filter++;
for ( i = 0; *filter; i++ ) {
if ( *filter == '*' || *filter == '?' ) {
break;
}
buf[i] = *filter;
filter++;
}
buf[i] = '\0';
if ( strlen( buf ) ) {
ptr = Com_StringContains( name, buf, casesensitive );
if ( !ptr ) {
return qfalse;
}
name = ptr + strlen( buf );
}
} else if ( *filter == '?' ) {
filter++;
name++;
} else if ( *filter == '[' && *( filter + 1 ) == '[' ) {
filter++;
} else if ( *filter == '[' ) {
filter++;
found = qfalse;
while ( *filter && !found ) {
if ( *filter == ']' && *( filter + 1 ) != ']' ) {
break;
}
if ( *( filter + 1 ) == '-' && *( filter + 2 ) && ( *( filter + 2 ) != ']' || *( filter + 3 ) == ']' ) ) {
if ( casesensitive ) {
if ( *name >= *filter && *name <= *( filter + 2 ) ) {
found = qtrue;
}
} else {
if ( toupper( *name ) >= toupper( *filter ) &&
toupper( *name ) <= toupper( *( filter + 2 ) ) ) {
found = qtrue;
}
}
filter += 3;
} else {
if ( casesensitive ) {
if ( *filter == *name ) {
found = qtrue;
}
} else {
if ( toupper( *filter ) == toupper( *name ) ) {
found = qtrue;
}
}
filter++;
}
}
if ( !found ) {
return qfalse;
}
while ( *filter ) {
if ( *filter == ']' && *( filter + 1 ) != ']' ) {
break;
}
filter++;
}
filter++;
name++;
} else {
if ( casesensitive ) {
if ( *filter != *name ) {
return qfalse;
}
} else {
if ( toupper( *filter ) != toupper( *name ) ) {
return qfalse;
}
}
filter++;
name++;
}
}
return qtrue;
}
/*
============
Com_FilterPath
============
*/
int Com_FilterPath( char *filter, char *name, int casesensitive ) {
int i;
char new_filter[MAX_QPATH];
char new_name[MAX_QPATH];
for ( i = 0; i < MAX_QPATH - 1 && filter[i]; i++ ) {
if ( filter[i] == '\\' || filter[i] == ':' ) {
new_filter[i] = '/';
} else {
new_filter[i] = filter[i];
}
}
new_filter[i] = '\0';
for ( i = 0; i < MAX_QPATH - 1 && name[i]; i++ ) {
if ( name[i] == '\\' || name[i] == ':' ) {
new_name[i] = '/';
} else {
new_name[i] = name[i];
}
}
new_name[i] = '\0';
return Com_Filter( new_filter, new_name, casesensitive );
}
/*
================
Com_RealTime
================
*/
int Com_RealTime( qtime_t *qtime ) {
time_t t;
struct tm *tms;
t = time( NULL );
if ( !qtime ) {
return t;
}
tms = localtime( &t );
if ( tms ) {
qtime->tm_sec = tms->tm_sec;
qtime->tm_min = tms->tm_min;
qtime->tm_hour = tms->tm_hour;
qtime->tm_mday = tms->tm_mday;
qtime->tm_mon = tms->tm_mon;
qtime->tm_year = tms->tm_year;
qtime->tm_wday = tms->tm_wday;
qtime->tm_yday = tms->tm_yday;
qtime->tm_isdst = tms->tm_isdst;
}
return t;
}
/*
==============================================================================
ZONE MEMORY ALLOCATION
==============================================================================
The old zone is gone, mallocs replaced it. To keep the widespread code changes down to a bare minimum
Z_Malloc and Z_Free still work.
*/
/*
========================
Z_Free
========================
*/
void Z_Free( void *ptr ) {
free( ptr );
}
/*
================
Z_Malloc
================
*/
void *Z_Malloc( int size ) {
void *buf = malloc( size );
Com_Memset( buf, 0, size );
return buf;
}
#if 0
/*
================
Z_TagMalloc
================
*/
void *Z_TagMalloc( int size, int tag ) {
if ( tag != TAG_RENDERER ) {
assert( 0 );
}
if ( g_numTaggedAllocs < MAX_TAG_ALLOCS ) {
void *ptr = Z_Malloc( size );
g_taggedAllocations[g_numTaggedAllocs++] = ptr;
return ptr;
} else {
Com_Error( ERR_FATAL, "Z_TagMalloc: out of tagged allocation space\n" );
}
return NULL;
}
/*
================
Z_FreeTags
================
*/
void Z_FreeTags( int tag ) {
int i;
if ( tag != TAG_RENDERER ) {
assert( 0 );
}
for ( i = 0; i < g_numTaggedAllocs; i++ ) {
free( g_taggedAllocations[i] );
}
g_numTaggedAllocs = 0;
}
#endif
/*
========================
CopyString
NOTE: never write over the memory CopyString returns because
memory from a memstatic_t might be returned
========================
*/
char *CopyString( const char *in ) {
char *out;
out = Z_Malloc( strlen( in ) + 1 );
strcpy( out, in );
return out;
}
/*
==============================================================================
Goals:
reproducable without history effects -- no out of memory errors on weird map to map changes
allow restarting of the client without fragmentation
minimize total pages in use at run time
minimize total pages needed during load time
Single block of memory with stack allocators coming from both ends towards the middle.
One side is designated the temporary memory allocator.
Temporary memory can be allocated and freed in any order.
A highwater mark is kept of the most in use at any time.
When there is no temporary memory allocated, the permanent and temp sides
can be switched, allowing the already touched temp memory to be used for
permanent storage.
Temp memory must never be allocated on two ends at once, or fragmentation
could occur.
If we have any in-use temp memory, additional temp allocations must come from
that side.
If not, we can choose to make either side the new temp side and push future
permanent allocations to the other side. Permanent allocations should be
kept on the side that has the current greatest wasted highwater mark.
==============================================================================
*/
#define HUNK_MAGIC 0x89537892
#define HUNK_FREE_MAGIC 0x89537893
typedef struct {
int magic;
int size;
} hunkHeader_t;
typedef struct {
int mark;
int permanent;
int temp;
int tempHighwater;
} hunkUsed_t;
typedef struct hunkblock_s {
int size;
byte printed;
struct hunkblock_s *next;
char *label;
char *file;
int line;
} hunkblock_t;
static hunkblock_t *hunkblocks;
static hunkUsed_t hunk_low, hunk_high;
static hunkUsed_t *hunk_permanent, *hunk_temp;
static byte *s_hunkData = NULL;
static int s_hunkTotal;
static int s_zoneTotal;
//static int s_smallZoneTotal; // TTimo: unused
/*
=================
Com_Meminfo_f
=================
*/
void Com_Meminfo_f( void ) {
int unused;
Com_Printf( "%8i bytes total hunk\n", s_hunkTotal );
Com_Printf( "%8i bytes total zone\n", s_zoneTotal );
Com_Printf( "\n" );
Com_Printf( "%8i low mark\n", hunk_low.mark );
Com_Printf( "%8i low permanent\n", hunk_low.permanent );
if ( hunk_low.temp != hunk_low.permanent ) {
Com_Printf( "%8i low temp\n", hunk_low.temp );
}
Com_Printf( "%8i low tempHighwater\n", hunk_low.tempHighwater );
Com_Printf( "\n" );
Com_Printf( "%8i high mark\n", hunk_high.mark );
Com_Printf( "%8i high permanent\n", hunk_high.permanent );
if ( hunk_high.temp != hunk_high.permanent ) {
Com_Printf( "%8i high temp\n", hunk_high.temp );
}
Com_Printf( "%8i high tempHighwater\n", hunk_high.tempHighwater );
Com_Printf( "\n" );
Com_Printf( "%8i total hunk in use\n", hunk_low.permanent + hunk_high.permanent );
unused = 0;
if ( hunk_low.tempHighwater > hunk_low.permanent ) {
unused += hunk_low.tempHighwater - hunk_low.permanent;
}
if ( hunk_high.tempHighwater > hunk_high.permanent ) {
unused += hunk_high.tempHighwater - hunk_high.permanent;
}
Com_Printf( "%8i unused highwater\n", unused );
Com_Printf( "\n" );
//Com_Printf( " %i number of tagged renderer allocations\n", g_numTaggedAllocs);
}
/*
===============
Com_TouchMemory
Touch all known used data to make sure it is paged in
===============
*/
void Com_TouchMemory( void ) {
int start, end;
int i, j;
int sum;
start = Sys_Milliseconds();
sum = 0;
j = hunk_low.permanent >> 2;
for ( i = 0 ; i < j ; i += 64 ) { // only need to touch each page
sum += ( (int *)s_hunkData )[i];
}
i = ( s_hunkTotal - hunk_high.permanent ) >> 2;
j = hunk_high.permanent >> 2;
for ( ; i < j ; i += 64 ) { // only need to touch each page
sum += ( (int *)s_hunkData )[i];
}
end = Sys_Milliseconds();
Com_Printf( "Com_TouchMemory: %i msec\n", end - start );
}
void Com_InitZoneMemory( void ) {
//memset(g_taggedAllocations, 0, sizeof(g_taggedAllocations));
//g_numTaggedAllocs = 0;
}
/*
=================
Hunk_Log
=================
*/
void Hunk_Log( void ) {
hunkblock_t *block;
char buf[4096];
int size, numBlocks;
if ( !logfile || !FS_Initialized() ) {
return;
}
size = 0;
numBlocks = 0;
Com_sprintf( buf, sizeof( buf ), "\r\n================\r\nHunk log\r\n================\r\n" );
FS_Write( buf, strlen( buf ), logfile );
for ( block = hunkblocks ; block; block = block->next ) {
#ifdef HUNK_DEBUG
Com_sprintf( buf, sizeof( buf ), "size = %8d: %s, line: %d (%s)\r\n", block->size, block->file, block->line, block->label );
FS_Write( buf, strlen( buf ), logfile );
#endif
size += block->size;
numBlocks++;
}
Com_sprintf( buf, sizeof( buf ), "%d Hunk memory\r\n", size );
FS_Write( buf, strlen( buf ), logfile );
Com_sprintf( buf, sizeof( buf ), "%d hunk blocks\r\n", numBlocks );
FS_Write( buf, strlen( buf ), logfile );
}
/*
=================
Hunk_SmallLog
=================
*/
void Hunk_SmallLog( void ) {
hunkblock_t *block, *block2;
char buf[4096];
int size, locsize, numBlocks;
if ( !logfile || !FS_Initialized() ) {
return;
}
for ( block = hunkblocks ; block; block = block->next ) {
block->printed = qfalse;
}
size = 0;
numBlocks = 0;
Com_sprintf( buf, sizeof( buf ), "\r\n================\r\nHunk Small log\r\n================\r\n" );
FS_Write( buf, strlen( buf ), logfile );
for ( block = hunkblocks; block; block = block->next ) {
if ( block->printed ) {
continue;
}
locsize = block->size;
for ( block2 = block->next; block2; block2 = block2->next ) {
if ( block->line != block2->line ) {
continue;
}
if ( Q_stricmp( block->file, block2->file ) ) {
continue;
}
size += block2->size;
locsize += block2->size;
block2->printed = qtrue;
}
#ifdef HUNK_DEBUG
Com_sprintf( buf, sizeof( buf ), "size = %8d: %s, line: %d (%s)\r\n", locsize, block->file, block->line, block->label );
FS_Write( buf, strlen( buf ), logfile );
#endif
size += block->size;
numBlocks++;
}
Com_sprintf( buf, sizeof( buf ), "%d Hunk memory\r\n", size );
FS_Write( buf, strlen( buf ), logfile );
Com_sprintf( buf, sizeof( buf ), "%d hunk blocks\r\n", numBlocks );
FS_Write( buf, strlen( buf ), logfile );
}
/*
=================
Com_InitHunkMemory
=================
*/
void Com_InitHunkMemory( void ) {
cvar_t *cv;
int nMinAlloc;
char *pMsg = NULL;
// make sure the file system has allocated and "not" freed any temp blocks
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( FS_LoadStack() != 0 ) {
Com_Error( ERR_FATAL, "Hunk initialization failed. File system load stack not zero" );
}
// allocate the stack based hunk allocator
cv = Cvar_Get( "com_hunkMegs", DEF_COMHUNKMEGS_S, CVAR_LATCH | CVAR_ARCHIVE );
// if we are not dedicated min allocation is 56, otherwise min is 1
if ( com_dedicated && com_dedicated->integer ) {
nMinAlloc = MIN_DEDICATED_COMHUNKMEGS;
pMsg = "Minimum com_hunkMegs for a dedicated server is %i, allocating %i megs.\n";
} else {
nMinAlloc = MIN_COMHUNKMEGS;
pMsg = "Minimum com_hunkMegs is %i, allocating %i megs.\n";
}
if ( cv->integer < nMinAlloc ) {
s_hunkTotal = 1024 * 1024 * nMinAlloc;
Com_Printf( pMsg, nMinAlloc, s_hunkTotal / ( 1024 * 1024 ) );
} else {
s_hunkTotal = cv->integer * 1024 * 1024;
}
s_hunkData = malloc( s_hunkTotal + 31 );
if ( !s_hunkData ) {
Com_Error( ERR_FATAL, "Hunk data failed to allocate %i megs", s_hunkTotal / ( 1024 * 1024 ) );
}
// cacheline align
s_hunkData = (byte *) ( ( (intptr_t)s_hunkData + 31 ) & ~31 );
Hunk_Clear();
Cmd_AddCommand( "meminfo", Com_Meminfo_f );
#ifdef HUNK_DEBUG
Cmd_AddCommand( "hunklog", Hunk_Log );
Cmd_AddCommand( "hunksmalllog", Hunk_SmallLog );
#endif
}
/*
====================
Hunk_MemoryRemaining
====================
*/
int Hunk_MemoryRemaining( void ) {
int low, high;
low = hunk_low.permanent > hunk_low.temp ? hunk_low.permanent : hunk_low.temp;
high = hunk_high.permanent > hunk_high.temp ? hunk_high.permanent : hunk_high.temp;
return s_hunkTotal - ( low + high );
}
/*
===================
Hunk_SetMark
The server calls this after the level and game VM have been loaded
===================
*/
void Hunk_SetMark( void ) {
hunk_low.mark = hunk_low.permanent;
hunk_high.mark = hunk_high.permanent;
}
/*
=================
Hunk_ClearToMark
The client calls this before starting a vid_restart or snd_restart
=================
*/
void Hunk_ClearToMark( void ) {
hunk_low.permanent = hunk_low.temp = hunk_low.mark;
hunk_high.permanent = hunk_high.temp = hunk_high.mark;
}
/*
=================
Hunk_CheckMark
=================
*/
qboolean Hunk_CheckMark( void ) {
if ( hunk_low.mark || hunk_high.mark ) {
return qtrue;
}
return qfalse;
}
void CL_ShutdownCGame( void );
void CL_ShutdownUI( void );
void SV_ShutdownGameProgs( void );
/*
=================
Hunk_Clear
The server calls this before shutting down or loading a new map
=================
*/
void Hunk_Clear( void ) {
#ifndef DEDICATED
CL_ShutdownCGame();
CL_ShutdownUI();
#endif
SV_ShutdownGameProgs();
#ifndef DEDICATED
CIN_CloseAllVideos();
#endif
hunk_low.mark = 0;
hunk_low.permanent = 0;
hunk_low.temp = 0;
hunk_low.tempHighwater = 0;
hunk_high.mark = 0;
hunk_high.permanent = 0;
hunk_high.temp = 0;
hunk_high.tempHighwater = 0;
hunk_permanent = &hunk_low;
hunk_temp = &hunk_high;
Cvar_Set( "com_hunkused", va( "%i", hunk_low.permanent + hunk_high.permanent ) );
Com_Printf( "Hunk_Clear: reset the hunk ok\n" );
VM_Clear(); // (SA) FIXME:TODO: was commented out in wolf
#ifdef HUNK_DEBUG
hunkblocks = NULL;
#endif
}
static void Hunk_SwapBanks( void ) {
hunkUsed_t *swap;
// can't swap banks if there is any temp already allocated
if ( hunk_temp->temp != hunk_temp->permanent ) {
return;
}
// if we have a larger highwater mark on this side, start making
// our permanent allocations here and use the other side for temp
if ( hunk_temp->tempHighwater - hunk_temp->permanent >
hunk_permanent->tempHighwater - hunk_permanent->permanent ) {
swap = hunk_temp;
hunk_temp = hunk_permanent;
hunk_permanent = swap;
}
}
/*
=================
Hunk_Alloc
Allocate permanent (until the hunk is cleared) memory
=================
*/
#ifdef HUNK_DEBUG
void *Hunk_AllocDebug( int size, ha_pref preference, char *label, char *file, int line ) {
#else
void *Hunk_Alloc( int size, ha_pref preference ) {
#endif
void *buf;
if ( s_hunkData == NULL ) {
Com_Error( ERR_FATAL, "Hunk_Alloc: Hunk memory system not initialized" );
}
Hunk_SwapBanks();
#ifdef HUNK_DEBUG
size += sizeof( hunkblock_t );
#endif
// round to cacheline
size = ( size + 31 ) & ~31;
if ( hunk_low.temp + hunk_high.temp + size > s_hunkTotal ) {
#ifdef HUNK_DEBUG
Hunk_Log();
Hunk_SmallLog();
Com_Error(ERR_DROP, "Hunk_Alloc failed on %i: %s, line: %d (%s)", size, file, line, label);
#else
Com_Error(ERR_DROP, "Hunk_Alloc failed on %i", size);
#endif
}
if ( hunk_permanent == &hunk_low ) {
buf = ( void * )( s_hunkData + hunk_permanent->permanent );
hunk_permanent->permanent += size;
} else {
hunk_permanent->permanent += size;
buf = ( void * )( s_hunkData + s_hunkTotal - hunk_permanent->permanent );
}
hunk_permanent->temp = hunk_permanent->permanent;
memset( buf, 0, size );
#ifdef HUNK_DEBUG
{
hunkblock_t *block;
block = (hunkblock_t *) buf;
block->size = size - sizeof( hunkblock_t );
block->file = file;
block->label = label;
block->line = line;
block->next = hunkblocks;
hunkblocks = block;
buf = ( (byte *) buf ) + sizeof( hunkblock_t );
}
#endif
// Ridah, update the com_hunkused cvar in increments, so we don't update it too often, since this cvar call isn't very efficent
if ( ( hunk_low.permanent + hunk_high.permanent ) > com_hunkused->integer + 10000 ) {
Cvar_Set( "com_hunkused", va( "%i", hunk_low.permanent + hunk_high.permanent ) );
}
return buf;
}
/*
=================
Hunk_AllocateTempMemory
This is used by the file loading system.
Multiple files can be loaded in temporary memory.
When the files-in-use count reaches zero, all temp memory will be deleted
=================
*/
void *Hunk_AllocateTempMemory( int size ) {
void *buf;
hunkHeader_t *hdr;
// return a Z_Malloc'd block if the hunk has not been initialized
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( s_hunkData == NULL ) {
return Z_Malloc( size );
}
Hunk_SwapBanks();
size = PAD(size, sizeof(intptr_t)) + sizeof( hunkHeader_t );
if ( hunk_temp->temp + hunk_permanent->permanent + size > s_hunkTotal ) {
Com_Error( ERR_DROP, "Hunk_AllocateTempMemory: failed on %i", size );
}
if ( hunk_temp == &hunk_low ) {
buf = ( void * )( s_hunkData + hunk_temp->temp );
hunk_temp->temp += size;
} else {
hunk_temp->temp += size;
buf = ( void * )( s_hunkData + s_hunkTotal - hunk_temp->temp );
}
if ( hunk_temp->temp > hunk_temp->tempHighwater ) {
hunk_temp->tempHighwater = hunk_temp->temp;
}
hdr = (hunkHeader_t *)buf;
buf = ( void * )( hdr + 1 );
hdr->magic = HUNK_MAGIC;
hdr->size = size;
// don't bother clearing, because we are going to load a file over it
return buf;
}
/*
==================
Hunk_FreeTempMemory
==================
*/
void Hunk_FreeTempMemory( void *buf ) {
hunkHeader_t *hdr;
// free with Z_Free if the hunk has not been initialized
// this allows the config and product id files ( journal files too ) to be loaded
// by the file system without redunant routines in the file system utilizing different
// memory systems
if ( s_hunkData == NULL ) {
Z_Free( buf );
return;
}
hdr = ( (hunkHeader_t *)buf ) - 1;
if ( hdr->magic != HUNK_MAGIC ) {
Com_Error( ERR_FATAL, "Hunk_FreeTempMemory: bad magic" );
}
hdr->magic = HUNK_FREE_MAGIC;
// this only works if the files are freed in stack order,
// otherwise the memory will stay around until Hunk_ClearTempMemory
if ( hunk_temp == &hunk_low ) {
if ( hdr == ( void * )( s_hunkData + hunk_temp->temp - hdr->size ) ) {
hunk_temp->temp -= hdr->size;
} else {
Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
}
} else {
if ( hdr == ( void * )( s_hunkData + s_hunkTotal - hunk_temp->temp ) ) {
hunk_temp->temp -= hdr->size;
} else {
Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
}
}
}
/*
=================
Hunk_ClearTempMemory
The temp space is no longer needed. If we have left more
touched but unused memory on this side, have future
permanent allocs use this side.
=================
*/
void Hunk_ClearTempMemory( void ) {
if ( s_hunkData != NULL ) {
hunk_temp->temp = hunk_temp->permanent;
}
}
/*
===================================================================
EVENTS AND JOURNALING
In addition to these events, .cfg files are also copied to the
journaled file
===================================================================
*/
#define MAX_PUSHED_EVENTS 1024
static int com_pushedEventsHead = 0;
static int com_pushedEventsTail = 0;
static sysEvent_t com_pushedEvents[MAX_PUSHED_EVENTS];
/*
=================
Com_InitJournaling
=================
*/
void Com_InitJournaling( void ) {
Com_StartupVariable( "journal" );
com_journal = Cvar_Get( "journal", "0", CVAR_INIT );
if ( !com_journal->integer ) {
return;
}
if ( com_journal->integer == 1 ) {
Com_Printf( "Journaling events\n" );
com_journalFile = FS_FOpenFileWrite( "journal.dat" );
com_journalDataFile = FS_FOpenFileWrite( "journaldata.dat" );
} else if ( com_journal->integer == 2 ) {
Com_Printf( "Replaying journaled events\n" );
FS_FOpenFileRead( "journal.dat", &com_journalFile, qtrue );
FS_FOpenFileRead( "journaldata.dat", &com_journalDataFile, qtrue );
}
if ( !com_journalFile || !com_journalDataFile ) {
Cvar_Set( "com_journal", "0" );
com_journalFile = 0;
com_journalDataFile = 0;
Com_Printf( "Couldn't open journal files\n" );
}
}
/*
========================================================================
EVENT LOOP
========================================================================
*/
#define MAX_QUEUED_EVENTS 256
#define MASK_QUEUED_EVENTS ( MAX_QUEUED_EVENTS - 1 )
static sysEvent_t eventQueue[ MAX_QUEUED_EVENTS ];
static int eventHead = 0;
static int eventTail = 0;
/*
================
Com_QueueEvent
A time of 0 will get the current time
Ptr should either be null, or point to a block of data that can
be freed by the game later.
================
*/
void Com_QueueEvent( int time, sysEventType_t type, int value, int value2, int ptrLength, void *ptr )
{
sysEvent_t *ev;
ev = &eventQueue[ eventHead & MASK_QUEUED_EVENTS ];
if ( eventHead - eventTail >= MAX_QUEUED_EVENTS )
{
Com_Printf("Com_QueueEvent: overflow\n");
// we are discarding an event, but don't leak memory
if ( ev->evPtr )
{
Z_Free( ev->evPtr );
}
eventTail++;
}
eventHead++;
if ( time == 0 )
{
time = Sys_Milliseconds();
}
ev->evTime = time;
ev->evType = type;
ev->evValue = value;
ev->evValue2 = value2;
ev->evPtrLength = ptrLength;
ev->evPtr = ptr;
}
/*
================
Com_GetSystemEvent
================
*/
sysEvent_t Com_GetSystemEvent( void )
{
sysEvent_t ev;
char *s;
// return if we have data
if ( eventHead > eventTail )
{
eventTail++;
return eventQueue[ ( eventTail - 1 ) & MASK_QUEUED_EVENTS ];
}
// check for console commands
s = Sys_ConsoleInput();
if ( s )
{
char *b;
int len;
len = strlen( s ) + 1;
b = Z_Malloc( len );
strcpy( b, s );
Com_QueueEvent( 0, SE_CONSOLE, 0, 0, len, b );
}
// return if we have data
if ( eventHead > eventTail )
{
eventTail++;
return eventQueue[ ( eventTail - 1 ) & MASK_QUEUED_EVENTS ];
}
// create an empty event to return
memset( &ev, 0, sizeof( ev ) );
ev.evTime = Sys_Milliseconds();
return ev;
}
/*
=================
Com_GetRealEvent
=================
*/
sysEvent_t Com_GetRealEvent( void ) {
int r;
sysEvent_t ev;
// either get an event from the system or the journal file
if ( com_journal->integer == 2 ) {
r = FS_Read( &ev, sizeof( ev ), com_journalFile );
if ( r != sizeof( ev ) ) {
Com_Error( ERR_FATAL, "Error reading from journal file" );
}
if ( ev.evPtrLength ) {
ev.evPtr = Z_Malloc( ev.evPtrLength );
r = FS_Read( ev.evPtr, ev.evPtrLength, com_journalFile );
if ( r != ev.evPtrLength ) {
Com_Error( ERR_FATAL, "Error reading from journal file" );
}
}
} else {
ev = Com_GetSystemEvent();
// write the journal value out if needed
if ( com_journal->integer == 1 ) {
r = FS_Write( &ev, sizeof( ev ), com_journalFile );
if ( r != sizeof( ev ) ) {
Com_Error( ERR_FATAL, "Error writing to journal file" );
}
if ( ev.evPtrLength ) {
r = FS_Write( ev.evPtr, ev.evPtrLength, com_journalFile );
if ( r != ev.evPtrLength ) {
Com_Error( ERR_FATAL, "Error writing to journal file" );
}
}
}
}
return ev;
}
/*
=================
Com_InitPushEvent
=================
*/
// bk001129 - added
void Com_InitPushEvent( void ) {
// clear the static buffer array
// this requires SE_NONE to be accepted as a valid but NOP event
memset( com_pushedEvents, 0, sizeof( com_pushedEvents ) );
// reset counters while we are at it
// beware: GetEvent might still return an SE_NONE from the buffer
com_pushedEventsHead = 0;
com_pushedEventsTail = 0;
}
/*
=================
Com_PushEvent
=================
*/
void Com_PushEvent( sysEvent_t *event ) {
sysEvent_t *ev;
static int printedWarning = 0;
ev = &com_pushedEvents[ com_pushedEventsHead & ( MAX_PUSHED_EVENTS - 1 ) ];
if ( com_pushedEventsHead - com_pushedEventsTail >= MAX_PUSHED_EVENTS ) {
// don't print the warning constantly, or it can give time for more...
if ( !printedWarning ) {
printedWarning = qtrue;
Com_Printf( "WARNING: Com_PushEvent overflow\n" );
}
if ( ev->evPtr ) {
Z_Free( ev->evPtr );
}
com_pushedEventsTail++;
} else {
printedWarning = qfalse;
}
*ev = *event;
com_pushedEventsHead++;
}
/*
=================
Com_GetEvent
=================
*/
sysEvent_t Com_GetEvent( void ) {
if ( com_pushedEventsHead > com_pushedEventsTail ) {
com_pushedEventsTail++;
return com_pushedEvents[ ( com_pushedEventsTail - 1 ) & ( MAX_PUSHED_EVENTS - 1 ) ];
}
return Com_GetRealEvent();
}
/*
=================
Com_RunAndTimeServerPacket
=================
*/
void Com_RunAndTimeServerPacket( netadr_t *evFrom, msg_t *buf ) {
int t1, t2, msec;
t1 = 0;
if ( com_speeds->integer ) {
t1 = Sys_Milliseconds();
}
SV_PacketEvent( *evFrom, buf );
if ( com_speeds->integer ) {
t2 = Sys_Milliseconds();
msec = t2 - t1;
if ( com_speeds->integer == 3 ) {
Com_Printf( "SV_PacketEvent time: %i\n", msec );
}
}
}
/*
=================
Com_EventLoop
Returns last event time
=================
*/
int Com_EventLoop( void ) {
sysEvent_t ev;
netadr_t evFrom;
byte bufData[MAX_MSGLEN];
msg_t buf;
MSG_Init( &buf, bufData, sizeof( bufData ) );
while ( 1 ) {
ev = Com_GetEvent();
// if no more events are available
if ( ev.evType == SE_NONE ) {
// manually send packet events for the loopback channel
while ( NET_GetLoopPacket( NS_CLIENT, &evFrom, &buf ) ) {
CL_PacketEvent( evFrom, &buf );
}
while ( NET_GetLoopPacket( NS_SERVER, &evFrom, &buf ) ) {
// if the server just shut down, flush the events
if ( com_sv_running->integer ) {
Com_RunAndTimeServerPacket( &evFrom, &buf );
}
}
return ev.evTime;
}
switch ( ev.evType ) {
case SE_KEY:
CL_KeyEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_CHAR:
CL_CharEvent( ev.evValue );
break;
case SE_MOUSE:
CL_MouseEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_JOYSTICK_AXIS:
CL_JoystickEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_CONSOLE:
Cbuf_AddText( (char *)ev.evPtr );
Cbuf_AddText( "\n" );
break;
default:
Com_Error( ERR_FATAL, "Com_EventLoop: bad event type %i", ev.evType );
break;
}
// free any block data
if ( ev.evPtr ) {
Z_Free( ev.evPtr );
}
}
return 0; // never reached
}
/*
================
Com_Milliseconds
Can be used for profiling, but will be journaled accurately
================
*/
int Com_Milliseconds( void ) {
sysEvent_t ev;
// get events and push them until we get a null event with the current time
do {
ev = Com_GetRealEvent();
if ( ev.evType != SE_NONE ) {
Com_PushEvent( &ev );
}
} while ( ev.evType != SE_NONE );
return ev.evTime;
}
//============================================================================
/*
=============
Com_Error_f
Just throw a fatal error to
test error shutdown procedures
=============
*/
static void __attribute__((__noreturn__)) Com_Error_f (void) {
if ( Cmd_Argc() > 1 ) {
Com_Error( ERR_DROP, "Testing drop error" );
} else {
Com_Error( ERR_FATAL, "Testing fatal error" );
}
}
/*
=============
Com_Freeze_f
Just freeze in place for a given number of seconds to test
error recovery
=============
*/
static void Com_Freeze_f( void ) {
float s;
int start, now;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "freeze <seconds>\n" );
return;
}
s = atof( Cmd_Argv( 1 ) );
start = Com_Milliseconds();
while ( 1 ) {
now = Com_Milliseconds();
if ( ( now - start ) * 0.001 > s ) {
break;
}
}
}
/*
=================
Com_Crash_f
A way to force a bus error for development reasons
=================
*/
static void Com_Crash_f( void ) {
* ( volatile int * ) 0 = 0x12345678;
}
/*
==================
Com_Setenv_f
For controlling environment variables
==================
*/
void Com_Setenv_f(void)
{
int argc = Cmd_Argc();
char *arg1 = Cmd_Argv(1);
if(argc > 2)
{
char *arg2 = Cmd_ArgsFrom(2);
Sys_SetEnv(arg1, arg2);
}
else if(argc == 2)
{
char *env = getenv(arg1);
if(env)
Com_Printf("%s=%s\n", arg1, env);
else
Com_Printf("%s undefined\n", arg1);
}
}
/*
==================
Com_ExecuteCfg
For controlling environment variables
==================
*/
void Com_ExecuteCfg(void)
{
Cbuf_ExecuteText(EXEC_NOW, "exec default.cfg\n");
if ( FS_ReadFile( "language.cfg", NULL ) > 0 ) {
Cbuf_ExecuteText(EXEC_APPEND, "exec language.cfg\n");
} else if ( FS_ReadFile( "Language.cfg", NULL ) > 0 ) {
Cbuf_ExecuteText(EXEC_APPEND, "exec Language.cfg\n");
}
Cbuf_Execute(); // Always execute after exec to prevent text buffer overflowing
if(!Com_SafeMode())
{
// skip the wolfconfig.cfg and autoexec.cfg if "safe" is on the command line
Cbuf_ExecuteText(EXEC_NOW, "exec " Q3CONFIG_CFG "\n");
Cbuf_Execute();
Cbuf_ExecuteText(EXEC_NOW, "exec autoexec.cfg\n");
Cbuf_Execute();
}
}
/*
==================
Com_GameRestart
Change to a new mod properly with cleaning up cvars before switching.
==================
*/
void Com_GameRestart(int checksumFeed, qboolean disconnect)
{
// make sure no recursion can be triggered
if(!com_gameRestarting && com_fullyInitialized)
{
com_gameRestarting = qtrue;
com_gameClientRestarting = com_cl_running->integer;
// Kill server if we have one
if(com_sv_running->integer)
SV_Shutdown("Game directory changed");
if(com_gameClientRestarting)
{
if(disconnect)
CL_Disconnect(qfalse);
CL_Shutdown("Game directory changed", disconnect, qfalse);
}
FS_Restart(checksumFeed);
// Clean out any user and VM created cvars
Cvar_Restart(qtrue);
Com_ExecuteCfg();
if(disconnect)
{
// We don't want to change any network settings if gamedir
// change was triggered by a connect to server because the
// new network settings might make the connection fail.
NET_Restart_f();
}
if(com_gameClientRestarting)
{
CL_Init();
CL_StartHunkUsers(qfalse);
}
com_gameRestarting = qfalse;
com_gameClientRestarting = qfalse;
}
}
/*
==================
Com_GameRestart_f
Expose possibility to change current running mod to the user
==================
*/
void Com_GameRestart_f(void)
{
if(!FS_FilenameCompare(Cmd_Argv(1), com_basegame->string))
{
// This is the standard base game. Servers and clients should
// use "" and not the standard basegame name because this messes
// up pak file negotiation and lots of other stuff
Cvar_Set("fs_game", "");
}
else
Cvar_Set("fs_game", Cmd_Argv(1));
Com_GameRestart(0, qtrue);
}
#ifndef STANDALONE
qboolean CL_CDKeyValidate( const char *key, const char *checksum );
// TTimo: centralizing the cl_cdkey stuff after I discovered a buffer overflow problem with the dedicated server version
// not sure it's necessary to have different defaults for regular and dedicated, but I don't want to take the risk
#ifndef DEDICATED
char cl_cdkey[34] = " ";
#else
char cl_cdkey[34] = "123456789";
#endif
/*
=================
Com_ReadCDKey
=================
*/
void Com_ReadCDKey( const char *filename ) {
fileHandle_t f;
char buffer[33];
char fbuffer[MAX_OSPATH];
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename);
FS_SV_FOpenFileRead( fbuffer, &f );
if ( !f ) {
Q_strncpyz( cl_cdkey, " ", 17 );
return;
}
Com_Memset( buffer, 0, sizeof( buffer ) );
FS_Read( buffer, 16, f );
FS_FCloseFile( f );
if ( CL_CDKeyValidate( buffer, NULL ) ) {
Q_strncpyz( cl_cdkey, buffer, 17 );
} else {
Q_strncpyz( cl_cdkey, " ", 17 );
}
}
/*
=================
Com_AppendCDKey
=================
*/
void Com_AppendCDKey( const char *filename ) {
fileHandle_t f;
char buffer[33];
char fbuffer[MAX_OSPATH];
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename);
FS_SV_FOpenFileRead( fbuffer, &f );
if ( !f ) {
Q_strncpyz( &cl_cdkey[16], " ", 17 );
return;
}
Com_Memset( buffer, 0, sizeof( buffer ) );
FS_Read( buffer, 16, f );
FS_FCloseFile( f );
if ( CL_CDKeyValidate( buffer, NULL ) ) {
strcat( &cl_cdkey[16], buffer );
} else {
Q_strncpyz( &cl_cdkey[16], " ", 17 );
}
}
#ifndef DEDICATED
/*
=================
Com_WriteCDKey
=================
*/
static void Com_WriteCDKey( const char *filename, const char *ikey ) {
fileHandle_t f;
char fbuffer[MAX_OSPATH];
char key[17];
#ifndef _WIN32
mode_t savedumask;
#endif
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename);
Q_strncpyz( key, ikey, 17 );
if ( !CL_CDKeyValidate( key, NULL ) ) {
return;
}
#ifndef _WIN32
savedumask = umask(0077);
#endif
f = FS_SV_FOpenFileWrite( fbuffer );
if ( !f ) {
Com_Printf ("Couldn't write CD key to %s.\n", fbuffer );
goto out;
}
FS_Write( key, 16, f );
FS_Printf( f, "\n// generated by RTCW, do not modify\r\n" );
FS_Printf( f, "// Do not give this file to ANYONE.\r\n" );
#ifdef __APPLE__ // TTimo
FS_Printf( f, "// Aspyr will NOT ask you to send this file to them.\r\n" );
#else
FS_Printf( f, "// id Software and Activision will NOT ask you to send this file to them.\r\n" );
#endif
FS_FCloseFile( f );
out:
#ifndef _WIN32
umask(savedumask);
#else
;
#endif
}
#endif
#endif // STANDALONE
static void Com_DetectAltivec(void)
{
// Only detect if user hasn't forcibly disabled it.
if (com_altivec->integer) {
static qboolean altivec = qfalse;
static qboolean detected = qfalse;
if (!detected) {
altivec = ( Sys_GetProcessorFeatures( ) & CF_ALTIVEC );
detected = qtrue;
}
if (!altivec) {
Cvar_Set( "com_altivec", "0" ); // we don't have it! Disable support!
}
}
}
void Com_SetRecommended( qboolean vidrestart ) {
cvar_t *cv;
qboolean goodVideo;
qboolean goodCPU;
qboolean lowMemory;
// will use this for recommended settings as well.. do i outside the lower check so it gets done even with command line stuff
cv = Cvar_Get( "r_highQualityVideo", "1", CVAR_ARCHIVE );
goodVideo = ( cv && cv->integer );
goodCPU = Sys_GetHighQualityCPU();
lowMemory = Sys_LowPhysicalMemory();
if ( goodVideo && goodCPU ) {
Com_Printf( "Found high quality video and CPU\n" );
Cbuf_AddText( "exec highVidhighCPU.cfg\n" );
} else if ( goodVideo && !goodCPU ) {
Cbuf_AddText( "exec highVidlowCPU.cfg\n" );
Com_Printf( "Found high quality video and low quality CPU\n" );
} else if ( !goodVideo && goodCPU ) {
Cbuf_AddText( "exec lowVidhighCPU.cfg\n" );
Com_Printf( "Found low quality video and high quality CPU\n" );
} else {
Cbuf_AddText( "exec lowVidlowCPU.cfg\n" );
Com_Printf( "Found low quality video and low quality CPU\n" );
}
// (SA) set the cvar so the menu will reflect this on first run
Cvar_Set( "ui_glCustom", "999" ); // 'recommended'
if ( lowMemory ) {
Com_Printf( "Found minimum memory requirement\n" );
Cvar_Set( "s_khz", "11" );
if ( !goodVideo ) {
Cvar_Set( "r_lowMemTextureSize", "256" );
Cvar_Set( "r_lowMemTextureThreshold", "40.0" );
}
}
if ( vidrestart ) {
Cbuf_AddText( "vid_restart\n" );
}
}
/*
=================
Com_DetectSSE
Find out whether we have SSE support for Q_ftol function
=================
*/
#if id386 || idx64
static void Com_DetectSSE(void)
{
#if !idx64
cpuFeatures_t feat;
feat = Sys_GetProcessorFeatures();
if(feat & CF_SSE)
{
if(feat & CF_SSE2)
Q_SnapVector = qsnapvectorsse;
else
Q_SnapVector = qsnapvectorx87;
Q_ftol = qftolsse;
#endif
Q_VMftol = qvmftolsse;
Com_Printf("SSE instruction set enabled\n");
#if !idx64
}
else
{
Q_ftol = qftolx87;
Q_VMftol = qvmftolx87;
Q_SnapVector = qsnapvectorx87;
Com_Printf("SSE instruction set not available\n");
}
#endif
}
#else
#define Com_DetectSSE()
#endif
/*
=================
Com_InitRand
Seed the random number generator, if possible with an OS supplied random seed.
=================
*/
static void Com_InitRand(void)
{
unsigned int seed;
if(Sys_RandomBytes((byte *) &seed, sizeof(seed)))
srand(seed);
else
srand(time(NULL));
}
/*
=================
Com_Init
=================
*/
void Com_Init( char *commandLine ) {
char *s;
int qport;
Com_Printf( "%s %s %s\n", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
if ( setjmp( abortframe ) ) {
Sys_Error( "Error during initialization" );
}
// Clear queues
Com_Memset( &eventQueue[ 0 ], 0, MAX_QUEUED_EVENTS * sizeof( sysEvent_t ) );
// initialize the weak pseudo-random number generator for use later.
Com_InitRand();
// do this before anything else decides to push events
Com_InitPushEvent();
Cvar_Init();
// prepare enough of the subsystems to handle
// cvar and command buffer management
Com_ParseCommandLine( commandLine );
// Swap_Init();
Cbuf_Init();
Com_DetectSSE();
// override anything from the config files with command line args
Com_StartupVariable( NULL );
Com_InitZoneMemory();
Cmd_Init ();
// get the developer cvar set as early as possible
com_developer = Cvar_Get("developer", "0", CVAR_TEMP);
// done early so bind command exists
CL_InitKeyCommands();
com_standalone = Cvar_Get("com_standalone", "0", CVAR_ROM);
com_basegame = Cvar_Get("com_basegame", BASEGAME, CVAR_INIT);
com_homepath = Cvar_Get("com_homepath", "", CVAR_INIT);
if(!com_basegame->string[0])
Cvar_ForceReset("com_basegame");
FS_InitFilesystem();
Com_InitJournaling();
// Add some commands here already so users can use them from config files
Cmd_AddCommand ("setenv", Com_Setenv_f);
if (com_developer && com_developer->integer)
{
Cmd_AddCommand ("error", Com_Error_f);
Cmd_AddCommand ("crash", Com_Crash_f);
Cmd_AddCommand ("freeze", Com_Freeze_f);
}
Cmd_AddCommand ("quit", Com_Quit_f);
Cmd_AddCommand ("changeVectors", MSG_ReportChangeVectors_f );
Cmd_AddCommand ("writeconfig", Com_WriteConfig_f );
Cmd_SetCommandCompletionFunc( "writeconfig", Cmd_CompleteCfgName );
Cmd_AddCommand("game_restart", Com_GameRestart_f);
Com_ExecuteCfg();
// override anything from the config files with command line args
Com_StartupVariable( NULL );
// get dedicated here for proper hunk megs initialization
#ifdef DEDICATED
com_dedicated = Cvar_Get ("dedicated", "1", CVAR_INIT);
Cvar_CheckRange( com_dedicated, 1, 2, qtrue );
#else
com_dedicated = Cvar_Get( "dedicated", "0", CVAR_LATCH );
Cvar_CheckRange( com_dedicated, 0, 2, qtrue );
#endif
// allocate the stack based hunk allocator
Com_InitHunkMemory();
// if any archived cvars are modified after this, we will trigger a writing
// of the config file
cvar_modifiedFlags &= ~CVAR_ARCHIVE;
//
// init commands and vars
//
com_altivec = Cvar_Get ("com_altivec", "1", CVAR_ARCHIVE);
com_maxfps = Cvar_Get( "com_maxfps", "76", CVAR_ARCHIVE );
com_blood = Cvar_Get( "com_blood", "1", CVAR_ARCHIVE );
com_logfile = Cvar_Get( "logfile", "0", CVAR_TEMP );
com_timescale = Cvar_Get( "timescale", "1", CVAR_CHEAT | CVAR_SYSTEMINFO );
com_fixedtime = Cvar_Get( "fixedtime", "0", CVAR_CHEAT );
com_showtrace = Cvar_Get( "com_showtrace", "0", CVAR_CHEAT );
com_speeds = Cvar_Get( "com_speeds", "0", 0 );
com_timedemo = Cvar_Get( "timedemo", "0", CVAR_CHEAT );
com_cameraMode = Cvar_Get( "com_cameraMode", "0", CVAR_CHEAT );
cl_paused = Cvar_Get( "cl_paused", "0", CVAR_ROM );
sv_paused = Cvar_Get( "sv_paused", "0", CVAR_ROM );
cl_packetdelay = Cvar_Get ("cl_packetdelay", "0", CVAR_CHEAT);
sv_packetdelay = Cvar_Get ("sv_packetdelay", "0", CVAR_CHEAT);
com_sv_running = Cvar_Get( "sv_running", "0", CVAR_ROM );
com_cl_running = Cvar_Get( "cl_running", "0", CVAR_ROM );
com_buildScript = Cvar_Get( "com_buildScript", "0", 0 );
com_ansiColor = Cvar_Get( "com_ansiColor", "0", CVAR_ARCHIVE );
com_unfocused = Cvar_Get( "com_unfocused", "0", CVAR_ROM );
com_maxfpsUnfocused = Cvar_Get( "com_maxfpsUnfocused", "0", CVAR_ARCHIVE );
com_minimized = Cvar_Get( "com_minimized", "0", CVAR_ROM );
com_maxfpsMinimized = Cvar_Get( "com_maxfpsMinimized", "0", CVAR_ARCHIVE );
com_abnormalExit = Cvar_Get( "com_abnormalExit", "0", CVAR_ROM );
com_busyWait = Cvar_Get("com_busyWait", "0", CVAR_ARCHIVE);
Cvar_Get("com_errorMessage", "", CVAR_ROM | CVAR_NORESTART);
#ifdef CINEMATICS_INTRO
com_introPlayed = Cvar_Get( "com_introplayed", "0", CVAR_ARCHIVE );
#endif
com_recommendedSet = Cvar_Get( "com_recommendedSet", "0", CVAR_ARCHIVE );
Cvar_Get( "savegame_loading", "0", CVAR_ROM );
s = va("%s %s %s", Q3_VERSION, PLATFORM_STRING, PRODUCT_DATE );
com_version = Cvar_Get ("version", s, CVAR_ROM | CVAR_SERVERINFO );
com_gamename = Cvar_Get("com_gamename", GAMENAME_FOR_MASTER, CVAR_SERVERINFO | CVAR_INIT);
com_protocol = Cvar_Get("com_protocol", va("%i", PROTOCOL_VERSION), CVAR_SERVERINFO | CVAR_INIT);
#ifdef LEGACY_PROTOCOL
com_legacyprotocol = Cvar_Get("com_legacyprotocol", va("%i", PROTOCOL_LEGACY_VERSION), CVAR_INIT);
// Keep for compatibility with old mods / mods that haven't updated yet.
if(com_legacyprotocol->integer > 0)
Cvar_Get("protocol", com_legacyprotocol->string, CVAR_ROM);
else
#endif
Cvar_Get("protocol", com_protocol->string, CVAR_ROM);
com_hunkused = Cvar_Get( "com_hunkused", "0", 0 );
Sys_Init();
Sys_InitPIDFile( FS_GetCurrentGameDir() );
// Pick a random port value
Com_RandomBytes( (byte*)&qport, sizeof(int) );
Netchan_Init( qport & 0xffff );
VM_Init();
SV_Init();
com_dedicated->modified = qfalse;
#ifndef DEDICATED
CL_Init();
#endif
// set com_frameTime so that if a map is started on the
// command line it will still be able to count on com_frameTime
// being random enough for a serverid
com_frameTime = Com_Milliseconds();
// add + commands from command line
if ( !Com_AddStartupCommands() ) {
// if the user didn't give any commands, run default action
}
// start in full screen ui mode
Cvar_Set( "r_uiFullScreen", "1" );
CL_StartHunkUsers( qfalse );
if ( !com_recommendedSet->integer ) {
Com_SetRecommended( qtrue );
Cvar_Set( "com_recommendedSet", "1" );
}
if ( !com_dedicated->integer ) {
#ifdef CINEMATICS_LOGO
//Cbuf_AddText ("cinematic " CINEMATICS_LOGO "\n");
#endif
#ifdef CINEMATICS_INTRO
if ( !com_introPlayed->integer ) {
//Cvar_Set( com_introPlayed->name, "1" ); //----(SA) force this to get played every time (but leave cvar for override)
Cbuf_AddText( "cinematic " CINEMATICS_INTRO " 3\n" );
//Cvar_Set( "nextmap", "cinematic " CINEMATICS_INTRO );
}
#endif
}
com_fullyInitialized = qtrue;
// always set the cvar, but only print the info if it makes sense.
Com_DetectAltivec();
#if idppc
Com_Printf ("Altivec support is %s\n", com_altivec->integer ? "enabled" : "disabled");
#endif
com_pipefile = Cvar_Get( "com_pipefile", "", CVAR_ARCHIVE|CVAR_LATCH );
if( com_pipefile->string[0] )
{
pipefile = FS_FCreateOpenPipeFile( com_pipefile->string );
}
Com_Printf ("--- Common Initialization Complete ---\n");
}
/*
===============
Com_ReadFromPipe
Read whatever is in com_pipefile, if anything, and execute it
===============
*/
void Com_ReadFromPipe( void )
{
static char buf[MAX_STRING_CHARS];
static int accu = 0;
int read;
if( !pipefile )
return;
while( ( read = FS_Read( buf + accu, sizeof( buf ) - accu - 1, pipefile ) ) > 0 )
{
char *brk = NULL;
int i;
for( i = accu; i < accu + read; ++i )
{
if( buf[ i ] == '\0' )
buf[ i ] = '\n';
if( buf[ i ] == '\n' || buf[ i ] == '\r' )
brk = &buf[ i + 1 ];
}
buf[ accu + read ] = '\0';
accu += read;
if( brk )
{
char tmp = *brk;
*brk = '\0';
Cbuf_ExecuteText( EXEC_APPEND, buf );
*brk = tmp;
accu -= brk - buf;
memmove( buf, brk, accu + 1 );
}
else if( accu >= sizeof( buf ) - 1 ) // full
{
Cbuf_ExecuteText( EXEC_APPEND, buf );
accu = 0;
}
}
}
//==================================================================
void Com_WriteConfigToFile( const char *filename ) {
fileHandle_t f;
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf( "Couldn't write %s.\n", filename );
return;
}
FS_Printf( f, "// generated by RTCW, do not modify\n" );
Key_WriteBindings( f );
Cvar_WriteVariables( f );
FS_FCloseFile( f );
}
/*
===============
Com_WriteConfiguration
Writes key bindings and archived cvars to config file if modified
===============
*/
void Com_WriteConfiguration( void ) {
#if !defined(DEDICATED) && !defined(STANDALONE)
cvar_t *fs;
#endif
// if we are quiting without fully initializing, make sure
// we don't write out anything
if ( !com_fullyInitialized ) {
return;
}
if ( !( cvar_modifiedFlags & CVAR_ARCHIVE ) ) {
return;
}
cvar_modifiedFlags &= ~CVAR_ARCHIVE;
Com_WriteConfigToFile( Q3CONFIG_CFG );
// not needed for dedicated or standalone
#if !defined(DEDICATED) && !defined(STANDALONE)
fs = Cvar_Get( "fs_game", "", CVAR_INIT | CVAR_SYSTEMINFO );
if(!com_standalone->integer)
{
if (UI_usesUniqueCDKey() && fs && fs->string[0] != 0) {
Com_WriteCDKey( fs->string, &cl_cdkey[16] );
} else {
Com_WriteCDKey( BASEGAME, cl_cdkey );
}
}
#endif
}
/*
===============
Com_WriteConfig_f
Write the config file to a specific name
===============
*/
void Com_WriteConfig_f( void ) {
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: writeconfig <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
Com_Printf( "Writing %s.\n", filename );
Com_WriteConfigToFile( filename );
}
/*
================
Com_ModifyMsec
================
*/
int Com_ModifyMsec( int msec ) {
int clampTime;
//
// modify time for debugging values
//
if ( com_fixedtime->integer ) {
msec = com_fixedtime->integer;
} else if ( com_timescale->value ) {
msec *= com_timescale->value;
// } else if (com_cameraMode->integer) {
// msec *= com_timescale->value;
}
// don't let it scale below 1 msec
if ( msec < 1 && com_timescale->value ) {
msec = 1;
}
if ( com_dedicated->integer ) {
// dedicated servers don't want to clamp for a much longer
// period, because it would mess up all the client's views
// of time.
if (com_sv_running->integer && msec > 500)
Com_Printf( "Hitch warning: %i msec frame time\n", msec );
clampTime = 5000;
} else
if ( !com_sv_running->integer ) {
// clients of remote servers do not want to clamp time, because
// it would skew their view of the server's time temporarily
clampTime = 5000;
} else {
// for local single player gaming
// we may want to clamp the time to prevent players from
// flying off edges when something hitches.
clampTime = 200;
}
if ( msec > clampTime ) {
msec = clampTime;
}
return msec;
}
/*
=================
Com_TimeVal
=================
*/
int Com_TimeVal(int minMsec)
{
int timeVal;
timeVal = Sys_Milliseconds() - com_frameTime;
if(timeVal >= minMsec)
timeVal = 0;
else
timeVal = minMsec - timeVal;
return timeVal;
}
/*
=================
Com_Frame
=================
*/
void Com_Frame( void ) {
int msec, minMsec;
int timeVal, timeValSV;
static int lastTime = 0, bias = 0;
int timeBeforeFirstEvents;
int timeBeforeServer;
int timeBeforeEvents;
int timeBeforeClient;
int timeAfter;
if ( setjmp( abortframe ) ) {
return; // an ERR_DROP was thrown
}
timeBeforeFirstEvents = 0;
timeBeforeServer = 0;
timeBeforeEvents = 0;
timeBeforeClient = 0;
timeAfter = 0;
// write config file if anything changed
Com_WriteConfiguration();
//
// main event loop
//
if ( com_speeds->integer ) {
timeBeforeFirstEvents = Sys_Milliseconds();
}
// Figure out how much time we have
if(!com_timedemo->integer)
{
if(com_dedicated->integer)
minMsec = SV_FrameMsec();
else
{
if(com_minimized->integer && com_maxfpsMinimized->integer > 0)
minMsec = 1000 / com_maxfpsMinimized->integer;
else if(com_unfocused->integer && com_maxfpsUnfocused->integer > 0)
minMsec = 1000 / com_maxfpsUnfocused->integer;
else if(com_maxfps->integer > 0)
minMsec = 1000 / com_maxfps->integer;
else
minMsec = 1;
timeVal = com_frameTime - lastTime;
bias += timeVal - minMsec;
if(bias > minMsec)
bias = minMsec;
// Adjust minMsec if previous frame took too long to render so
// that framerate is stable at the requested value.
minMsec -= bias;
}
}
else
minMsec = 1;
do
{
if(com_sv_running->integer)
{
timeValSV = SV_SendQueuedPackets();
timeVal = Com_TimeVal(minMsec);
if(timeValSV < timeVal)
timeVal = timeValSV;
}
else
timeVal = Com_TimeVal(minMsec);
if(com_busyWait->integer || timeVal < 1)
NET_Sleep(0);
else
NET_Sleep(timeVal - 1);
} while(Com_TimeVal(minMsec));
lastTime = com_frameTime;
com_frameTime = Com_EventLoop();
msec = com_frameTime - lastTime;
Cbuf_Execute();
if (com_altivec->modified)
{
Com_DetectAltivec();
com_altivec->modified = qfalse;
}
// mess with msec if needed
msec = Com_ModifyMsec(msec);
//
// server side
//
if ( com_speeds->integer ) {
timeBeforeServer = Sys_Milliseconds();
}
SV_Frame( msec );
// if "dedicated" has been modified, start up
// or shut down the client system.
// Do this after the server may have started,
// but before the client tries to auto-connect
if ( com_dedicated->modified ) {
// get the latched value
Cvar_Get( "dedicated", "0", 0 );
com_dedicated->modified = qfalse;
if ( !com_dedicated->integer ) {
SV_Shutdown( "dedicated set to 0" );
CL_FlushMemory();
}
}
#ifndef DEDICATED
//
// client system
//
//
// run event loop a second time to get server to client packets
// without a frame of latency
//
if ( com_speeds->integer ) {
timeBeforeEvents = Sys_Milliseconds ();
}
Com_EventLoop();
Cbuf_Execute ();
//
// client side
//
if ( com_speeds->integer ) {
timeBeforeClient = Sys_Milliseconds ();
}
CL_Frame( msec );
if ( com_speeds->integer ) {
timeAfter = Sys_Milliseconds ();
}
#else
if ( com_speeds->integer ) {
timeAfter = Sys_Milliseconds ();
timeBeforeEvents = timeAfter;
timeBeforeClient = timeAfter;
}
#endif
NET_FlushPacketQueue();
//
// report timing information
//
if ( com_speeds->integer ) {
int all, sv, ev, cl;
all = timeAfter - timeBeforeServer;
sv = timeBeforeEvents - timeBeforeServer;
ev = timeBeforeServer - timeBeforeFirstEvents + timeBeforeClient - timeBeforeEvents;
cl = timeAfter - timeBeforeClient;
sv -= time_game;
cl -= time_frontend + time_backend;
Com_Printf( "frame:%i all:%3i sv:%3i ev:%3i cl:%3i gm:%3i rf:%3i bk:%3i\n",
com_frameNumber, all, sv, ev, cl, time_game, time_frontend, time_backend );
}
//
// trace optimization tracking
//
if ( com_showtrace->integer ) {
extern int c_traces, c_brush_traces, c_patch_traces;
extern int c_pointcontents;
Com_Printf( "%4i traces (%ib %ip) %4i points\n", c_traces,
c_brush_traces, c_patch_traces, c_pointcontents );
c_traces = 0;
c_brush_traces = 0;
c_patch_traces = 0;
c_pointcontents = 0;
}
Com_ReadFromPipe( );
com_frameNumber++;
}
/*
=================
Com_Shutdown
=================
*/
void Com_Shutdown( void ) {
// write config file if anything changed
Com_WriteConfiguration();
if ( logfile ) {
FS_FCloseFile( logfile );
logfile = 0;
}
if ( com_journalFile ) {
FS_FCloseFile( com_journalFile );
com_journalFile = 0;
}
if( pipefile ) {
FS_FCloseFile( pipefile );
FS_HomeRemove( com_pipefile->string );
}
}
/*
===========================================
command line completion
===========================================
*/
/*
==================
Field_Clear
==================
*/
void Field_Clear( field_t *edit ) {
memset( edit->buffer, 0, MAX_EDIT_LINE );
edit->cursor = 0;
edit->scroll = 0;
}
static const char *completionString;
static char shortestMatch[MAX_TOKEN_CHARS];
static int matchCount;
// field we are working on, passed to Field_AutoComplete(&g_consoleCommand for instance)
static field_t *completionField;
/*
===============
FindMatches
===============
*/
static void FindMatches( const char *s ) {
int i;
if ( Q_stricmpn( s, completionString, strlen( completionString ) ) ) {
return;
}
matchCount++;
if ( matchCount == 1 ) {
Q_strncpyz( shortestMatch, s, sizeof( shortestMatch ) );
return;
}
// cut shortestMatch to the amount common with s
for ( i = 0 ; shortestMatch[i] ; i++ ) {
if ( i >= strlen( s ) ) {
shortestMatch[i] = 0;
break;
}
if ( tolower( shortestMatch[i] ) != tolower( s[i] ) ) {
shortestMatch[i] = 0;
}
}
}
/*
===============
PrintMatches
===============
*/
static void PrintMatches( const char *s ) {
if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
Com_Printf( " %s\n", s );
}
}
/*
===============
PrintCvarMatches
===============
*/
static void PrintCvarMatches( const char *s ) {
char value[ TRUNCATE_LENGTH ];
if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
Com_TruncateLongString( value, Cvar_VariableString( s ) );
Com_Printf( " %s = \"%s\"\n", s, value );
}
}
/*
===============
Field_FindFirstSeparator
===============
*/
static char *Field_FindFirstSeparator( char *s )
{
int i;
for( i = 0; i < strlen( s ); i++ )
{
if( s[ i ] == ';' )
return &s[ i ];
}
return NULL;
}
/*
===============
Field_Complete
===============
*/
static qboolean Field_Complete( void )
{
int completionOffset;
if( matchCount == 0 )
return qtrue;
completionOffset = strlen( completionField->buffer ) - strlen( completionString );
Q_strncpyz( &completionField->buffer[ completionOffset ], shortestMatch,
sizeof( completionField->buffer ) - completionOffset );
completionField->cursor = strlen( completionField->buffer );
if( matchCount == 1 )
{
Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " );
completionField->cursor++;
return qtrue;
}
Com_Printf( "]%s\n", completionField->buffer );
return qfalse;
}
#ifndef DEDICATED
/*
===============
Field_CompleteKeyname
===============
*/
void Field_CompleteKeyname( void )
{
matchCount = 0;
shortestMatch[ 0 ] = 0;
Key_KeynameCompletion( FindMatches );
if( !Field_Complete( ) )
Key_KeynameCompletion( PrintMatches );
}
#endif
/*
===============
Field_CompleteFilename
===============
*/
void Field_CompleteFilename( const char *dir,
const char *ext, qboolean stripExt, qboolean allowNonPureFilesOnDisk )
{
matchCount = 0;
shortestMatch[ 0 ] = 0;
FS_FilenameCompletion( dir, ext, stripExt, FindMatches, allowNonPureFilesOnDisk );
if( !Field_Complete( ) )
FS_FilenameCompletion( dir, ext, stripExt, PrintMatches, allowNonPureFilesOnDisk );
}
/*
===============
Field_CompleteCommand
===============
*/
void Field_CompleteCommand( char *cmd,
qboolean doCommands, qboolean doCvars )
{
int completionArgument = 0;
// Skip leading whitespace and quotes
cmd = Com_SkipCharset( cmd, " \"" );
Cmd_TokenizeStringIgnoreQuotes( cmd );
completionArgument = Cmd_Argc( );
// If there is trailing whitespace on the cmd
if( *( cmd + strlen( cmd ) - 1 ) == ' ' )
{
completionString = "";
completionArgument++;
}
else
completionString = Cmd_Argv( completionArgument - 1 );
#ifndef DEDICATED
// Unconditionally add a '\' to the start of the buffer
if( completionField->buffer[ 0 ] &&
completionField->buffer[ 0 ] != '\\' )
{
if( completionField->buffer[ 0 ] != '/' )
{
// Buffer is full, refuse to complete
if( strlen( completionField->buffer ) + 1 >=
sizeof( completionField->buffer ) )
return;
memmove( &completionField->buffer[ 1 ],
&completionField->buffer[ 0 ],
strlen( completionField->buffer ) + 1 );
completionField->cursor++;
}
completionField->buffer[ 0 ] = '\\';
}
#endif
if( completionArgument > 1 )
{
const char *baseCmd = Cmd_Argv( 0 );
char *p;
#ifndef DEDICATED
// This should always be true
if( baseCmd[ 0 ] == '\\' || baseCmd[ 0 ] == '/' )
baseCmd++;
#endif
if( ( p = Field_FindFirstSeparator( cmd ) ) )
Field_CompleteCommand( p + 1, qtrue, qtrue ); // Compound command
else
Cmd_CompleteArgument( baseCmd, cmd, completionArgument );
}
else
{
if( completionString[0] == '\\' || completionString[0] == '/' )
completionString++;
matchCount = 0;
shortestMatch[ 0 ] = 0;
if( strlen( completionString ) == 0 )
return;
if( doCommands )
Cmd_CommandCompletion( FindMatches );
if( doCvars )
Cvar_CommandCompletion( FindMatches );
if( !Field_Complete( ) )
{
// run through again, printing matches
if( doCommands )
Cmd_CommandCompletion( PrintMatches );
if( doCvars )
Cvar_CommandCompletion( PrintCvarMatches );
}
}
}
/*
===============
Field_AutoComplete
Perform Tab expansion
===============
*/
void Field_AutoComplete( field_t *field )
{
completionField = field;
Field_CompleteCommand( completionField->buffer, qtrue, qtrue );
}
/*
==================
Com_RandomBytes
fills string array with len random bytes, peferably from the OS randomizer
==================
*/
void Com_RandomBytes( byte *string, int len )
{
int i;
if( Sys_RandomBytes( string, len ) )
return;
Com_Printf( "Com_RandomBytes: using weak randomization\n" );
for( i = 0; i < len; i++ )
string[i] = (unsigned char)( rand() % 256 );
}
/*
==================
Com_IsVoipTarget
Returns non-zero if given clientNum is enabled in voipTargets, zero otherwise.
If clientNum is negative return if any bit is set.
==================
*/
qboolean Com_IsVoipTarget(uint8_t *voipTargets, int voipTargetsSize, int clientNum)
{
int index;
if(clientNum < 0)
{
for(index = 0; index < voipTargetsSize; index++)
{
if(voipTargets[index])
return qtrue;
}
return qfalse;
}
index = clientNum >> 3;
if(index < voipTargetsSize)
return (voipTargets[index] & (1 << (clientNum & 0x07)));
return qfalse;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3231_3 |
crossvul-cpp_data_bad_3151_1 | /*
* Copyright (C) 2014-2016 Firejail Authors
*
* This file is part of firejail 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "firejail.h"
#include <sys/mount.h>
#include <linux/limits.h>
#include <glob.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <grp.h>
static void skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
// zsh
if (arg_zsh) {
// copy skel files
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.zshrc", &s) == 0) {
if (is_link("/etc/skel/.zshrc")) {
fprintf(stderr, "Error: invalid /etc/skel/.zshrc file\n");
exit(1);
}
if (copy_file("/etc/skel/.zshrc", fname) == 0) {
if (chown(fname, u, g) == -1)
errExit("chown");
fs_logger("clone /etc/skel/.zshrc");
}
}
else { //
FILE *fp = fopen(fname, "w");
if (fp) {
fprintf(fp, "\n");
fclose(fp);
if (chown(fname, u, g) == -1)
errExit("chown");
if (chmod(fname, S_IRUSR | S_IWUSR) < 0)
errExit("chown");
fs_logger2("touch", fname);
}
}
free(fname);
}
// csh
else if (arg_csh) {
// copy skel files
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.cshrc", &s) == 0) {
if (is_link("/etc/skel/.cshrc")) {
fprintf(stderr, "Error: invalid /etc/skel/.cshrc file\n");
exit(1);
}
if (copy_file("/etc/skel/.cshrc", fname) == 0) {
if (chown(fname, u, g) == -1)
errExit("chown");
fs_logger("clone /etc/skel/.cshrc");
}
}
else { //
/* coverity[toctou] */
FILE *fp = fopen(fname, "w");
if (fp) {
fprintf(fp, "\n");
fclose(fp);
if (chown(fname, u, g) == -1)
errExit("chown");
if (chmod(fname, S_IRUSR | S_IWUSR) < 0)
errExit("chown");
fs_logger2("touch", fname);
}
}
free(fname);
}
// bash etc.
else {
// copy skel files
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.bashrc", &s) == 0) {
if (is_link("/etc/skel/.bashrc")) {
fprintf(stderr, "Error: invalid /etc/skel/.bashrc file\n");
exit(1);
}
if (copy_file("/etc/skel/.bashrc", fname) == 0) {
/* coverity[toctou] */
if (chown(fname, u, g) == -1)
errExit("chown");
fs_logger("clone /etc/skel/.bashrc");
}
}
free(fname);
}
}
static int store_xauthority(void) {
// put a copy of .Xauthority in XAUTHORITY_FILE
fs_build_mnt_dir();
char *src;
char *dest = RUN_XAUTHORITY_FILE;
// create an empty file
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0600);
fclose(fp);
}
if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Error: invalid .Xauthority file\n");
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
// drop privileges
drop_privs(0);
// copy, set permissions and ownership
int rv = copy_file(src, dest);
if (rv)
fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
if (chown(dest, getuid(), getgid()) == -1)
errExit("fchown");
if (chmod(dest, 0600) == -1)
errExit("fchmod");
return 1; // file copied
}
return 0;
}
static int store_asoundrc(void) {
// put a copy of .Xauthority in XAUTHORITY_FILE
fs_build_mnt_dir();
char *src;
char *dest = RUN_ASOUNDRC_FILE;
// create an empty file
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0644);
fclose(fp);
}
if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Error: invalid .asoundrc file\n");
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
// drop privileges
drop_privs(0);
// copy, set permissions and ownership
int rv = copy_file(src, dest);
if (rv)
fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
if (chown(dest, getuid(), getgid()) == -1)
errExit("fchown");
if (chmod(dest, 0644) == -1)
errExit("fchmod");
return 1; // file copied
}
return 0;
}
static void copy_xauthority(void) {
// copy XAUTHORITY_FILE in the new home directory
char *src = RUN_XAUTHORITY_FILE ;
char *dest;
if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
// if destination is a symbolic link, exit the sandbox!!!
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
// drop privileges
drop_privs(0);
// copy, set permissions and ownership
int rv = copy_file(src, dest);
if (rv)
fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
// set permissions and ownership
if (chown(dest, getuid(), getgid()) < 0)
errExit("chown");
if (chmod(dest, S_IRUSR | S_IWUSR) < 0)
errExit("chmod");
// delete the temporary file
unlink(src);
}
static void copy_asoundrc(void) {
// copy XAUTHORITY_FILE in the new home directory
char *src = RUN_ASOUNDRC_FILE ;
char *dest;
if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
// if destination is a symbolic link, exit the sandbox!!!
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
// drop privileges
drop_privs(0);
// copy, set permissions and ownership
int rv = copy_file(src, dest);
if (rv)
fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
// set permissions and ownership
if (chown(dest, getuid(), getgid()) < 0)
errExit("chown");
if (chmod(dest, S_IRUSR | S_IWUSR) < 0)
errExit("chmod");
// delete the temporary file
unlink(src);
}
// private mode (--private=homedir):
// mount homedir on top of /home/user,
// tmpfs on top of /root in nonroot mode,
// set skel files,
// restore .Xauthority
void fs_private_homedir(void) {
char *homedir = cfg.homedir;
char *private_homedir = cfg.home_private;
assert(homedir);
assert(private_homedir);
int xflag = store_xauthority();
int aflag = store_asoundrc();
uid_t u = getuid();
gid_t g = getgid();
struct stat s;
if (stat(homedir, &s) == -1) {
fprintf(stderr, "Error: cannot find user home directory\n");
exit(1);
}
// mount bind private_homedir on top of homedir
if (arg_debug)
printf("Mount-bind %s on top of %s\n", private_homedir, homedir);
if (mount(private_homedir, homedir, NULL, MS_BIND|MS_REC, NULL) < 0)
errExit("mount bind");
fs_logger3("mount-bind", private_homedir, cfg.homedir);
// preserve mode and ownership
// if (chown(homedir, s.st_uid, s.st_gid) == -1)
// errExit("mount-bind chown");
// if (chmod(homedir, s.st_mode) == -1)
// errExit("mount-bind chmod");
if (u != 0) {
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting home directory");
fs_logger("mount tmpfs on /root");
}
else {
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
fs_logger("mount tmpfs on /home");
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
// private mode (--private):
// mount tmpfs over /home/user,
// tmpfs on top of /root in nonroot mode,
// set skel files,
// restore .Xauthority
void fs_private(void) {
char *homedir = cfg.homedir;
assert(homedir);
uid_t u = getuid();
gid_t g = getgid();
int xflag = store_xauthority();
int aflag = store_asoundrc();
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
fs_logger("mount tmpfs on /home");
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting root directory");
fs_logger("mount tmpfs on /root");
if (u != 0) {
// create /home/user
if (arg_debug)
printf("Create a new user directory\n");
if (mkdir(homedir, S_IRWXU) == -1) {
if (mkpath_as_root(homedir) == -1)
errExit("mkpath");
if (mkdir(homedir, S_IRWXU) == -1)
errExit("mkdir");
}
if (chown(homedir, u, g) < 0)
errExit("chown");
fs_logger2("mkdir", homedir);
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
// check new private home directory (--private= option) - exit if it fails
void fs_check_private_dir(void) {
invalid_filename(cfg.home_private);
// Expand the home directory
char *tmp = expand_home(cfg.home_private, cfg.homedir);
cfg.home_private = realpath(tmp, NULL);
free(tmp);
if (!cfg.home_private
|| !is_dir(cfg.home_private)
|| is_link(cfg.home_private)
|| strstr(cfg.home_private, "..")) {
fprintf(stderr, "Error: invalid private directory\n");
exit(1);
}
// check home directory and chroot home directory have the same owner
struct stat s2;
int rv = stat(cfg.home_private, &s2);
if (rv < 0) {
fprintf(stderr, "Error: cannot find %s directory\n", cfg.home_private);
exit(1);
}
struct stat s1;
rv = stat(cfg.homedir, &s1);
if (rv < 0) {
fprintf(stderr, "Error: cannot find %s directory, full path name required\n", cfg.homedir);
exit(1);
}
if (s1.st_uid != s2.st_uid) {
printf("Error: --private directory should be owned by the current user\n");
exit(1);
}
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3151_1 |
crossvul-cpp_data_bad_3152_1 | /*
* Copyright (C) 2014-2016 Firejail Authors
*
* This file is part of firejail 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "firejail.h"
#include <sys/mount.h>
#include <linux/limits.h>
#include <glob.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <grp.h>
#include <ftw.h>
static void skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
// zsh
if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) {
// copy skel files
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.zshrc", &s) == 0) {
if (copy_file("/etc/skel/.zshrc", fname, u, g, 0644) == 0) {
fs_logger("clone /etc/skel/.zshrc");
}
}
else { //
FILE *fp = fopen(fname, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, u, g, S_IRUSR | S_IWUSR);
fclose(fp);
fs_logger2("touch", fname);
}
}
free(fname);
}
// csh
else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) {
// copy skel files
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.cshrc", &s) == 0) {
if (copy_file("/etc/skel/.cshrc", fname, u, g, 0644) == 0) {
fs_logger("clone /etc/skel/.cshrc");
}
}
else { //
/* coverity[toctou] */
FILE *fp = fopen(fname, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, u, g, S_IRUSR | S_IWUSR);
fclose(fp);
fs_logger2("touch", fname);
}
}
free(fname);
}
// bash etc.
else {
// copy skel files
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
// don't copy it if we already have the file
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.bashrc", &s) == 0) {
if (copy_file("/etc/skel/.bashrc", fname, u, g, 0644) == 0) {
fs_logger("clone /etc/skel/.bashrc");
}
}
free(fname);
}
}
static int store_xauthority(void) {
// put a copy of .Xauthority in XAUTHORITY_FILE
fs_build_mnt_dir();
char *src;
char *dest = RUN_XAUTHORITY_FILE;
// create an empty file
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0600);
fclose(fp);
}
if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Warning: invalid .Xauthority file\n");
return 0;
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
// drop privileges
drop_privs(0);
// copy, set permissions and ownership
int rv = copy_file(src, dest, getuid(), getgid(), 0600);
if (rv)
fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
return 1; // file copied
}
return 0;
}
static int store_asoundrc(void) {
// put a copy of .Xauthority in XAUTHORITY_FILE
fs_build_mnt_dir();
char *src;
char *dest = RUN_ASOUNDRC_FILE;
// create an empty file
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0644);
fclose(fp);
}
if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
// make sure the real path of the file is inside the home directory
/* coverity[toctou] */
char* rp = realpath(src, NULL);
if (!rp) {
fprintf(stderr, "Error: Cannot access %s\n", src);
exit(1);
}
if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n");
exit(1);
}
free(rp);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
// drop privileges
drop_privs(0);
// copy, set permissions and ownership
int rv = copy_file(src, dest, getuid(), getgid(), 0644);
if (rv)
fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
return 1; // file copied
}
return 0;
}
static void copy_xauthority(void) {
// copy XAUTHORITY_FILE in the new home directory
char *src = RUN_XAUTHORITY_FILE ;
char *dest;
if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
// if destination is a symbolic link, exit the sandbox!!!
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
// drop privileges
drop_privs(0);
// copy, set permissions and ownership
int rv = copy_file(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR);
if (rv)
fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
// delete the temporary file
unlink(src);
}
static void copy_asoundrc(void) {
// copy XAUTHORITY_FILE in the new home directory
char *src = RUN_ASOUNDRC_FILE ;
char *dest;
if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
// if destination is a symbolic link, exit the sandbox!!!
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
// drop privileges
drop_privs(0);
// copy, set permissions and ownership
int rv = copy_file(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR);
if (rv)
fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
// delete the temporary file
unlink(src);
}
// private mode (--private=homedir):
// mount homedir on top of /home/user,
// tmpfs on top of /root in nonroot mode,
// set skel files,
// restore .Xauthority
void fs_private_homedir(void) {
char *homedir = cfg.homedir;
char *private_homedir = cfg.home_private;
assert(homedir);
assert(private_homedir);
int xflag = store_xauthority();
int aflag = store_asoundrc();
uid_t u = getuid();
gid_t g = getgid();
struct stat s;
if (stat(homedir, &s) == -1) {
fprintf(stderr, "Error: cannot find user home directory\n");
exit(1);
}
// mount bind private_homedir on top of homedir
if (arg_debug)
printf("Mount-bind %s on top of %s\n", private_homedir, homedir);
if (mount(private_homedir, homedir, NULL, MS_NOSUID | MS_NODEV | MS_BIND | MS_REC, NULL) < 0)
errExit("mount bind");
fs_logger3("mount-bind", private_homedir, cfg.homedir);
fs_logger2("whitelist", cfg.homedir);
// preserve mode and ownership
// if (chown(homedir, s.st_uid, s.st_gid) == -1)
// errExit("mount-bind chown");
// if (chmod(homedir, s.st_mode) == -1)
// errExit("mount-bind chmod");
if (u != 0) {
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting home directory");
fs_logger("tmpfs /root");
}
else {
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
fs_logger("tmpfs /home");
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
// private mode (--private):
// mount tmpfs over /home/user,
// tmpfs on top of /root in nonroot mode,
// set skel files,
// restore .Xauthority
void fs_private(void) {
char *homedir = cfg.homedir;
assert(homedir);
uid_t u = getuid();
gid_t g = getgid();
int xflag = store_xauthority();
int aflag = store_asoundrc();
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
fs_logger("tmpfs /home");
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting root directory");
fs_logger("tmpfs /root");
if (u != 0) {
// create /home/user
if (arg_debug)
printf("Create a new user directory\n");
if (mkdir(homedir, S_IRWXU) == -1) {
if (mkpath_as_root(homedir) == -1)
errExit("mkpath");
if (mkdir(homedir, S_IRWXU) == -1)
errExit("mkdir");
}
if (chown(homedir, u, g) < 0)
errExit("chown");
fs_logger2("mkdir", homedir);
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
// check new private home directory (--private= option) - exit if it fails
void fs_check_private_dir(void) {
EUID_ASSERT();
invalid_filename(cfg.home_private);
// Expand the home directory
char *tmp = expand_home(cfg.home_private, cfg.homedir);
cfg.home_private = realpath(tmp, NULL);
free(tmp);
if (!cfg.home_private
|| !is_dir(cfg.home_private)
|| is_link(cfg.home_private)
|| strstr(cfg.home_private, "..")) {
fprintf(stderr, "Error: invalid private directory\n");
exit(1);
}
// check home directory and chroot home directory have the same owner
struct stat s2;
int rv = stat(cfg.home_private, &s2);
if (rv < 0) {
fprintf(stderr, "Error: cannot find %s directory\n", cfg.home_private);
exit(1);
}
struct stat s1;
rv = stat(cfg.homedir, &s1);
if (rv < 0) {
fprintf(stderr, "Error: cannot find %s directory, full path name required\n", cfg.homedir);
exit(1);
}
if (s1.st_uid != s2.st_uid) {
printf("Error: --private directory should be owned by the current user\n");
exit(1);
}
}
//***********************************************************************************
// --private-home
//***********************************************************************************
#define PRIVATE_COPY_LIMIT (500 * 1024 *1024)
static int size_limit_reached = 0;
static unsigned file_cnt = 0;
static unsigned size_cnt = 0;
static char *check_dir_or_file(const char *name);
int fs_copydir(const char *path, const struct stat *st, int ftype, struct FTW *sftw) {
(void) st;
(void) sftw;
if (size_limit_reached)
return 0;
struct stat s;
char *dest;
if (asprintf(&dest, "%s%s", RUN_HOME_DIR, path + strlen(cfg.homedir)) == -1)
errExit("asprintf");
// don't copy it if we already have the file
if (stat(dest, &s) == 0) {
free(dest);
return 0;
}
// extract mode and ownership
if (stat(path, &s) != 0) {
free(dest);
return 0;
}
// check uid
if (s.st_uid != firejail_uid || s.st_gid != firejail_gid) {
free(dest);
return 0;
}
if ((s.st_size + size_cnt) > PRIVATE_COPY_LIMIT) {
size_limit_reached = 1;
free(dest);
return 0;
}
file_cnt++;
size_cnt += s.st_size;
if(ftype == FTW_F)
copy_file(path, dest, firejail_uid, firejail_gid, s.st_mode);
else if (ftype == FTW_D) {
if (mkdir(dest, s.st_mode) == -1)
errExit("mkdir");
if (chmod(dest, s.st_mode) < 0) {
fprintf(stderr, "Error: cannot change mode for %s\n", path);
exit(1);
}
if (chown(dest, firejail_uid, firejail_gid) < 0) {
fprintf(stderr, "Error: cannot change ownership for %s\n", path);
exit(1);
}
#if 0
struct stat s2;
if (stat(dest, &s2) == 0) {
printf("%s\t", dest);
printf((S_ISDIR(s.st_mode)) ? "d" : "-");
printf((s.st_mode & S_IRUSR) ? "r" : "-");
printf((s.st_mode & S_IWUSR) ? "w" : "-");
printf((s.st_mode & S_IXUSR) ? "x" : "-");
printf((s.st_mode & S_IRGRP) ? "r" : "-");
printf((s.st_mode & S_IWGRP) ? "w" : "-");
printf((s.st_mode & S_IXGRP) ? "x" : "-");
printf((s.st_mode & S_IROTH) ? "r" : "-");
printf((s.st_mode & S_IWOTH) ? "w" : "-");
printf((s.st_mode & S_IXOTH) ? "x" : "-");
printf("\n");
}
#endif
fs_logger2("clone", path);
}
free(dest);
return(0);
}
static void duplicate(char *name) {
char *fname = check_dir_or_file(name);
if (arg_debug)
printf("Private home: duplicating %s\n", fname);
assert(strncmp(fname, cfg.homedir, strlen(cfg.homedir)) == 0);
struct stat s;
if (stat(fname, &s) == -1) {
free(fname);
return;
}
if(nftw(fname, fs_copydir, 1, FTW_PHYS) != 0) {
fprintf(stderr, "Error: unable to copy template dir\n");
exit(1);
}
fs_logger_print(); // save the current log
free(fname);
}
static char *check_dir_or_file(const char *name) {
assert(name);
struct stat s;
// basic checks
invalid_filename(name);
if (arg_debug)
printf("Private home: checking %s\n", name);
// expand home directory
char *fname = expand_home(name, cfg.homedir);
if (!fname) {
fprintf(stderr, "Error: file %s not found.\n", name);
exit(1);
}
// If it doesn't start with '/', it must be relative to homedir
if (fname[0] != '/') {
char* tmp;
if (asprintf(&tmp, "%s/%s", cfg.homedir, fname) == -1)
errExit("asprintf");
free(fname);
fname = tmp;
}
// check the file is in user home directory
char *rname = realpath(fname, NULL);
if (!rname) {
fprintf(stderr, "Error: invalid file %s\n", name);
exit(1);
}
if (strncmp(rname, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: file %s is not in user home directory\n", name);
exit(1);
}
// a full home directory is not allowed
if (strcmp(rname, cfg.homedir) == 0) {
fprintf(stderr, "Error: invalid directory %s\n", rname);
exit(1);
}
// only top files and directories in user home are allowed
char *ptr = rname + strlen(cfg.homedir);
if (*ptr == '\0') {
fprintf(stderr, "Error: invalid file %s\n", name);
exit(1);
}
ptr++;
ptr = strchr(ptr, '/');
if (ptr) {
if (*ptr != '\0') {
fprintf(stderr, "Error: only top files and directories in user home are allowed\n");
exit(1);
}
}
if (stat(fname, &s) == -1) {
fprintf(stderr, "Error: file %s not found.\n", fname);
exit(1);
}
// check uid
uid_t uid = getuid();
gid_t gid = getgid();
if (s.st_uid != uid || s.st_gid != gid) {
fprintf(stderr, "Error: only files or directories created by the current user are allowed.\n");
exit(1);
}
// dir or regular file
if (S_ISDIR(s.st_mode) || S_ISREG(s.st_mode)) {
free(fname);
return rname; // regular exit from the function
}
fprintf(stderr, "Error: invalid file type, %s.\n", fname);
exit(1);
}
// check directory list specified by user (--private-home option) - exit if it fails
void fs_check_home_list(void) {
if (strstr(cfg.home_private_keep, "..")) {
fprintf(stderr, "Error: invalid private-home list\n");
exit(1);
}
char *dlist = strdup(cfg.home_private_keep);
if (!dlist)
errExit("strdup");
char *ptr = strtok(dlist, ",");
char *tmp = check_dir_or_file(ptr);
free(tmp);
while ((ptr = strtok(NULL, ",")) != NULL) {
tmp = check_dir_or_file(ptr);
free(tmp);
}
free(dlist);
}
// private mode (--private-home=list):
// mount homedir on top of /home/user,
// tmpfs on top of /root in nonroot mode,
// tmpfs on top of /tmp in root mode,
// set skel files,
// restore .Xauthority
void fs_private_home_list(void) {
char *homedir = cfg.homedir;
char *private_list = cfg.home_private_keep;
assert(homedir);
assert(private_list);
int xflag = store_xauthority();
int aflag = store_asoundrc();
uid_t u = firejail_uid;
gid_t g = firejail_gid;
struct stat s;
if (stat(homedir, &s) == -1) {
fprintf(stderr, "Error: cannot find user home directory\n");
exit(1);
}
// create /run/firejail/mnt/home directory
fs_build_mnt_dir();
int rv = mkdir(RUN_HOME_DIR, 0755);
if (rv == -1)
errExit("mkdir");
if (chown(RUN_HOME_DIR, u, g) < 0)
errExit("chown");
if (chmod(RUN_HOME_DIR, 0755) < 0)
errExit("chmod");
ASSERT_PERMS(RUN_HOME_DIR, u, g, 0755);
fs_logger_print(); // save the current log
// copy the list of files in the new home directory
// using a new child process without root privileges
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
if (arg_debug)
printf("Copying files in the new home:\n");
// drop privileges
if (setgroups(0, NULL) < 0)
errExit("setgroups");
if (setgid(getgid()) < 0)
errExit("setgid/getgid");
if (setuid(getuid()) < 0)
errExit("setuid/getuid");
// copy the list of files in the new home directory
char *dlist = strdup(cfg.home_private_keep);
if (!dlist)
errExit("strdup");
char *ptr = strtok(dlist, ",");
duplicate(ptr);
while ((ptr = strtok(NULL, ",")) != NULL)
duplicate(ptr);
if (!arg_quiet) {
if (size_limit_reached)
fprintf(stderr, "Warning: private-home copy limit of %u MB reached, not all the files were copied\n",
PRIVATE_COPY_LIMIT / (1024 *1024));
else
printf("Private home: %u files, total size %u bytes\n", file_cnt, size_cnt);
}
fs_logger_print(); // save the current log
free(dlist);
_exit(0);
}
// wait for the child to finish
waitpid(child, NULL, 0);
if (arg_debug)
printf("Mount-bind %s on top of %s\n", RUN_HOME_DIR, homedir);
if (mount(RUN_HOME_DIR, homedir, NULL, MS_BIND|MS_REC, NULL) < 0)
errExit("mount bind");
if (u != 0) {
// mask /root
if (arg_debug)
printf("Mounting a new /root directory\n");
if (mount("tmpfs", "/root", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=700,gid=0") < 0)
errExit("mounting home directory");
}
else {
// mask /home
if (arg_debug)
printf("Mounting a new /home directory\n");
if (mount("tmpfs", "/home", "tmpfs", MS_NOSUID | MS_NODEV | MS_STRICTATIME | MS_REC, "mode=755,gid=0") < 0)
errExit("mounting home directory");
}
skel(homedir, u, g);
if (xflag)
copy_xauthority();
if (aflag)
copy_asoundrc();
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3152_1 |
crossvul-cpp_data_good_3233_1 | /*
===========================================================================
Return to Castle Wolfenstein multiplayer GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (RTCW MP Source Code).
RTCW MP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW MP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW MP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
/*****************************************************************************
* name: files.c
*
* desc: handle based filesystem for Quake III Arena
*
*
*****************************************************************************/
#include "q_shared.h"
#include "qcommon.h"
#include "../zlib-1.2.8/unzip.h"
/*
=============================================================================
QUAKE3 FILESYSTEM
All of Quake's data access is through a hierarchical file system, but the contents of
the file system can be transparently merged from several sources.
A "qpath" is a reference to game file data. MAX_ZPATH is 256 characters, which must include
a terminating zero. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any
references outside the quake directory system.
The "base path" is the path to the directory holding all the game directories and usually
the executable. It defaults to ".", but can be overridden with a "+set fs_basepath c:\quake3"
command line to allow code debugging in a different directory. Basepath cannot
be modified at all after startup. Any files that are created (demos, screenshots,
etc) will be created relative to the base path, so base path should usually be writable.
The "home path" is the path used for all write access. On win32 systems we have "base path"
== "home path", but on *nix systems the base installation is usually readonly, and
"home path" points to ~/.q3a or similar
The user can also install custom mods and content in "home path", so it should be searched
along with "home path" and "cd path" for game content.
The "base game" is the directory under the paths where data comes from by default, and
can be either "baseq3" or "demoq3".
The "current game" may be the same as the base game, or it may be the name of another
directory under the paths that should be searched for files before looking in the base game.
This is the basis for addons.
Clients automatically set the game directory after receiving a gamestate from a server,
so only servers need to worry about +set fs_game.
No other directories outside of the base game and current game will ever be referenced by
filesystem functions.
To save disk space and speed loading, directory trees can be collapsed into zip files.
The files use a ".pk3" extension to prevent users from unzipping them accidentally, but
otherwise the are simply normal uncompressed zip files. A game directory can have multiple
zip files of the form "pak0.pk3", "pak1.pk3", etc. Zip files are searched in decending order
from the highest number to the lowest, and will always take precedence over the filesystem.
This allows a pk3 distributed as a patch to override all existing data.
Because we will have updated executables freely available online, there is no point to
trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
should be exactly the same executables as release versions, but with different data that
automatically restricts where game media can come from to prevent add-ons from working.
File search order: when FS_FOpenFileRead gets called it will go through the fs_searchpaths
structure and stop on the first successful hit. fs_searchpaths is built with successive
calls to FS_AddGameDirectory
Additionaly, we search in several subdirectories:
current game is the current mode
base game is a variable to allow mods based on other mods
(such as baseq3 + missionpack content combination in a mod for instance)
BASEGAME is the hardcoded base game ("baseq3")
e.g. the qpath "sound/newstuff/test.wav" would be searched for in the following places:
home path + current game's zip files
home path + current game's directory
base path + current game's zip files
base path + current game's directory
cd path + current game's zip files
cd path + current game's directory
home path + base game's zip file
home path + base game's directory
base path + base game's zip file
base path + base game's directory
cd path + base game's zip file
cd path + base game's directory
home path + BASEGAME's zip file
home path + BASEGAME's directory
base path + BASEGAME's zip file
base path + BASEGAME's directory
cd path + BASEGAME's zip file
cd path + BASEGAME's directory
server download, to be written to home path + current game's directory
The filesystem can be safely shutdown and reinitialized with different
basedir / cddir / game combinations, but all other subsystems that rely on it
(sound, video) must also be forced to restart.
Because the same files are loaded by both the clip model (CM_) and renderer (TR_)
subsystems, a simple single-file caching scheme is used. The CM_ subsystems will
load the file with a request to cache. Only one file will be kept cached at a time,
so any models that are going to be referenced by both subsystems should alternate
between the CM_ load function and the ref load function.
TODO: A qpath that starts with a leading slash will always refer to the base game, even if another
game is currently active. This allows character models, skins, and sounds to be downloaded
to a common directory no matter which game is active.
How to prevent downloading zip files?
Pass pk3 file names in systeminfo, and download before FS_Restart()?
Aborting a download disconnects the client from the server.
How to mark files as downloadable? Commercial add-ons won't be downloadable.
Non-commercial downloads will want to download the entire zip file.
the game would have to be reset to actually read the zip in
Auto-update information
Path separators
Casing
separate server gamedir and client gamedir, so if the user starts
a local game after having connected to a network game, it won't stick
with the network game.
allow menu options for game selection?
Read / write config to floppy option.
Different version coexistance?
When building a pak file, make sure a wolfconfig.cfg isn't present in it,
or configs will never get loaded from disk!
todo:
downloading (outside fs?)
game directory passing and restarting
=============================================================================
*/
// TTimo: moved to qcommon.h
// NOTE: could really do with a cvar
//#define BASEGAME "main"
//#define DEMOGAME "demomain"
// every time a new demo pk3 file is built, this checksum must be updated.
// the easiest way to get it is to just run the game and see what it spits out
//DHM - Nerve :: Wolf Multiplayer demo checksum
// NOTE TTimo: always needs the 'u' for unsigned int (gcc)
#define DEMO_PAK0_CHECKSUM 2031778175u
static const unsigned int pak_checksums[] = {
1886207346u
};
static const unsigned int mppak_checksums[] = {
764840216u,
-1023558518u,
125907563u,
131270674u,
-137448799u,
2149774797u
};
#define MAX_ZPATH 256
#define MAX_SEARCH_PATHS 4096
#define MAX_FILEHASH_SIZE 1024
typedef struct fileInPack_s {
char *name; // name of the file
unsigned long pos; // file info position in zip
unsigned long len; // uncompress file size
struct fileInPack_s* next; // next file in the hash
} fileInPack_t;
typedef struct {
char pakPathname[MAX_OSPATH]; // c:\quake3\baseq3
char pakFilename[MAX_OSPATH]; // c:\quake3\baseq3\pak0.pk3
char pakBasename[MAX_OSPATH]; // pak0
char pakGamename[MAX_OSPATH]; // baseq3
unzFile handle; // handle to zip file
int checksum; // regular checksum
int pure_checksum; // checksum for pure
int numfiles; // number of files in pk3
int referenced; // referenced file flags
int hashSize; // hash table size (power of 2)
fileInPack_t* *hashTable; // hash table
fileInPack_t* buildBuffer; // buffer with the filenames etc.
} pack_t;
typedef struct {
char path[MAX_OSPATH]; // c:\quake3
char fullpath[MAX_OSPATH]; // c:\quake3\baseq3
char gamedir[MAX_OSPATH]; // baseq3
qboolean allowUnzippedDLLs; // whether to load unzipped dlls from directory
} directory_t;
typedef struct searchpath_s {
struct searchpath_s *next;
pack_t *pack; // only one of pack / dir will be non NULL
directory_t *dir;
} searchpath_t;
static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators
static cvar_t *fs_debug;
static cvar_t *fs_homepath;
#ifdef __APPLE__
// Also search the .app bundle for .pk3 files
static cvar_t *fs_apppath;
#endif
#ifndef STANDALONE
static cvar_t *fs_steampath;
#endif
static cvar_t *fs_basepath;
static cvar_t *fs_basegame;
static cvar_t *fs_gamedirvar;
static searchpath_t *fs_searchpaths;
static int fs_readCount; // total bytes read
static int fs_loadCount; // total files read
static int fs_loadStack; // total files in memory
static int fs_packFiles = 0; // total number of files in packs
static int fs_checksumFeed;
typedef union qfile_gus {
FILE* o;
unzFile z;
} qfile_gut;
typedef struct qfile_us {
qfile_gut file;
qboolean unique;
} qfile_ut;
typedef struct {
qfile_ut handleFiles;
qboolean handleSync;
int fileSize;
int zipFilePos;
int zipFileLen;
qboolean zipFile;
qboolean streamed;
char name[MAX_ZPATH];
} fileHandleData_t;
static fileHandleData_t fsh[MAX_FILE_HANDLES];
// TTimo - show_bug.cgi?id=540
// wether we did a reorder on the current search path when joining the server
static qboolean fs_reordered;
// never load anything from pk3 files that are not present at the server when pure
// ex: when fs_numServerPaks != 0, FS_FOpenFileRead won't load anything outside of pk3 except .cfg .menu .game .dat
static int fs_numServerPaks = 0;
static int fs_serverPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverPakNames[MAX_SEARCH_PATHS]; // pk3 names
// only used for autodownload, to make sure the client has at least
// all the pk3 files that are referenced at the server side
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS]; // checksums
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS]; // pk3 names
// last valid game folder used
char lastValidBase[MAX_OSPATH];
char lastValidComBaseGame[MAX_OSPATH];
char lastValidFsBaseGame[MAX_OSPATH];
char lastValidGame[MAX_OSPATH];
#ifdef FS_MISSING
FILE* missingFiles = NULL;
#endif
/* C99 defines __func__ */
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2 || _MSC_VER >= 1300
# define __func__ __FUNCTION__
# else
# define __func__ "(unknown)"
# endif
#endif
/*
==============
FS_Initialized
==============
*/
qboolean FS_Initialized( void ) {
return ( fs_searchpaths != NULL );
}
/*
=================
FS_PakIsPure
=================
*/
qboolean FS_PakIsPure( pack_t *pack ) {
int i;
if ( fs_numServerPaks ) {
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
// FIXME: also use hashed file names
// NOTE TTimo: a pk3 with same checksum but different name would be validated too
// I don't see this as allowing for any exploit, it would only happen if the client does manips of its file names 'not a bug'
if ( pack->checksum == fs_serverPaks[i] ) {
return qtrue; // on the approved list
}
}
return qfalse; // not on the pure server pak list
}
return qtrue;
}
/*
=================
FS_LoadStack
return load stack
=================
*/
int FS_LoadStack( void ) {
return fs_loadStack;
}
/*
================
return a hash value for the filename
================
*/
static long FS_HashFileName( const char *fname, int hashSize ) {
int i;
long hash;
char letter;
hash = 0;
i = 0;
while ( fname[i] != '\0' ) {
letter = tolower( fname[i] );
if ( letter == '.' ) {
break; // don't include extension
}
if ( letter == '\\' ) {
letter = '/'; // damn path names
}
if ( letter == PATH_SEP ) {
letter = '/'; // damn path names
}
hash += (long)( letter ) * ( i + 119 );
i++;
}
hash = ( hash ^ ( hash >> 10 ) ^ ( hash >> 20 ) );
hash &= ( hashSize - 1 );
return hash;
}
static fileHandle_t FS_HandleForFile( void ) {
int i;
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o == NULL ) {
return i;
}
}
Com_Error( ERR_DROP, "FS_HandleForFile: none free" );
return 0;
}
static FILE *FS_FileForHandle( fileHandle_t f ) {
if ( f < 1 || f >= MAX_FILE_HANDLES ) {
Com_Error( ERR_DROP, "FS_FileForHandle: out of range" );
}
if ( fsh[f].zipFile == qtrue ) {
Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" );
}
if ( !fsh[f].handleFiles.file.o ) {
Com_Error( ERR_DROP, "FS_FileForHandle: NULL" );
}
return fsh[f].handleFiles.file.o;
}
void FS_ForceFlush( fileHandle_t f ) {
FILE *file;
file = FS_FileForHandle( f );
setvbuf( file, NULL, _IONBF, 0 );
}
/*
================
FS_fplength
================
*/
long FS_fplength(FILE *h)
{
long pos;
long end;
pos = ftell(h);
fseek(h, 0, SEEK_END);
end = ftell(h);
fseek(h, pos, SEEK_SET);
return end;
}
/*
================
FS_filelength
If this is called on a non-unique FILE (from a pak file),
it will return the size of the pak file, not the expected
size of the file.
================
*/
long FS_filelength(fileHandle_t f)
{
FILE *h;
h = FS_FileForHandle(f);
if(h == NULL)
return -1;
else
return FS_fplength(h);
}
/*
====================
FS_ReplaceSeparators
Fix things up differently for win/unix/mac
====================
*/
static void FS_ReplaceSeparators( char *path ) {
char *s;
qboolean lastCharWasSep = qfalse;
for ( s = path ; *s ; s++ ) {
if ( *s == '/' || *s == '\\' ) {
if ( !lastCharWasSep ) {
*s = PATH_SEP;
lastCharWasSep = qtrue;
} else {
memmove (s, s + 1, strlen (s));
}
} else {
lastCharWasSep = qfalse;
}
}
}
/*
===================
FS_BuildOSPath
Qpath may have either forward or backwards slashes
===================
*/
char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) {
char temp[MAX_OSPATH];
static char ospath[2][MAX_OSPATH];
static int toggle;
toggle ^= 1; // flip-flop to allow two returns without clash
if ( !game || !game[0] ) {
game = fs_gamedir;
}
Com_sprintf( temp, sizeof( temp ), "/%s/%s", game, qpath );
FS_ReplaceSeparators( temp );
Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp );
return ospath[toggle];
}
/*
============
FS_CreatePath
Creates any directories needed to store the given filename
============
*/
qboolean FS_CreatePath( char *OSPath ) {
char *ofs;
char path[MAX_OSPATH];
// make absolutely sure that it can't back up the path
// FIXME: is c: allowed???
if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) {
Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath );
return qtrue;
}
Q_strncpyz( path, OSPath, sizeof( path ) );
FS_ReplaceSeparators( path );
// Skip creation of the root directory as it will always be there
ofs = strchr( path, PATH_SEP );
if ( ofs != NULL ) {
ofs++;
}
for (; ofs != NULL && *ofs ; ofs++) {
if (*ofs == PATH_SEP) {
// create the directory
*ofs = 0;
if (!Sys_Mkdir (path)) {
Com_Error( ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"",
path );
}
*ofs = PATH_SEP;
}
}
return qfalse;
}
/*
=================
FS_CheckFilenameIsMutable
ERR_FATAL if trying to maniuplate a file with the platform library, QVM, or pk3 extension
=================
*/
static void FS_CheckFilenameIsMutable( const char *filename,
const char *function )
{
// Check if the filename ends with the library, QVM, or pk3 extension
if( COM_CompareExtension( filename, DLL_EXT )
|| COM_CompareExtension( filename, ".qvm" )
|| COM_CompareExtension( filename, ".pk3" ) )
{
Com_Error( ERR_FATAL, "%s: Not allowed to manipulate '%s' due "
"to %s extension", function, filename, COM_GetExtension( filename ) );
}
}
/*
===========
FS_Remove
===========
*/
void FS_Remove( const char *osPath ) {
FS_CheckFilenameIsMutable( osPath, __func__ );
remove( osPath );
}
/*
===========
FS_HomeRemove
===========
*/
void FS_HomeRemove( const char *homePath ) {
FS_CheckFilenameIsMutable( homePath, __func__ );
remove( FS_BuildOSPath( fs_homepath->string,
fs_gamedir, homePath ) );
}
/*
================
FS_FileInPathExists
Tests if path and file exists
================
*/
qboolean FS_FileInPathExists(const char *testpath)
{
FILE *filep;
filep = Sys_FOpen(testpath, "rb");
if(filep)
{
fclose(filep);
return qtrue;
}
return qfalse;
}
/*
================
FS_FileExists
Tests if the file exists in the current gamedir, this DOES NOT
search the paths. This is to determine if opening a file to write
(which always goes into the current gamedir) will cause any overwrites.
NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards
================
*/
qboolean FS_FileExists(const char *file)
{
return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file));
}
/*
================
FS_SV_FileExists
Tests if the file exists
================
*/
qboolean FS_SV_FileExists( const char *file )
{
char *testpath;
testpath = FS_BuildOSPath( fs_homepath->string, file, "");
testpath[strlen(testpath)-1] = '\0';
return FS_FileInPathExists(testpath);
}
/*
===========
FS_SV_FOpenFileWrite
===========
*/
fileHandle_t FS_SV_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileWrite: %s\n", ospath );
}
// FS_CheckFilenameIsMutable( ospath, __func__ );
if( FS_CreatePath( ospath ) ) {
return 0;
}
Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o) {
f = 0;
}
return f;
}
/*
===========
FS_SV_FOpenFileRead
Search for a file somewhere below the home path then base path
in that order
===========
*/
long FS_SV_FOpenFileRead( const char *filename, fileHandle_t *fp ) {
char *ospath;
fileHandle_t f = 0;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
// S_ClearSoundBuffer();
// search homepath
ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
// remove trailing slash
ospath[strlen( ospath ) - 1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
if (!fsh[f].handleFiles.file.o)
{
// If fs_homepath == fs_basepath, don't bother
if (Q_stricmp(fs_homepath->string,fs_basepath->string))
{
// search basepath
ospath = FS_BuildOSPath( fs_basepath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
#ifndef STANDALONE
// Check fs_steampath too
if (!fsh[f].handleFiles.file.o && fs_steampath->string[0])
{
ospath = FS_BuildOSPath( fs_steampath->string, filename, "" );
ospath[strlen(ospath)-1] = '\0';
if ( fs_debug->integer )
{
Com_Printf( "FS_SV_FOpenFileRead (fs_steampath): %s\n", ospath );
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
fsh[f].handleSync = qfalse;
}
#endif
if ( !fsh[f].handleFiles.file.o )
{
f = 0;
}
}
*fp = f;
if ( f ) {
return FS_filelength( f );
}
return -1;
}
/*
===========
FS_SV_Rename
===========
*/
void FS_SV_Rename( const char *from, const char *to, qboolean safe ) {
char *from_ospath, *to_ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
// don't let sound stutter
// S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, from, "" );
to_ospath = FS_BuildOSPath( fs_homepath->string, to, "" );
from_ospath[strlen( from_ospath ) - 1] = '\0';
to_ospath[strlen( to_ospath ) - 1] = '\0';
if ( fs_debug->integer ) {
Com_Printf( "FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath );
}
if ( safe ) {
FS_CheckFilenameIsMutable( to_ospath, __func__ );
}
rename(from_ospath, to_ospath);
}
/*
===========
FS_Rename
===========
*/
void FS_Rename( const char *from, const char *to ) {
char *from_ospath, *to_ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
// don't let sound stutter
// S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from );
to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to );
if ( fs_debug->integer ) {
Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath );
}
FS_CheckFilenameIsMutable( to_ospath, __func__ );
rename(from_ospath, to_ospath);
}
/*
==============
FS_FCloseFile
If the FILE pointer is an open pak file, leave it open.
For some reason, other dll's can't just cal fclose()
on files returned by FS_FOpenFile...
==============
*/
void FS_FCloseFile( fileHandle_t f ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( fsh[f].zipFile == qtrue ) {
unzCloseCurrentFile( fsh[f].handleFiles.file.z );
if ( fsh[f].handleFiles.unique ) {
unzClose( fsh[f].handleFiles.file.z );
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
return;
}
// we didn't find it as a pak, so close it as a unique file
if ( fsh[f].handleFiles.file.o ) {
fclose( fsh[f].handleFiles.file.o );
}
Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
}
/*
===========
FS_FOpenFileWrite
===========
*/
fileHandle_t FS_FOpenFileWrite( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileWrite: %s\n", ospath );
}
// FS_CheckFilenameIsMutable( ospath, __func__ );
if ( FS_CreatePath( ospath ) ) {
return 0;
}
// enabling the following line causes a recursive function call loop
// when running with +set logfile 1 +set developer 1
//Com_DPrintf( "writing to: %s\n", ospath );
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "wb" );
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
fsh[f].handleSync = qfalse;
if ( !fsh[f].handleFiles.file.o ) {
f = 0;
}
return f;
}
/*
===========
FS_FOpenFileAppend
===========
*/
fileHandle_t FS_FOpenFileAppend( const char *filename ) {
char *ospath;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
// S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FOpenFileAppend: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
if ( FS_CreatePath( ospath ) ) {
return 0;
}
fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "ab" );
fsh[f].handleSync = qfalse;
if ( !fsh[f].handleFiles.file.o ) {
f = 0;
}
return f;
}
/*
===========
FS_FCreateOpenPipeFile
===========
*/
fileHandle_t FS_FCreateOpenPipeFile( const char *filename ) {
char *ospath;
FILE *fifo;
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
f = FS_HandleForFile();
fsh[f].zipFile = qfalse;
Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
// don't let sound stutter
// S_ClearSoundBuffer();
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( fs_debug->integer ) {
Com_Printf( "FS_FCreateOpenPipeFile: %s\n", ospath );
}
FS_CheckFilenameIsMutable( ospath, __func__ );
fifo = Sys_Mkfifo( ospath );
if( fifo ) {
fsh[f].handleFiles.file.o = fifo;
fsh[f].handleSync = qfalse;
}
else
{
Com_Printf( S_COLOR_YELLOW "WARNING: Could not create new com_pipefile at %s. "
"com_pipefile will not be used.\n", ospath );
f = 0;
}
return f;
}
/*
===========
FS_FilenameCompare
Ignore case and seprator char distinctions
===========
*/
qboolean FS_FilenameCompare( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if ( c1 >= 'a' && c1 <= 'z' ) {
c1 -= ( 'a' - 'A' );
}
if ( c2 >= 'a' && c2 <= 'z' ) {
c2 -= ( 'a' - 'A' );
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if ( c1 != c2 ) {
return qtrue; // strings not equal
}
} while ( c1 );
return qfalse; // strings are equal
}
/*
===========
FS_IsExt
Return qtrue if ext matches file extension filename
===========
*/
qboolean FS_IsExt(const char *filename, const char *ext, int namelen)
{
int extlen;
extlen = strlen(ext);
if(extlen > namelen)
return qfalse;
filename += namelen - extlen;
return !Q_stricmp(filename, ext);
}
/*
===========
FS_IsDemoExt
Return qtrue if filename has a demo extension
===========
*/
qboolean FS_IsDemoExt(const char *filename, int namelen)
{
char *ext_test;
int index, protocol;
ext_test = strrchr(filename, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMOEXT, ARRAY_LEN(DEMOEXT) - 1))
{
protocol = atoi(ext_test + ARRAY_LEN(DEMOEXT));
if(protocol == com_protocol->integer)
return qtrue;
#ifdef LEGACY_PROTOCOL
if(protocol == com_legacyprotocol->integer)
return qtrue;
#endif
for(index = 0; demo_protocols[index]; index++)
{
if(demo_protocols[index] == protocol)
return qtrue;
}
}
return qfalse;
}
/*
===========
FS_ShiftedStrStr
===========
*/
char *FS_ShiftedStrStr( const char *string, const char *substring, int shift ) {
char buf[MAX_STRING_TOKENS];
int i;
for ( i = 0; substring[i]; i++ ) {
buf[i] = substring[i] + shift;
}
buf[i] = '\0';
return strstr( string, buf );
}
/*
==========
FS_ShiftStr
perform simple string shifting to avoid scanning from the exe
==========
*/
char *FS_ShiftStr( const char *string, int shift ) {
static char buf[MAX_STRING_CHARS];
int i,l;
l = strlen( string );
for ( i = 0; i < l; i++ ) {
buf[i] = string[i] + shift;
}
buf[i] = '\0';
return buf;
}
/*
===========
FS_FOpenFileReadDir
Tries opening file "filename" in searchpath "search"
Returns filesize and an open FILE pointer.
===========
*/
extern qboolean com_fullyInitialized;
// see FS_FOpenFileRead_Filtered
static int fs_filter_flag = 0;
long FS_FOpenFileReadDir(const char *filename, searchpath_t *search, fileHandle_t *file, qboolean uniqueFILE, qboolean unpure)
{
long hash;
pack_t *pak;
fileInPack_t *pakFile;
directory_t *dir;
char *netpath;
FILE *filep;
int len;
if(filename == NULL)
Com_Error(ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed");
// qpaths are not supposed to have a leading slash
if(filename[0] == '/' || filename[0] == '\\')
filename++;
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if(strstr(filename, ".." ) || strstr(filename, "::"))
{
if(file == NULL)
return qfalse;
*file = 0;
return -1;
}
// make sure the rtcwkey file is only readable by the WolfMP.exe at initialization
// any other time the key should only be accessed in memory using the provided functions
if(com_fullyInitialized && strstr(filename, "rtcwkey"))
{
if(file == NULL)
return qfalse;
*file = 0;
return -1;
}
if(file == NULL)
{
// just wants to see if file is there
// is the element a pak file?
if(search->pack)
{
hash = FS_HashFileName(filename, search->pack->hashSize);
if(search->pack->hashTable[hash] && !(fs_filter_flag & FS_EXCLUDE_PK3))
{
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do
{
// case and separator insensitive comparisons
if(!FS_FilenameCompare(pakFile->name, filename))
{
// found it!
if(pakFile->len)
return pakFile->len;
else
{
// It's not nice, but legacy code depends
// on positive value if file exists no matter
// what size
return 1;
}
}
pakFile = pakFile->next;
} while(pakFile != NULL);
}
}
else if(search->dir && !(fs_filter_flag & FS_EXCLUDE_DIR))
{
dir = search->dir;
netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
filep = Sys_FOpen(netpath, "rb");
if(filep)
{
len = FS_fplength(filep);
fclose(filep);
if(len)
return len;
else
return 1;
}
}
return 0;
}
*file = FS_HandleForFile();
fsh[*file].handleFiles.unique = uniqueFILE;
// is the element a pak file?
if(search->pack)
{
hash = FS_HashFileName(filename, search->pack->hashSize);
if(search->pack->hashTable[hash] && !(fs_filter_flag & FS_EXCLUDE_PK3))
{
// disregard if it doesn't match one of the allowed pure pak files
if(!unpure && !FS_PakIsPure(search->pack))
{
*file = 0;
return -1;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do
{
// case and separator insensitive comparisons
if(!FS_FilenameCompare(pakFile->name, filename))
{
// found it!
// Mark the pak as having been referenced and mark specifics on cgame and ui.
// Shaders, txt, and arena files by themselves do not count as a reference as
// these are loaded from all pk3s
len = strlen(filename);
if (!(pak->referenced & FS_GENERAL_REF))
{
if(!FS_IsExt(filename, ".shader", len) &&
!FS_IsExt(filename, ".txt", len) &&
!FS_IsExt(filename, ".cfg", len) &&
!FS_IsExt(filename, ".config", len) &&
!FS_IsExt(filename, ".bot", len) &&
!FS_IsExt(filename, ".arena", len) &&
!FS_IsExt(filename, ".menu", len) &&
// Q_stricmp(filename, "vm/qagame.qvm") != 0 && // Commented out for now
!strstr(filename, "levelshots"))
{
pak->referenced |= FS_GENERAL_REF;
}
}
if(strstr(filename, Sys_GetDLLName( "cgame" )))
pak->referenced |= FS_CGAME_REF;
if(strstr(filename, Sys_GetDLLName( "ui" )))
pak->referenced |= FS_UI_REF;
if(strstr(filename, "cgame.mp.qvm"))
pak->referenced |= FS_CGAME_REF;
if(strstr(filename, "ui.mp.qvm"))
pak->referenced |= FS_UI_REF;
// DHM -- Nerve :: Don't allow singleplayer maps to be loaded from pak0
if ( Q_stricmp( filename + len - 4, ".bsp" ) == 0 &&
Q_stricmp( pak->pakBasename, "pak0" ) == 0 ) {
*file = 0;
return -1;
}
if(uniqueFILE)
{
// open a new file on the pakfile
fsh[*file].handleFiles.file.z = unzOpen(pak->pakFilename);
if(fsh[*file].handleFiles.file.z == NULL)
Com_Error(ERR_FATAL, "Couldn't open %s", pak->pakFilename);
}
else
fsh[*file].handleFiles.file.z = pak->handle;
Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
fsh[*file].zipFile = qtrue;
// set the file position in the zip file (also sets the current file info)
unzSetOffset(fsh[*file].handleFiles.file.z, pakFile->pos);
// open the file in the zip
unzOpenCurrentFile(fsh[*file].handleFiles.file.z);
fsh[*file].zipFilePos = pakFile->pos;
fsh[*file].zipFileLen = pakFile->len;
if(fs_debug->integer)
{
Com_Printf("FS_FOpenFileRead: %s (found in '%s')\n",
filename, pak->pakFilename);
}
return pakFile->len;
}
pakFile = pakFile->next;
} while(pakFile != NULL);
}
}
else if(search->dir && !(fs_filter_flag & FS_EXCLUDE_DIR))
{
// check a file in the directory tree
// if we are running restricted, the only files we
// will allow to come from the directory are .cfg files
len = strlen(filename);
// FIXME TTimo I'm not sure about the fs_numServerPaks test
// if you are using FS_ReadFile to find out if a file exists,
// this test can make the search fail although the file is in the directory
// I had the problem on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8
// turned out I used FS_FileExists instead
if(!unpure && fs_numServerPaks)
{
if(!FS_IsExt(filename, ".cfg", len) && // for config files
!FS_IsExt(filename, ".menu", len) && // menu files
!FS_IsExt(filename, ".game", len) && // menu files
!FS_IsExt(filename, ".dat", len) && // for journal files
!FS_IsDemoExt(filename, len)) // demos
{
*file = 0;
return -1;
}
}
dir = search->dir;
netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
filep = Sys_FOpen(netpath, "rb");
if (filep == NULL)
{
*file = 0;
return -1;
}
Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
fsh[*file].zipFile = qfalse;
if(fs_debug->integer)
{
Com_Printf("FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename,
dir->path, PATH_SEP, dir->gamedir);
}
fsh[*file].handleFiles.file.o = filep;
return FS_fplength(filep);
}
*file = 0;
return -1;
}
/*
===========
FS_FOpenFileRead
Finds the file in the search path.
Returns filesize and an open FILE pointer.
Used for streaming data out of either a
separate file or a ZIP file.
===========
*/
long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE)
{
searchpath_t *search;
long len;
qboolean isLocalConfig;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
isLocalConfig = !strcmp(filename, "autoexec.cfg") || !strcmp(filename, Q3CONFIG_CFG);
for(search = fs_searchpaths; search; search = search->next)
{
// autoexec.cfg and wolfconfig_mp.cfg can only be loaded outside of pk3 files.
if (isLocalConfig && search->pack)
continue;
len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse);
if(file == NULL)
{
if(len > 0)
return len;
}
else
{
if(len >= 0 && *file)
return len;
}
}
#ifdef FS_MISSING
if(missingFiles)
fprintf(missingFiles, "%s\n", filename);
#endif
if(file)
{
*file = 0;
return -1;
}
else
{
// When file is NULL, we're querying the existance of the file
// If we've got here, it doesn't exist
return 0;
}
}
int FS_FOpenFileRead_Filtered( const char *qpath, fileHandle_t *file, qboolean uniqueFILE, int filter_flag ) {
int ret;
fs_filter_flag = filter_flag;
ret = FS_FOpenFileRead( qpath, file, uniqueFILE );
fs_filter_flag = 0;
return ret;
}
/*
=================
FS_FindVM
Find a suitable VM file in search path order.
In each searchpath try:
- open DLL file
- open QVM file if QVM loading enabled
write found DLL or QVM to "found" and return VMI_NATIVE if DLL, VMI_COMPILED if QVM
Return the searchpath in "startSearch".
=================
*/
int FS_FindVM(void **startSearch, char *found, int foundlen, const char *name, qboolean unpure, int enableQvm)
{
searchpath_t *search, *lastSearch;
directory_t *dir;
pack_t *pack;
char dllName[MAX_OSPATH], qvmName[MAX_OSPATH];
char *netpath;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
if(enableQvm)
Com_sprintf(qvmName, sizeof(qvmName), "vm/%s.mp.qvm", name);
Q_strncpyz(dllName, Sys_GetDLLName(name), sizeof(dllName));
lastSearch = *startSearch;
if(*startSearch == NULL)
search = fs_searchpaths;
else
search = lastSearch->next;
while(search)
{
if(search->dir && (unpure || !Q_stricmp(name, "qagame")))
{
dir = search->dir;
netpath = FS_BuildOSPath(dir->path, dir->gamedir, dllName);
if(enableQvm && FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, unpure) > 0)
{
*startSearch = search;
return VMI_COMPILED;
}
if(dir->allowUnzippedDLLs && FS_FileInPathExists(netpath))
{
Q_strncpyz(found, netpath, foundlen);
*startSearch = search;
return VMI_NATIVE;
}
}
else if(search->pack)
{
pack = search->pack;
if(lastSearch && lastSearch->pack)
{
// make sure we only try loading one VM file per game dir
// i.e. if VM from pak7.pk3 fails we won't try one from pak6.pk3
if(!FS_FilenameCompare(lastSearch->pack->pakPathname, pack->pakPathname))
{
search = search->next;
continue;
}
}
if(enableQvm && FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, unpure) > 0)
{
*startSearch = search;
return VMI_COMPILED;
}
#ifndef DEDICATED
// extract the dlls from the mp_bin.pk3 so
// that they can be referenced
if (Q_stricmp(name, "qagame"))
{
netpath = FS_BuildOSPath(fs_homepath->string, pack->pakGamename, dllName);
if (FS_FOpenFileReadDir(dllName, search, NULL, qfalse, unpure) > 0
&& FS_CL_ExtractFromPakFile(search, netpath, dllName, NULL))
{
Com_Printf( "Loading %s dll from %s\n", name, pack->pakFilename );
Q_strncpyz(found, netpath, foundlen);
*startSearch = search;
return VMI_NATIVE;
}
}
#endif
}
search = search->next;
}
return -1;
}
// TTimo
// relevant to client only
#if !defined( DEDICATED )
/*
==================
FS_CL_ExtractFromPakFile
NERVE - SMF - Extracts the latest file from a pak file.
Compares packed file against extracted file. If no differences, does not copy.
This is necessary for exe/dlls which may or may not be locked.
NOTE TTimo:
fullpath gives the full OS path to the dll that will potentially be loaded
on win32 it's always in fs_basepath/<fs_game>/
on linux it can be in fs_homepath/<fs_game>/ or fs_basepath/<fs_game>/
the dll is extracted to fs_homepath (== fs_basepath on win32) if needed
the return value doesn't tell wether file was extracted or not, it just says wether it's ok to continue
(i.e. either the right file was extracted successfully, or it was already present)
cvar_lastVersion is the optional name of a CVAR_ARCHIVE used to store the wolf version for the last extracted .so
show_bug.cgi?id=463
==================
*/
qboolean FS_CL_ExtractFromPakFile( void *searchpath, const char *fullpath, const char *filename, const char *cvar_lastVersion ) {
int srcLength;
int destLength;
unsigned char *srcData;
unsigned char *destData;
qboolean needToCopy;
FILE *destHandle;
int read;
needToCopy = qtrue;
// read in compressed file
srcLength = FS_ReadFileDir(filename, searchpath, qfalse, (void **)&srcData);
// if its not in the pak, we bail
if ( srcLength == -1 ) {
return qfalse;
}
// read in local file
destHandle = Sys_FOpen( fullpath, "rb" );
// if we have a local file, we need to compare the two
if ( destHandle ) {
fseek( destHandle, 0, SEEK_END );
destLength = ftell( destHandle );
fseek( destHandle, 0, SEEK_SET );
if ( destLength > 0 ) {
destData = (unsigned char*)Z_Malloc( destLength );
read = fread( destData, 1, destLength, destHandle );
if (read == 0) {
Com_Error (ERR_FATAL, "FS_CL_ExtractFromPakFile: 0 bytes read");
}
// compare files
if ( destLength == srcLength ) {
int i;
for ( i = 0; i < destLength; i++ ) {
if ( destData[i] != srcData[i] ) {
break;
}
}
if ( i == destLength ) {
needToCopy = qfalse;
}
}
Z_Free( destData ); // TTimo
}
fclose( destHandle );
}
// write file
if ( needToCopy ) {
fileHandle_t f;
Com_DPrintf("FS_ExtractFromPakFile: FS_FOpenFileWrite '%s'\n", filename);
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf( "Failed to open %s\n", filename );
return qfalse;
}
FS_Write( srcData, srcLength, f );
FS_FCloseFile( f );
#ifdef __linux__
// show_bug.cgi?id=463
// need to keep track of what versions we extract
if ( cvar_lastVersion ) {
Cvar_Set( cvar_lastVersion, Cvar_VariableString( "version" ) );
}
#endif
}
FS_FreeFile( srcData );
return qtrue;
}
#endif
/*
==============
FS_Delete
TTimo - this was not in the 1.30 filesystem code
using fs_homepath for the file to remove
==============
*/
int FS_Delete( char *filename ) {
#if 0 // Stub...not used in MP
char *ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
}
if ( !filename || filename[0] == 0 ) {
return 0;
}
// for safety, only allow deletion from the save directory
if ( Q_strncmp( filename, "save/", 5 ) != 0 ) {
return 0;
}
ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
if ( remove( ospath ) != -1 ) { // success
return 1;
}
#endif
return 0;
}
/*
=================
FS_Read
Properly handles partial reads
=================
*/
int FS_Read2( void *buffer, int len, fileHandle_t f ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !f ) {
return 0;
}
if ( fsh[f].streamed ) {
int r;
fsh[f].streamed = qfalse;
r = FS_Read( buffer, len, f );
fsh[f].streamed = qtrue;
return r;
} else {
return FS_Read( buffer, len, f );
}
}
int FS_Read( void *buffer, int len, fileHandle_t f ) {
int block, remaining;
int read;
byte *buf;
int tries;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !f ) {
return 0;
}
buf = (byte *)buffer;
fs_readCount += len;
if ( fsh[f].zipFile == qfalse ) {
remaining = len;
tries = 0;
while ( remaining ) {
block = remaining;
read = fread( buf, 1, block, fsh[f].handleFiles.file.o );
if ( read == 0 ) {
// we might have been trying to read from a CD, which
// sometimes returns a 0 read on windows
if ( !tries ) {
tries = 1;
} else {
return len - remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read");
}
}
if ( read == -1 ) {
Com_Error( ERR_FATAL, "FS_Read: -1 bytes read" );
}
remaining -= read;
buf += read;
}
return len;
} else {
return unzReadCurrentFile( fsh[f].handleFiles.file.z, buffer, len );
}
}
/*
=================
FS_Write
Properly handles partial writes
=================
*/
int FS_Write( const void *buffer, int len, fileHandle_t h ) {
int block, remaining;
int written;
byte *buf;
int tries;
FILE *f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !h ) {
return 0;
}
f = FS_FileForHandle( h );
buf = (byte *)buffer;
remaining = len;
tries = 0;
while ( remaining ) {
block = remaining;
written = fwrite( buf, 1, block, f );
if ( written == 0 ) {
if ( !tries ) {
tries = 1;
} else {
Com_Printf( "FS_Write: 0 bytes written\n" );
return 0;
}
}
if ( written == -1 ) {
Com_Printf( "FS_Write: -1 bytes written\n" );
return 0;
}
remaining -= written;
buf += written;
}
if ( fsh[h].handleSync ) {
fflush( f );
}
return len;
}
void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof( msg ), fmt, argptr );
va_end( argptr );
FS_Write( msg, strlen( msg ), h );
}
#define PK3_SEEK_BUFFER_SIZE 65536
/*
=================
FS_Seek
=================
*/
int FS_Seek( fileHandle_t f, long offset, int origin ) {
int _origin;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
return -1;
}
if (fsh[f].streamed) {
int r;
fsh[f].streamed = qfalse;
r = FS_Seek( f, offset, origin );
fsh[f].streamed = qtrue;
return r;
}
if (fsh[f].zipFile == qtrue) {
//FIXME: this is really, really crappy
//(but better than what was here before)
byte buffer[PK3_SEEK_BUFFER_SIZE];
int remainder;
int currentPosition = FS_FTell( f );
// change negative offsets into FS_SEEK_SET
if ( offset < 0 ) {
switch( origin ) {
case FS_SEEK_END:
remainder = fsh[f].zipFileLen + offset;
break;
case FS_SEEK_CUR:
remainder = currentPosition + offset;
break;
case FS_SEEK_SET:
default:
remainder = 0;
break;
}
if ( remainder < 0 ) {
remainder = 0;
}
origin = FS_SEEK_SET;
} else {
if ( origin == FS_SEEK_END ) {
remainder = fsh[f].zipFileLen - currentPosition + offset;
} else {
remainder = offset;
}
}
switch( origin ) {
case FS_SEEK_SET:
if ( remainder == currentPosition ) {
return offset;
}
unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
unzOpenCurrentFile(fsh[f].handleFiles.file.z);
//fallthrough
case FS_SEEK_END:
case FS_SEEK_CUR:
while( remainder > PK3_SEEK_BUFFER_SIZE ) {
FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f );
remainder -= PK3_SEEK_BUFFER_SIZE;
}
FS_Read( buffer, remainder, f );
return offset;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
return -1;
}
} else {
FILE *file;
file = FS_FileForHandle(f);
switch( origin ) {
case FS_SEEK_CUR:
_origin = SEEK_CUR;
break;
case FS_SEEK_END:
_origin = SEEK_END;
break;
case FS_SEEK_SET:
_origin = SEEK_SET;
break;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
break;
}
return fseek( file, offset, _origin );
}
}
/*
======================================================================================
CONVENIENCE FUNCTIONS FOR ENTIRE FILES
======================================================================================
*/
int FS_FileIsInPAK( const char *filename, int *pChecksum ) {
searchpath_t *search;
pack_t *pak;
fileInPack_t *pakFile;
long hash = 0;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !filename ) {
Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed" );
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// make absolutely sure that it can't back up the path.
// The searchpaths do guarantee that something will always
// be prepended, so we don't need to worry about "c:" or "//limbo"
if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
return -1;
}
//
// search through the path, one element at a time
//
for ( search = fs_searchpaths ; search ; search = search->next ) {
//
if ( search->pack ) {
hash = FS_HashFileName( filename, search->pack->hashSize );
}
// is the element a pak file?
if ( search->pack && search->pack->hashTable[hash] ) {
// disregard if it doesn't match one of the allowed pure pak files
if ( !FS_PakIsPure( search->pack ) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
pakFile = pak->hashTable[hash];
do {
// case and separator insensitive comparisons
if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
if ( pChecksum ) {
*pChecksum = pak->pure_checksum;
}
return 1;
}
pakFile = pakFile->next;
} while ( pakFile != NULL );
}
}
return -1;
}
/*
============
FS_ReadFileDir
Filename are relative to the quake search path
a null buffer will just return the file length without loading
If searchPath is non-NULL search only in that specific search path
============
*/
long FS_ReadFileDir(const char *qpath, void *searchPath, qboolean unpure, void **buffer)
{
fileHandle_t h;
searchpath_t *search;
byte* buf;
qboolean isConfig;
long len;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !qpath || !qpath[0] ) {
Com_Error( ERR_FATAL, "FS_ReadFile with empty name" );
}
buf = NULL; // quiet compiler warning
// if this is a .cfg file and we are playing back a journal, read
// it from the journal file
if ( strstr( qpath, ".cfg" ) ) {
isConfig = qtrue;
if ( com_journal && com_journal->integer == 2 ) {
int r;
Com_DPrintf( "Loading %s from journal file.\n", qpath );
r = FS_Read( &len, sizeof( len ), com_journalDataFile );
if ( r != sizeof( len ) ) {
if (buffer != NULL) *buffer = NULL;
return -1;
}
// if the file didn't exist when the journal was created
if (!len) {
if (buffer == NULL) {
return 1; // hack for old journal files
}
*buffer = NULL;
return -1;
}
if (buffer == NULL) {
return len;
}
buf = Hunk_AllocateTempMemory(len+1);
*buffer = buf;
r = FS_Read( buf, len, com_journalDataFile );
if ( r != len ) {
Com_Error( ERR_FATAL, "Read from journalDataFile failed" );
}
fs_loadCount++;
fs_loadStack++;
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
return len;
}
} else {
isConfig = qfalse;
}
search = searchPath;
if(search == NULL)
{
// look for it in the filesystem or pack files
len = FS_FOpenFileRead(qpath, &h, qfalse);
}
else
{
// look for it in a specific search path only
len = FS_FOpenFileReadDir(qpath, search, &h, qfalse, unpure);
}
if ( h == 0 ) {
if ( buffer ) {
*buffer = NULL;
}
// if we are journalling and it is a config file, write a zero to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing zero for %s to journal file.\n", qpath );
len = 0;
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return -1;
}
if ( !buffer ) {
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing len for %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Flush( com_journalDataFile );
}
FS_FCloseFile( h);
return len;
}
fs_loadCount++;
fs_loadStack++;
buf = Hunk_AllocateTempMemory(len+1);
*buffer = buf;
FS_Read (buf, len, h);
// guarantee that it will have a trailing 0 for string operations
buf[len] = 0;
FS_FCloseFile( h );
// if we are journalling and it is a config file, write it to the journal file
if ( isConfig && com_journal && com_journal->integer == 1 ) {
Com_DPrintf( "Writing %s to journal file.\n", qpath );
FS_Write( &len, sizeof( len ), com_journalDataFile );
FS_Write( buf, len, com_journalDataFile );
FS_Flush( com_journalDataFile );
}
return len;
}
/*
============
FS_ReadFile
Filename are relative to the quake search path
a null buffer will just return the file length without loading
============
*/
long FS_ReadFile(const char *qpath, void **buffer)
{
return FS_ReadFileDir(qpath, NULL, qfalse, buffer);
}
/*
=============
FS_FreeFile
=============
*/
void FS_FreeFile( void *buffer ) {
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !buffer ) {
Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" );
}
fs_loadStack--;
Hunk_FreeTempMemory( buffer );
// if all of our temp files are free, clear all of our space
if ( fs_loadStack == 0 ) {
Hunk_ClearTempMemory();
}
}
/*
============
FS_WriteFile
Filenames are relative to the quake search path
============
*/
void FS_WriteFile( const char *qpath, const void *buffer, int size ) {
fileHandle_t f;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !qpath || !buffer ) {
Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" );
}
f = FS_FOpenFileWrite( qpath );
if ( !f ) {
Com_Printf( "Failed to open %s\n", qpath );
return;
}
FS_Write( buffer, size, f );
FS_FCloseFile( f );
}
/*
==========================================================================
ZIP FILE LOADING
==========================================================================
*/
/*
=================
FS_LoadZipFile
Creates a new pak_t in the search chain for the contents
of a zip file.
=================
*/
static pack_t *FS_LoadZipFile(const char *zipfile, const char *basename ) {
fileInPack_t *buildBuffer;
pack_t *pack;
unzFile uf;
int err;
unz_global_info gi;
char filename_inzip[MAX_ZPATH];
unz_file_info file_info;
int i, len;
long hash;
int fs_numHeaderLongs;
int *fs_headerLongs;
char *namePtr;
fs_numHeaderLongs = 0;
uf = unzOpen( zipfile );
err = unzGetGlobalInfo( uf,&gi );
if ( err != UNZ_OK ) {
return NULL;
}
fs_packFiles += gi.number_entry;
len = 0;
unzGoToFirstFile( uf );
for ( i = 0; i < gi.number_entry; i++ )
{
err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 );
if ( err != UNZ_OK ) {
break;
}
len += strlen( filename_inzip ) + 1;
unzGoToNextFile( uf );
}
buildBuffer = Z_Malloc( ( gi.number_entry * sizeof( fileInPack_t ) ) + len );
namePtr = ( (char *) buildBuffer ) + gi.number_entry * sizeof( fileInPack_t );
fs_headerLongs = Z_Malloc( ( gi.number_entry + 1 ) * sizeof(int) );
fs_headerLongs[ fs_numHeaderLongs++ ] = LittleLong( fs_checksumFeed );
// get the hash table size from the number of files in the zip
// because lots of custom pk3 files have less than 32 or 64 files
for ( i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1 ) {
if ( i > gi.number_entry ) {
break;
}
}
pack = Z_Malloc( sizeof( pack_t ) + i * sizeof( fileInPack_t * ) );
pack->hashSize = i;
pack->hashTable = ( fileInPack_t ** )( ( (char *) pack ) + sizeof( pack_t ) );
for ( i = 0; i < pack->hashSize; i++ ) {
pack->hashTable[i] = NULL;
}
Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) );
Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) );
// strip .pk3 if needed
if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) {
pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0;
}
pack->handle = uf;
pack->numfiles = gi.number_entry;
unzGoToFirstFile( uf );
for ( i = 0; i < gi.number_entry; i++ )
{
err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 );
if ( err != UNZ_OK ) {
break;
}
if ( file_info.uncompressed_size > 0 ) {
fs_headerLongs[fs_numHeaderLongs++] = LittleLong( file_info.crc );
}
Q_strlwr( filename_inzip );
hash = FS_HashFileName( filename_inzip, pack->hashSize );
buildBuffer[i].name = namePtr;
strcpy( buildBuffer[i].name, filename_inzip );
namePtr += strlen( filename_inzip ) + 1;
// store the file position in the zip
buildBuffer[i].pos = unzGetOffset(uf);
buildBuffer[i].len = file_info.uncompressed_size;
buildBuffer[i].next = pack->hashTable[hash];
pack->hashTable[hash] = &buildBuffer[i];
unzGoToNextFile( uf );
}
pack->checksum = Com_BlockChecksum( &fs_headerLongs[ 1 ], sizeof(*fs_headerLongs) * ( fs_numHeaderLongs - 1 ) );
pack->pure_checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs );
pack->checksum = LittleLong( pack->checksum );
pack->pure_checksum = LittleLong( pack->pure_checksum );
Z_Free( fs_headerLongs );
pack->buildBuffer = buildBuffer;
return pack;
}
/*
=================
FS_FreePak
Frees a pak structure and releases all associated resources
=================
*/
static void FS_FreePak(pack_t *thepak)
{
unzClose(thepak->handle);
Z_Free(thepak->buildBuffer);
Z_Free(thepak);
}
/*
=================
FS_GetZipChecksum
Compares whether the given pak file matches a referenced checksum
=================
*/
qboolean FS_CompareZipChecksum(const char *zipfile)
{
pack_t *thepak;
int index, checksum;
thepak = FS_LoadZipFile(zipfile, "");
if(!thepak)
return qfalse;
checksum = thepak->checksum;
FS_FreePak(thepak);
for(index = 0; index < fs_numServerReferencedPaks; index++)
{
if(checksum == fs_serverReferencedPaks[index])
return qtrue;
}
return qfalse;
}
/*
=================================================================================
DIRECTORY SCANNING FUNCTIONS
=================================================================================
*/
#define MAX_FOUND_FILES 0x1000
static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) {
int len, at, newdep;
newdep = 0;
zpath[0] = 0;
len = 0;
at = 0;
while ( zname[at] != 0 )
{
if ( zname[at] == '/' || zname[at] == '\\' ) {
len = at;
newdep++;
}
at++;
}
strcpy( zpath, zname );
zpath[len] = 0;
*depth = newdep;
return len;
}
/*
==================
FS_AddFileToList
==================
*/
static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) {
int i;
if ( nfiles == MAX_FOUND_FILES - 1 ) {
return nfiles;
}
for ( i = 0 ; i < nfiles ; i++ ) {
if ( !Q_stricmp( name, list[i] ) ) {
return nfiles; // allready in list
}
}
list[nfiles] = CopyString( name );
nfiles++;
return nfiles;
}
/*
===============
FS_ListFilteredFiles
Returns a uniqued list of files that match the given criteria
from all search paths
===============
*/
char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles, qboolean allowNonPureFilesOnDisk ) {
int nfiles;
char **listCopy;
char *list[MAX_FOUND_FILES];
searchpath_t *search;
int i;
int pathLength;
int extensionLength;
int length, pathDepth, temp;
pack_t *pak;
fileInPack_t *buildBuffer;
char zpath[MAX_ZPATH];
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !path ) {
*numfiles = 0;
return NULL;
}
if ( !extension ) {
extension = "";
}
pathLength = strlen( path );
if ( path[pathLength - 1] == '\\' || path[pathLength - 1] == '/' ) {
pathLength--;
}
extensionLength = strlen( extension );
nfiles = 0;
FS_ReturnPath( path, zpath, &pathDepth );
//
// search through the path, one element at a time, adding to list
//
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
//ZOID: If we are pure, don't search for files on paks that
// aren't on the pure list
if ( !FS_PakIsPure( search->pack ) ) {
continue;
}
// look through all the pak file elements
pak = search->pack;
buildBuffer = pak->buildBuffer;
for ( i = 0; i < pak->numfiles; i++ ) {
char *name;
int zpathLen, depth;
// check for directory match
name = buildBuffer[i].name;
//
if ( filter ) {
// case insensitive
if ( !Com_FilterPath( filter, name, qfalse ) ) {
continue;
}
// unique the match
nfiles = FS_AddFileToList( name, list, nfiles );
} else {
zpathLen = FS_ReturnPath( name, zpath, &depth );
if ( ( depth - pathDepth ) > 2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) {
continue;
}
// check for extension match
length = strlen( name );
if ( length < extensionLength ) {
continue;
}
if ( Q_stricmp( name + length - extensionLength, extension ) ) {
continue;
}
// unique the match
temp = pathLength;
if ( pathLength ) {
temp++; // include the '/'
}
nfiles = FS_AddFileToList( name + temp, list, nfiles );
}
}
} else if ( search->dir ) { // scan for files in the filesystem
char *netpath;
int numSysFiles;
char **sysFiles;
char *name;
// don't scan directories for files if we are pure or restricted
if ( fs_numServerPaks && !allowNonPureFilesOnDisk ) {
continue;
} else {
netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path );
sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse );
for ( i = 0 ; i < numSysFiles ; i++ ) {
// unique the match
name = sysFiles[i];
nfiles = FS_AddFileToList( name, list, nfiles );
}
Sys_FreeFileList( sysFiles );
}
}
}
// return a copy of the list
*numfiles = nfiles;
if ( !nfiles ) {
return NULL;
}
listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
for ( i = 0 ; i < nfiles ; i++ ) {
listCopy[i] = list[i];
}
listCopy[i] = NULL;
return listCopy;
}
/*
=================
FS_ListFiles
=================
*/
char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) {
return FS_ListFilteredFiles( path, extension, NULL, numfiles, qfalse );
}
/*
=================
FS_FreeFileList
=================
*/
void FS_FreeFileList( char **list ) {
int i;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
if ( !list ) {
return;
}
for ( i = 0 ; list[i] ; i++ ) {
Z_Free( list[i] );
}
Z_Free( list );
}
/*
================
FS_GetFileList
================
*/
int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
int nFiles, i, nTotal, nLen;
char **pFiles = NULL;
*listbuf = 0;
nFiles = 0;
nTotal = 0;
if ( Q_stricmp( path, "$modlist" ) == 0 ) {
return FS_GetModList( listbuf, bufsize );
}
pFiles = FS_ListFiles( path, extension, &nFiles );
for ( i = 0; i < nFiles; i++ ) {
nLen = strlen( pFiles[i] ) + 1;
if ( nTotal + nLen + 1 < bufsize ) {
strcpy( listbuf, pFiles[i] );
listbuf += nLen;
nTotal += nLen;
} else {
nFiles = i;
break;
}
}
FS_FreeFileList( pFiles );
return nFiles;
}
/*
=======================
Sys_ConcatenateFileLists
mkv: Naive implementation. Concatenates three lists into a
new list, and frees the old lists from the heap.
FIXME TTimo those two should move to common.c next to Sys_ListFiles
=======================
*/
static unsigned int Sys_CountFileList(char **list)
{
int i = 0;
if (list)
{
while (*list)
{
list++;
i++;
}
}
return i;
}
static char** Sys_ConcatenateFileLists( char **list0, char **list1 )
{
int totalLength = 0;
char** cat = NULL, **dst, **src;
totalLength += Sys_CountFileList(list0);
totalLength += Sys_CountFileList(list1);
/* Create new list. */
dst = cat = Z_Malloc( ( totalLength + 1 ) * sizeof( char* ) );
/* Copy over lists. */
if (list0)
{
for (src = list0; *src; src++, dst++)
*dst = *src;
}
if (list1)
{
for (src = list1; *src; src++, dst++)
*dst = *src;
}
// Terminate the list
*dst = NULL;
// Free our old lists.
// NOTE: not freeing their content, it's been merged in dst and still being used
if (list0) Z_Free( list0 );
if (list1) Z_Free( list1 );
return cat;
}
/*
================
FS_GetModDescription
================
*/
void FS_GetModDescription( const char *modDir, char *description, int descriptionLen ) {
fileHandle_t descHandle;
char descPath[MAX_QPATH];
int nDescLen;
FILE *file;
Com_sprintf( descPath, sizeof ( descPath ), "%s/description.txt", modDir );
nDescLen = FS_SV_FOpenFileRead( descPath, &descHandle );
if ( nDescLen > 0 && descHandle ) {
file = FS_FileForHandle(descHandle);
Com_Memset( description, 0, descriptionLen );
nDescLen = fread(description, 1, descriptionLen, file);
if (nDescLen >= 0) {
description[nDescLen] = '\0';
}
FS_FCloseFile(descHandle);
} else {
Q_strncpyz( description, modDir, descriptionLen );
}
}
/*
================
FS_GetModList
Returns a list of mod directory names
A mod directory is a peer to baseq3 with a pk3 in it
The directories are searched in base path, cd path and home path
================
*/
int FS_GetModList( char *listbuf, int bufsize ) {
int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen;
char **pFiles = NULL;
char **pPaks = NULL;
char *name, *path;
char description[MAX_OSPATH];
int dummy;
char **pFiles0 = NULL;
char **pFiles1 = NULL;
#ifndef STANDALONE
char **pFiles2 = NULL;
char **pFiles3 = NULL;
#endif
qboolean bDrop = qfalse;
*listbuf = 0;
nMods = nTotal = 0;
pFiles0 = Sys_ListFiles( fs_homepath->string, NULL, NULL, &dummy, qtrue );
pFiles1 = Sys_ListFiles( fs_basepath->string, NULL, NULL, &dummy, qtrue );
#ifndef STANDALONE
pFiles2 = Sys_ListFiles( fs_steampath->string, NULL, NULL, &dummy, qtrue );
#endif
// we searched for mods in the three paths
// it is likely that we have duplicate names now, which we will cleanup below
#ifndef STANDALONE
pFiles3 = Sys_ConcatenateFileLists( pFiles0, pFiles1 );
pFiles = Sys_ConcatenateFileLists( pFiles2, pFiles3 );
#else
pFiles = Sys_ConcatenateFileLists( pFiles0, pFiles1 );
#endif
nPotential = Sys_CountFileList(pFiles);
for ( i = 0 ; i < nPotential ; i++ ) {
name = pFiles[i];
// NOTE: cleaner would involve more changes
// ignore duplicate mod directories
if (i!=0) {
bDrop = qfalse;
for(j=0; j<i; j++)
{
if (Q_stricmp(pFiles[j],name)==0) {
// this one can be dropped
bDrop = qtrue;
break;
}
}
}
if (bDrop) {
continue;
}
// we drop "baseq3" "." and ".."
if (Q_stricmp(name, com_basegame->string) && Q_stricmpn(name, ".", 1)) {
// now we need to find some .pk3 files to validate the mod
// NOTE TTimo: (actually I'm not sure why .. what if it's a mod under developement with no .pk3?)
// we didn't keep the information when we merged the directory names, as to what OS Path it was found under
// so it could be in base path, cd path or home path
// we will try each three of them here (yes, it's a bit messy)
path = FS_BuildOSPath( fs_basepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse);
Sys_FreeFileList( pPaks ); // we only use Sys_ListFiles to check wether .pk3 files are present
/* try on home path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_homepath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
#ifndef STANDALONE
/* try on steam path */
if ( nPaks <= 0 )
{
path = FS_BuildOSPath( fs_steampath->string, name, "" );
nPaks = 0;
pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
Sys_FreeFileList( pPaks );
}
#endif
if (nPaks > 0) {
nLen = strlen(name) + 1;
// nLen is the length of the mod path
// we need to see if there is a description available
FS_GetModDescription( name, description, sizeof( description ) );
nDescLen = strlen(description) + 1;
if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) {
strcpy(listbuf, name);
listbuf += nLen;
strcpy(listbuf, description);
listbuf += nDescLen;
nTotal += nLen + nDescLen;
nMods++;
}
else {
break;
}
}
}
}
Sys_FreeFileList( pFiles );
return nMods;
}
//============================================================================
/*
================
FS_Dir_f
================
*/
void FS_Dir_f( void ) {
char *path;
char *extension;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) {
Com_Printf( "usage: dir <directory> [extension]\n" );
return;
}
if ( Cmd_Argc() == 2 ) {
path = Cmd_Argv( 1 );
extension = "";
} else {
path = Cmd_Argv( 1 );
extension = Cmd_Argv( 2 );
}
Com_Printf( "Directory of %s %s\n", path, extension );
Com_Printf( "---------------\n" );
dirnames = FS_ListFiles( path, extension, &ndirs );
for ( i = 0; i < ndirs; i++ ) {
Com_Printf( "%s\n", dirnames[i] );
}
FS_FreeFileList( dirnames );
}
/*
===========
FS_ConvertPath
===========
*/
void FS_ConvertPath( char *s ) {
while ( *s ) {
if ( *s == '\\' || *s == ':' ) {
*s = '/';
}
s++;
}
}
/*
===========
FS_PathCmp
Ignore case and seprator char distinctions
===========
*/
int FS_PathCmp( const char *s1, const char *s2 ) {
int c1, c2;
do {
c1 = *s1++;
c2 = *s2++;
if ( c1 >= 'a' && c1 <= 'z' ) {
c1 -= ( 'a' - 'A' );
}
if ( c2 >= 'a' && c2 <= 'z' ) {
c2 -= ( 'a' - 'A' );
}
if ( c1 == '\\' || c1 == ':' ) {
c1 = '/';
}
if ( c2 == '\\' || c2 == ':' ) {
c2 = '/';
}
if ( c1 < c2 ) {
return -1; // strings not equal
}
if ( c1 > c2 ) {
return 1;
}
} while ( c1 );
return 0; // strings are equal
}
/*
================
FS_SortFileList
================
*/
void FS_SortFileList( char **filelist, int numfiles ) {
int i, j, k, numsortedfiles;
char **sortedlist;
sortedlist = Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ) );
sortedlist[0] = NULL;
numsortedfiles = 0;
for ( i = 0; i < numfiles; i++ ) {
for ( j = 0; j < numsortedfiles; j++ ) {
if ( FS_PathCmp( filelist[i], sortedlist[j] ) < 0 ) {
break;
}
}
for ( k = numsortedfiles; k > j; k-- ) {
sortedlist[k] = sortedlist[k - 1];
}
sortedlist[j] = filelist[i];
numsortedfiles++;
}
Com_Memcpy( filelist, sortedlist, numfiles * sizeof( *filelist ) );
Z_Free( sortedlist );
}
/*
================
FS_NewDir_f
================
*/
void FS_NewDir_f( void ) {
char *filter;
char **dirnames;
int ndirs;
int i;
if ( Cmd_Argc() < 2 ) {
Com_Printf( "usage: fdir <filter>\n" );
Com_Printf( "example: fdir *q3dm*.bsp\n" );
return;
}
filter = Cmd_Argv( 1 );
Com_Printf( "---------------\n" );
dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs, qfalse );
FS_SortFileList( dirnames, ndirs );
for ( i = 0; i < ndirs; i++ ) {
FS_ConvertPath( dirnames[i] );
Com_Printf( "%s\n", dirnames[i] );
}
Com_Printf( "%d files listed\n", ndirs );
FS_FreeFileList( dirnames );
}
/*
============
FS_Path_f
============
*/
void FS_Path_f( void ) {
searchpath_t *s;
int i;
Com_Printf( "Current search path:\n" );
for ( s = fs_searchpaths; s; s = s->next ) {
if ( s->pack ) {
Com_Printf( "%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles );
if ( fs_numServerPaks ) {
if ( !FS_PakIsPure( s->pack ) ) {
Com_Printf( " not on the pure list\n" );
} else {
Com_Printf( " on the pure list\n" );
}
}
} else {
Com_Printf ("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir );
}
}
Com_Printf( "\n" );
for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
if ( fsh[i].handleFiles.file.o ) {
Com_Printf( "handle %i: %s\n", i, fsh[i].name );
}
}
}
/*
============
FS_TouchFile_f
============
*/
void FS_TouchFile_f( void ) {
fileHandle_t f;
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: touchFile <file>\n" );
return;
}
FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse );
if ( f ) {
FS_FCloseFile( f );
}
}
/*
============
FS_Which
============
*/
qboolean FS_Which(const char *filename, void *searchPath)
{
searchpath_t *search = searchPath;
if(FS_FOpenFileReadDir(filename, search, NULL, qfalse, qfalse) > 0)
{
if(search->pack)
{
Com_Printf("File \"%s\" found in \"%s\"\n", filename, search->pack->pakFilename);
return qtrue;
}
else if(search->dir)
{
Com_Printf( "File \"%s\" found at \"%s\"\n", filename, search->dir->fullpath);
return qtrue;
}
}
return qfalse;
}
/*
============
FS_Which_f
============
*/
void FS_Which_f( void ) {
searchpath_t *search;
char *filename;
filename = Cmd_Argv(1);
if ( !filename[0] ) {
Com_Printf( "Usage: which <file>\n" );
return;
}
// qpaths are not supposed to have a leading slash
if ( filename[0] == '/' || filename[0] == '\\' ) {
filename++;
}
// just wants to see if file is there
for(search = fs_searchpaths; search; search = search->next)
{
if(FS_Which(filename, search))
return;
}
Com_Printf("File not found: \"%s\"\n", filename);
}
//===========================================================================
static int QDECL paksort( const void *a, const void *b ) {
char *aa, *bb;
aa = *(char **)a;
bb = *(char **)b;
return FS_PathCmp( aa, bb );
}
/*
================
FS_AddGameDirectory
Sets fs_gamedir, adds the directory to the head of the path,
then loads the zip headers
================
*/
#define MAX_PAKFILES 1024
void FS_AddGameDirectory( const char *path, const char *dir, qboolean allowUnzippedDLLs ) {
searchpath_t *sp;
int i;
searchpath_t *search;
pack_t *pak;
char curpath[MAX_OSPATH + 1], *pakfile;
int numfiles;
char **pakfiles;
char *sorted[MAX_PAKFILES];
// find all pak files in this directory
Q_strncpyz(curpath, FS_BuildOSPath(path, dir, ""), sizeof(curpath));
curpath[strlen(curpath) - 1] = '\0'; // strip the trailing slash
// this fixes the case where fs_basepath is the same as fs_cdpath
// which happens on full installs
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->dir && !Q_stricmp( sp->dir->path, path ) && !Q_stricmp( sp->dir->gamedir, dir ) ) {
return; // we've already got this one
}
}
Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) );
// find all pak files in this directory
pakfile = FS_BuildOSPath( path, dir, "" );
pakfile[ strlen( pakfile ) - 1 ] = 0; // strip the trailing slash
pakfiles = Sys_ListFiles( pakfile, ".pk3", NULL, &numfiles, qfalse );
// sort them so that later alphabetic matches override
// earlier ones. This makes pak1.pk3 override pak0.pk3
if ( numfiles > MAX_PAKFILES ) {
numfiles = MAX_PAKFILES;
}
for ( i = 0 ; i < numfiles ; i++ ) {
sorted[i] = pakfiles[i];
// JPW NERVE KLUDGE: sorry, temp mod mp_* to _p_* so "mp_pak*" gets alphabetically sorted before "pak*"
if ( !Q_strncmp( sorted[i],"mp_",3 ) ) {
memcpy( sorted[i],"zz",2 );
}
// jpw
}
qsort( sorted, numfiles, sizeof(char*), paksort );
for ( i = 0 ; i < numfiles ; i++ ) {
if ( Q_strncmp( sorted[i],"sp_",3 ) ) { // JPW NERVE -- exclude sp_*
// JPW NERVE KLUDGE: fix filenames broken in mp/sp/pak sort above
if ( !Q_strncmp( sorted[i],"zz_",3 ) ) {
memcpy( sorted[i],"mp",2 );
}
// jpw
pakfile = FS_BuildOSPath( path, dir, sorted[i] );
if ( ( pak = FS_LoadZipFile( pakfile, sorted[i] ) ) == 0 ) {
continue;
}
Q_strncpyz(pak->pakPathname, curpath, sizeof(pak->pakPathname));
// store the game name for downloading
strcpy( pak->pakGamename, dir );
search = Z_Malloc( sizeof( searchpath_t ) );
search->pack = pak;
search->next = fs_searchpaths;
fs_searchpaths = search;
}
}
// done
Sys_FreeFileList( pakfiles );
//
// add the directory to the search path
//
search = Z_Malloc (sizeof(searchpath_t));
search->dir = Z_Malloc( sizeof( *search->dir ) );
Q_strncpyz(search->dir->path, path, sizeof(search->dir->path));
Q_strncpyz(search->dir->fullpath, curpath, sizeof(search->dir->fullpath));
Q_strncpyz(search->dir->gamedir, dir, sizeof(search->dir->gamedir));
search->dir->allowUnzippedDLLs = allowUnzippedDLLs;
search->next = fs_searchpaths;
fs_searchpaths = search;
}
/*
================
FS_idPak
================
*/
qboolean FS_idPak(char *pak, char *base, int numPaks) {
int i;
if ( !FS_FilenameCompare( pak, va( "%s/mp_bin", base ) ) ) {
return qtrue;
}
for ( i = 0; i < NUM_ID_PAKS; i++ ) {
if ( !FS_FilenameCompare( pak, va( "%s/mp_bin%d", base, i ) ) ) {
break;
}
if ( !FS_FilenameCompare( pak, va( "%s/pak%d", base, i ) ) ) {
break;
}
// JPW NERVE -- this fn prevents external sources from downloading/overwriting official files, so exclude both SP and MP files from this list as well
if ( !FS_FilenameCompare( pak, va( "%s/mp_pak%d",base,i ) ) ) {
break;
}
if ( !FS_FilenameCompare( pak, va( "%s/sp_pak%d",base,i + 1) ) ) {
break;
}
// jpw
}
if ( i < numPaks ) {
return qtrue;
}
return qfalse;
}
/*
================
FS_CheckDirTraversal
Check whether the string contains stuff like "../" to prevent directory traversal bugs
and return qtrue if it does.
================
*/
qboolean FS_CheckDirTraversal(const char *checkdir)
{
if(strstr(checkdir, "../") || strstr(checkdir, "..\\"))
return qtrue;
return qfalse;
}
/*
================
FS_ComparePaks
----------------
dlstring == qtrue
Returns a list of pak files that we should download from the server. They all get stored
in the current gamedir and an FS_Restart will be fired up after we download them all.
The string is the format:
@remotename@localname [repeat]
static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS];
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS];
----------------
dlstring == qfalse
we are not interested in a download string format, we want something human-readable
(this is used for diagnostics while connecting to a pure server)
================
*/
qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring ) {
searchpath_t *sp;
qboolean havepak;
char *origpos = neededpaks;
int i;
if ( !fs_numServerReferencedPaks )
return qfalse; // Server didn't send any pack information along
*neededpaks = 0;
for ( i = 0 ; i < fs_numServerReferencedPaks ; i++ )
{
// Ok, see if we have this pak file
havepak = qfalse;
// never autodownload any of the id paks
if(FS_idPak(fs_serverReferencedPakNames[i], BASEGAME, NUM_ID_PAKS))
{
continue;
}
// Make sure the server cannot make us write to non-quake3 directories.
if(FS_CheckDirTraversal(fs_serverReferencedPakNames[i]))
{
Com_Printf("WARNING: Invalid download name %s\n", fs_serverReferencedPakNames[i]);
continue;
}
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i] ) {
havepak = qtrue; // This is it!
break;
}
}
if ( !havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i] ) {
// Don't got it
if ( dlstring ) {
// We need this to make sure we won't hit the end of the buffer or the server could
// overwrite non-pk3 files on clients by writing so much crap into neededpaks that
// Q_strcat cuts off the .pk3 extension.
origpos += strlen(origpos);
// Remote name
Q_strcat( neededpaks, len, "@" );
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Local name
Q_strcat( neededpaks, len, "@" );
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) ) {
char st[MAX_ZPATH];
// We already have one called this, we need to download it to another name
// Make something up with the checksum in it
Com_sprintf( st, sizeof( st ), "%s.%08x.pk3", fs_serverReferencedPakNames[i], fs_serverReferencedPaks[i] );
Q_strcat( neededpaks, len, st );
} else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
}
// Find out whether it might have overflowed the buffer and don't add this file to the
// list if that is the case.
if(strlen(origpos) + (origpos - neededpaks) >= len - 1)
{
*origpos = '\0';
break;
}
} else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
// Do we have one with the same name?
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) ) {
Q_strcat( neededpaks, len, " (local file exists with wrong checksum)" );
}
Q_strcat( neededpaks, len, "\n" );
}
}
}
if ( *neededpaks ) {
Com_Printf( "Need paks: %s\n", neededpaks );
return qtrue;
}
return qfalse; // We have them all
}
/*
================
FS_Shutdown
Frees all resources.
================
*/
void FS_Shutdown( qboolean closemfp ) {
searchpath_t *p, *next;
int i;
for ( i = 0; i < MAX_FILE_HANDLES; i++ ) {
if ( fsh[i].fileSize ) {
FS_FCloseFile( i );
}
}
// free everything
for ( p = fs_searchpaths ; p ; p = next ) {
next = p->next;
if(p->pack)
FS_FreePak(p->pack);
if (p->dir)
Z_Free(p->dir);
Z_Free(p);
}
// any FS_ calls will now be an error until reinitialized
fs_searchpaths = NULL;
Cmd_RemoveCommand( "path" );
Cmd_RemoveCommand( "dir" );
Cmd_RemoveCommand( "fdir" );
Cmd_RemoveCommand( "touchFile" );
Cmd_RemoveCommand( "which" );
#ifdef FS_MISSING
if ( closemfp ) {
fclose( missingFiles );
}
#endif
}
/*
================
FS_ReorderPurePaks
NOTE TTimo: the reordering that happens here is not reflected in the cvars (\cvarlist *pak*)
this can lead to misleading situations, see show_bug.cgi?id=540
================
*/
static void FS_ReorderPurePaks( void ) {
searchpath_t *s;
int i;
searchpath_t **p_insert_index, // for linked list reordering
**p_previous; // when doing the scan
fs_reordered = qfalse;
// only relevant when connected to pure server
if ( !fs_numServerPaks ) {
return;
}
p_insert_index = &fs_searchpaths; // we insert in order at the beginning of the list
for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
p_previous = p_insert_index; // track the pointer-to-current-item
for ( s = *p_insert_index; s; s = s->next ) { // the part of the list before p_insert_index has been sorted already
if ( s->pack && fs_serverPaks[i] == s->pack->checksum ) {
fs_reordered = qtrue;
// move this element to the insert list
*p_previous = s->next;
s->next = *p_insert_index;
*p_insert_index = s;
// increment insert list
p_insert_index = &s->next;
break; // iterate to next server pack
}
p_previous = &s->next;
}
}
}
/*
================
FS_Startup
================
*/
static void FS_Startup( const char *gameName ) {
const char *homePath;
Com_Printf( "----- FS_Startup -----\n" );
fs_packFiles = 0;
fs_debug = Cvar_Get( "fs_debug", "0", 0 );
fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT|CVAR_PROTECTED );
fs_basegame = Cvar_Get( "fs_basegame", "", CVAR_INIT );
homePath = Sys_DefaultHomePath();
if (!homePath || !homePath[0]) {
homePath = fs_basepath->string;
}
fs_homepath = Cvar_Get ("fs_homepath", homePath, CVAR_INIT|CVAR_PROTECTED );
fs_gamedirvar = Cvar_Get( "fs_game", "", CVAR_INIT | CVAR_SYSTEMINFO );
// add search path elements in reverse priority order
#ifndef STANDALONE
fs_steampath = Cvar_Get ("fs_steampath", Sys_SteamPath(), CVAR_INIT|CVAR_PROTECTED );
if (fs_steampath->string[0]) {
FS_AddGameDirectory( fs_steampath->string, gameName, qtrue );
}
#endif
if ( fs_basepath->string[0] ) {
FS_AddGameDirectory( fs_basepath->string, gameName, qtrue );
}
#ifdef __APPLE__
fs_apppath = Cvar_Get ("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT|CVAR_PROTECTED );
// Make MacOSX also include the base path included with the .app bundle
if (fs_apppath->string[0])
FS_AddGameDirectory(fs_apppath->string, gameName, qtrue);
#endif
// NOTE: same filtering below for mods and basegame
if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string)) {
FS_CreatePath ( fs_homepath->string );
FS_AddGameDirectory( fs_homepath->string, gameName, qtrue );
}
// check for additional base game so mods can be based upon other mods
if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) ) {
#ifndef STANDALONE
if ( fs_steampath->string[0] ) {
FS_AddGameDirectory( fs_steampath->string, fs_basegame->string, qtrue );
}
#endif
if ( fs_basepath->string[0] ) {
FS_AddGameDirectory( fs_basepath->string, fs_basegame->string, qtrue );
}
if ( fs_homepath->string[0] && Q_stricmp( fs_homepath->string,fs_basepath->string ) ) {
FS_AddGameDirectory( fs_homepath->string, fs_basegame->string, qtrue );
}
}
// check for additional game folder for mods
if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) ) {
#ifndef STANDALONE
if ( fs_steampath->string[0] ) {
FS_AddGameDirectory( fs_steampath->string, fs_gamedirvar->string, qtrue );
}
#endif
if ( fs_basepath->string[0] ) {
FS_AddGameDirectory( fs_basepath->string, fs_gamedirvar->string, qtrue );
}
if ( fs_homepath->string[0] && Q_stricmp( fs_homepath->string,fs_basepath->string ) ) {
FS_AddGameDirectory( fs_homepath->string, fs_gamedirvar->string, qtrue );
}
}
#ifndef STANDALONE
if(!com_standalone->integer)
{
cvar_t *fs;
Com_ReadCDKey(BASEGAME);
fs = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
if (fs && fs->string[0] != 0) {
Com_AppendCDKey( fs->string );
}
}
#endif
// add our commands
Cmd_AddCommand( "path", FS_Path_f );
Cmd_AddCommand( "dir", FS_Dir_f );
Cmd_AddCommand( "fdir", FS_NewDir_f );
Cmd_AddCommand( "touchFile", FS_TouchFile_f );
Cmd_AddCommand ("which", FS_Which_f );
// show_bug.cgi?id=506
// reorder the pure pk3 files according to server order
FS_ReorderPurePaks();
// print the current search paths
FS_Path_f();
fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified
Com_Printf( "----------------------\n" );
#ifdef FS_MISSING
if ( missingFiles == NULL ) {
missingFiles = Sys_FOpen( "\\missing.txt", "ab" );
}
#endif
Com_Printf( "%d files in pk3 files\n", fs_packFiles );
}
#ifndef STANDALONE
/*
===================
FS_CheckMPPaks
Check whether any of the original id pak files is present,
and start up in standalone mode, if there are none and a
different com_basegame was set.
Note: If you're building a game that doesn't depend on the
RTCW media mp_pak0.pk3, you'll want to remove this by defining
STANDALONE in q_shared.h
===================
*/
static void FS_CheckMPPaks( void )
{
searchpath_t *path;
pack_t *curpack;
unsigned int foundPak = 0;
for( path = fs_searchpaths; path; path = path->next )
{
const char* pakBasename = path->pack->pakBasename;
if(!path->pack)
continue;
curpack = path->pack;
if(!Q_stricmpn( curpack->pakGamename, BASEGAME, MAX_OSPATH )
&& strlen(pakBasename) == 7 && !Q_stricmpn( pakBasename, "mp_pak", 6 )
&& pakBasename[6] >= '0' && pakBasename[6] <= '0' + NUM_MP_PAKS - 1)
{
if( curpack->checksum != mppak_checksums[pakBasename[6]-'0'] )
{
if(pakBasename[6] == '0')
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/mp_pak0.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-copy mp_pak0.pk3 from your\n"
"legitimate RTCW CDROM.\n"
"**************************************************\n\n\n",
curpack->checksum );
}
else
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/mp_pak%d.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-install the point release\n"
"**************************************************\n\n\n",
pakBasename[6]-'0', curpack->checksum );
}
}
foundPak |= 1<<(pakBasename[6]-'0');
}
else
{
int index;
// Finally check whether this pak's checksum is listed because the user tried
// to trick us by renaming the file, and set foundPak's highest bit to indicate this case.
for(index = 0; index < ARRAY_LEN(mppak_checksums); index++)
{
if(curpack->checksum == mppak_checksums[index])
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: %s is renamed pak file %s%cmp_pak%d.pk3\n"
"Running in standalone mode won't work\n"
"Please rename, or remove this file\n"
"**************************************************\n\n\n",
curpack->pakFilename, BASEGAME, PATH_SEP, index);
foundPak |= 0x80000000;
}
}
}
}
if(!foundPak && Q_stricmp(com_basegame->string, BASEGAME))
{
Cvar_Set("com_standalone", "1");
}
else
Cvar_Set("com_standalone", "0");
if(!com_standalone->integer && (foundPak & 0x3f) != 0x3f)
{
char errorText[MAX_STRING_CHARS] = "";
char missingPaks[MAX_STRING_CHARS] = "";
int i = 0;
if((foundPak & 0x3f) != 0x3f)
{
for( i = 0; i < NUM_MP_PAKS; i++ ) {
if ( !( foundPak & ( 1 << i ) ) ) {
Q_strcat( missingPaks, sizeof( missingPaks ), va( "mp_pak%d.pk3 ", i ) );
}
}
Q_strcat( errorText, sizeof( errorText ),
va( "\n\nPoint Release files are missing: %s \n"
"Please re-install the 1.41 point release.\n\n", missingPaks ) );
}
Com_Error(ERR_FATAL, "%s", errorText);
}
}
/*
===================
FS_CheckPak0
Check whether any of the original id pak files is present,
and start up in standalone mode, if there are none and a
different com_basegame was set.
Note: If you're building a game that doesn't depend on the
RTCW media pak0.pk3, you'll want to remove this by defining
STANDALONE in q_shared.h
===================
*/
static void FS_CheckPak0( void )
{
searchpath_t *path;
pack_t *curpack;
qboolean founddemo = qfalse;
unsigned int foundPak = 0;
for( path = fs_searchpaths; path; path = path->next )
{
const char* pakBasename = path->pack->pakBasename;
if(!path->pack)
continue;
curpack = path->pack;
if(!Q_stricmpn( curpack->pakGamename, "demomain", MAX_OSPATH )
&& !Q_stricmpn( pakBasename, "pak0", MAX_OSPATH ))
{
if(curpack->checksum == DEMO_PAK0_CHECKSUM)
founddemo = qtrue;
}
else if(!Q_stricmpn( curpack->pakGamename, BASEGAME, MAX_OSPATH )
&& strlen(pakBasename) == 4 && !Q_stricmpn( pakBasename, "pak", 3 )
&& pakBasename[3] >= '0' && pakBasename[3] <= '0' + NUM_ID_PAKS - 1)
{
if( curpack->checksum != pak_checksums[pakBasename[3]-'0'] )
{
if(pakBasename[3] == '0')
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/pak0.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-copy pak0.pk3 from your\n"
"legitimate RTCW CDROM.\n"
"**************************************************\n\n\n",
curpack->checksum );
Com_Error(ERR_FATAL, NULL);
}
/*
else
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: " BASEGAME "/pak%d.pk3 is present but its checksum (%u)\n"
"is not correct. Please re-install the point release\n"
"**************************************************\n\n\n",
pakBasename[3]-'0', curpack->checksum );
}
*/
}
foundPak |= 1<<(pakBasename[3]-'0');
}
else
{
int index;
// Finally check whether this pak's checksum is listed because the user tried
// to trick us by renaming the file, and set foundPak's highest bit to indicate this case.
for(index = 0; index < ARRAY_LEN(pak_checksums); index++)
{
if(curpack->checksum == pak_checksums[index])
{
Com_Printf("\n\n"
"**************************************************\n"
"WARNING: %s is renamed pak file %s%cpak%d.pk3\n"
"Running in standalone mode won't work\n"
"Please rename, or remove this file\n"
"**************************************************\n\n\n",
curpack->pakFilename, BASEGAME, PATH_SEP, index);
foundPak |= 0x80000000;
}
}
}
}
if(!foundPak && Q_stricmp(com_basegame->string, BASEGAME))
{
Cvar_Set("com_standalone", "1");
}
else
Cvar_Set("com_standalone", "0");
if(!com_standalone->integer)
{
if(!(foundPak & 0x01))
{
if(founddemo)
{
Com_Printf( "\n\n"
"**************************************************\n"
"WARNING: It looks like you're using pak0.pk3\n"
"from the demo. This may work fine, but it is not\n"
"guaranteed or supported.\n"
"**************************************************\n\n\n" );
foundPak |= 0x01;
}
}
}
if(!com_standalone->integer && (foundPak & 0x01) != 0x01)
{
char errorText[MAX_STRING_CHARS] = "";
if((foundPak & 0x01) != 0x01)
{
Q_strcat(errorText, sizeof(errorText),
"\n\n\"pak0.pk3\" is missing. Please copy it\n"
"from your legitimate RTCW CDROM.\n\n");
}
Q_strcat(errorText, sizeof(errorText),
va("Also check that your iortcw executable is in\n"
"the correct place and that every file\n"
"in the \"%s\" directory is present and readable.\n\n", BASEGAME));
Com_Error(ERR_FATAL, "%s", errorText);
}
if(!founddemo)
FS_CheckMPPaks();
}
#endif
/*
=====================
FS_LoadedPakChecksums
Returns a space separated string containing the checksums of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->checksum ) );
}
return info;
}
/*
=====================
FS_LoadedPakNames
Returns a space separated string containing the names of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
if ( *info ) {
Q_strcat( info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
return info;
}
/*
=====================
FS_LoadedPakPureChecksums
Returns a space separated string containing the pure checksums of all loaded pk3 files.
Servers with sv_pure use these checksums to compare with the checksums the clients send
back to the server.
=====================
*/
const char *FS_LoadedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( !search->pack ) {
continue;
}
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->pure_checksum ) );
}
return info;
}
/*
=====================
FS_ReferencedPakChecksums
Returns a space separated string containing the checksums of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) {
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->checksum ) );
}
}
}
return info;
}
/*
=====================
FS_ReferencedPakNames
Returns a space separated string containing the names of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakNames( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
info[0] = 0;
// we want to return ALL pk3's from the fs_game path
// and referenced one's from baseq3
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file?
if ( search->pack ) {
if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) {
if (*info) {
Q_strcat(info, sizeof( info ), " " );
}
Q_strcat( info, sizeof( info ), search->pack->pakGamename );
Q_strcat( info, sizeof( info ), "/" );
Q_strcat( info, sizeof( info ), search->pack->pakBasename );
}
}
}
return info;
}
/*
=====================
FS_ReferencedPakPureChecksums
Returns a space separated string containing the pure checksums of all referenced pk3 files.
Servers with sv_pure set will get this string back from clients for pure validation
The string has a specific order, "cgame ui @ ref1 ref2 ref3 ..."
=====================
*/
const char *FS_ReferencedPakPureChecksums( void ) {
static char info[BIG_INFO_STRING];
searchpath_t *search;
int nFlags, numPaks, checksum;
info[0] = 0;
checksum = fs_checksumFeed;
numPaks = 0;
for ( nFlags = FS_CGAME_REF; nFlags; nFlags = nFlags >> 1 ) {
if ( nFlags & FS_GENERAL_REF ) {
// add a delimter between must haves and general refs
//Q_strcat(info, sizeof(info), "@ ");
info[strlen( info ) + 1] = '\0';
info[strlen( info ) + 2] = '\0';
info[strlen( info )] = '@';
info[strlen( info )] = ' ';
}
for ( search = fs_searchpaths ; search ; search = search->next ) {
// is the element a pak file and has it been referenced based on flag?
if ( search->pack && ( search->pack->referenced & nFlags ) ) {
Q_strcat( info, sizeof( info ), va( "%i ", search->pack->pure_checksum ) );
if ( nFlags & ( FS_CGAME_REF | FS_UI_REF ) ) {
break;
}
checksum ^= search->pack->pure_checksum;
numPaks++;
}
}
}
// last checksum is the encoded number of referenced pk3s
checksum ^= numPaks;
Q_strcat( info, sizeof( info ), va( "%i ", checksum ) );
return info;
}
/*
=====================
FS_ClearPakReferences
=====================
*/
void FS_ClearPakReferences( int flags ) {
searchpath_t *search;
if ( !flags ) {
flags = -1;
}
for ( search = fs_searchpaths; search; search = search->next ) {
// is the element a pak file and has it been referenced?
if ( search->pack ) {
search->pack->referenced &= ~flags;
}
}
}
/*
=====================
FS_PureServerSetLoadedPaks
If the string is empty, all data sources will be allowed.
If not empty, only pk3 files that match one of the space
separated checksums will be checked for files, with the
exception of .cfg and .dat files.
=====================
*/
void FS_PureServerSetLoadedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
fs_numServerPaks = c;
for ( i = 0 ; i < c ; i++ ) {
fs_serverPaks[i] = atoi( Cmd_Argv( i ) );
}
if ( fs_numServerPaks ) {
Com_DPrintf( "Connected to a pure server.\n" );
} else
{
if ( fs_reordered ) {
// show_bug.cgi?id=540
// force a restart to make sure the search order will be correct
Com_DPrintf( "FS search reorder is required\n" );
FS_Restart( fs_checksumFeed );
return;
}
}
for ( i = 0 ; i < c ; i++ ) {
if ( fs_serverPakNames[i] ) {
Z_Free( fs_serverPakNames[i] );
}
fs_serverPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if ( d > MAX_SEARCH_PATHS ) {
d = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < d ; i++ ) {
fs_serverPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
}
/*
=====================
FS_PureServerSetReferencedPaks
The checksums and names of the pk3 files referenced at the server
are sent to the client and stored here. The client will use these
checksums to see if any pk3 files need to be auto-downloaded.
=====================
*/
void FS_PureServerSetReferencedPaks( const char *pakSums, const char *pakNames ) {
int i, c, d = 0;
Cmd_TokenizeString( pakSums );
c = Cmd_Argc();
if ( c > MAX_SEARCH_PATHS ) {
c = MAX_SEARCH_PATHS;
}
for ( i = 0 ; i < c ; i++ ) {
fs_serverReferencedPaks[i] = atoi( Cmd_Argv( i ) );
}
for (i = 0 ; i < ARRAY_LEN(fs_serverReferencedPakNames); i++)
{
if(fs_serverReferencedPakNames[i])
Z_Free( fs_serverReferencedPakNames[i] );
fs_serverReferencedPakNames[i] = NULL;
}
if ( pakNames && *pakNames ) {
Cmd_TokenizeString( pakNames );
d = Cmd_Argc();
if(d > c)
d = c;
for ( i = 0 ; i < d ; i++ ) {
fs_serverReferencedPakNames[i] = CopyString( Cmd_Argv( i ) );
}
}
// ensure that there are as many checksums as there are pak names.
if(d < c)
c = d;
fs_numServerReferencedPaks = c;
}
/*
================
FS_InitFilesystem
Called only at inital startup, not when the filesystem
is resetting due to a game change
================
*/
void FS_InitFilesystem( void ) {
// allow command line parms to override our defaults
// we have to specially handle this, because normal command
// line variable sets don't happen until after the filesystem
// has already been initialized
Com_StartupVariable("fs_basepath");
Com_StartupVariable("fs_homepath");
Com_StartupVariable("fs_game");
if(!FS_FilenameCompare(Cvar_VariableString("fs_game"), com_basegame->string))
Cvar_Set("fs_game", "");
// try to start up normally
FS_Startup(com_basegame->string);
#ifndef STANDALONE
#ifndef UPDATE_SERVER
FS_CheckPak0( );
#endif
#endif
#ifndef UPDATE_SERVER
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
// TTimo - added some verbosity, 'couldn't load default.cfg' confuses the hell out of users
Com_Error( ERR_FATAL, "Couldn't load default.cfg - I am missing essential files - verify your installation?" );
}
#endif
Q_strncpyz( lastValidBase, fs_basepath->string, sizeof( lastValidBase ) );
Q_strncpyz( lastValidComBaseGame, com_basegame->string, sizeof( lastValidComBaseGame ) );
Q_strncpyz( lastValidFsBaseGame, fs_basegame->string, sizeof( lastValidFsBaseGame ) );
Q_strncpyz( lastValidGame, fs_gamedirvar->string, sizeof( lastValidGame ) );
}
/*
================
FS_Restart
================
*/
void FS_Restart( int checksumFeed ) {
const char *lastGameDir;
// free anything we currently have loaded
FS_Shutdown( qfalse );
// set the checksum feed
fs_checksumFeed = checksumFeed;
// clear pak references
FS_ClearPakReferences( 0 );
// try to start up normally
FS_Startup(com_basegame->string);
#ifndef STANDALONE
FS_CheckPak0( );
#endif
// if we can't find default.cfg, assume that the paths are
// busted and error out now, rather than getting an unreadable
// graphics screen when the font fails to load
if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
// this might happen when connecting to a pure server not using BASEGAME/pak0.pk3
// (for instance a TA demo server)
if ( lastValidBase[0] ) {
FS_PureServerSetLoadedPaks( "", "" );
Cvar_Set( "fs_basepath", lastValidBase );
Cvar_Set( "com_basegame", lastValidComBaseGame );
Cvar_Set( "fs_basegame", lastValidFsBaseGame );
Cvar_Set( "fs_game", lastValidGame );
lastValidBase[0] = '\0';
lastValidComBaseGame[0] = '\0';
lastValidFsBaseGame[0] = '\0';
lastValidGame[0] = '\0';
FS_Restart( checksumFeed );
Com_Error( ERR_DROP, "Invalid game folder" );
return;
}
Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
}
lastGameDir = ( lastValidGame[0] ) ? lastValidGame : lastValidComBaseGame;
if ( Q_stricmp( FS_GetCurrentGameDir(), lastGameDir ) ) {
Sys_RemovePIDFile( lastGameDir );
Sys_InitPIDFile( FS_GetCurrentGameDir() );
// skip the wolfconfig.cfg if "safe" is on the command line
if ( !Com_SafeMode() ) {
Cbuf_AddText("exec " Q3CONFIG_CFG "\n");
}
}
Q_strncpyz( lastValidBase, fs_basepath->string, sizeof( lastValidBase ) );
Q_strncpyz( lastValidComBaseGame, com_basegame->string, sizeof( lastValidComBaseGame ) );
Q_strncpyz( lastValidFsBaseGame, fs_basegame->string, sizeof( lastValidFsBaseGame ) );
Q_strncpyz( lastValidGame, fs_gamedirvar->string, sizeof( lastValidGame ) );
}
/*
=================
FS_ConditionalRestart
Restart if necessary
Return qtrue if restarting due to game directory changed, qfalse otherwise
=================
*/
qboolean FS_ConditionalRestart(int checksumFeed, qboolean disconnect)
{
if(fs_gamedirvar->modified)
{
if(FS_FilenameCompare(lastValidGame, fs_gamedirvar->string) &&
(*lastValidGame || FS_FilenameCompare(fs_gamedirvar->string, com_basegame->string)) &&
(*fs_gamedirvar->string || FS_FilenameCompare(lastValidGame, com_basegame->string)))
{
Com_GameRestart(checksumFeed, disconnect);
return qtrue;
}
else
fs_gamedirvar->modified = qfalse;
}
if(checksumFeed != fs_checksumFeed)
FS_Restart(checksumFeed);
else if(fs_numServerPaks && !fs_reordered)
FS_ReorderPurePaks();
return qfalse;
}
/*
========================================================================================
Handle based file calls for virtual machines
========================================================================================
*/
int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
int r;
qboolean sync;
sync = qfalse;
switch( mode ) {
case FS_READ:
r = FS_FOpenFileRead( qpath, f, qtrue );
break;
case FS_WRITE:
*f = FS_FOpenFileWrite( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
case FS_APPEND_SYNC:
sync = qtrue;
case FS_APPEND:
*f = FS_FOpenFileAppend( qpath );
r = 0;
if (*f == 0) {
r = -1;
}
break;
default:
Com_Error( ERR_FATAL, "FS_FOpenFileByMode: bad mode" );
return -1;
}
if (!f) {
return r;
}
if ( *f ) {
fsh[*f].fileSize = r;
fsh[*f].streamed = qfalse;
if (mode == FS_READ) {
fsh[*f].streamed = qtrue;
}
}
fsh[*f].handleSync = sync;
return r;
}
int FS_FTell( fileHandle_t f ) {
int pos;
if ( fsh[f].zipFile == qtrue ) {
pos = unztell( fsh[f].handleFiles.file.z );
} else {
pos = ftell( fsh[f].handleFiles.file.o );
}
return pos;
}
void FS_Flush( fileHandle_t f ) {
fflush( fsh[f].handleFiles.file.o );
}
void FS_FilenameCompletion( const char *dir, const char *ext,
qboolean stripExt, void(*callback)(const char *s), qboolean allowNonPureFilesOnDisk ) {
char **filenames;
int nfiles;
int i;
char filename[ MAX_STRING_CHARS ];
filenames = FS_ListFilteredFiles( dir, ext, NULL, &nfiles, allowNonPureFilesOnDisk );
FS_SortFileList( filenames, nfiles );
for( i = 0; i < nfiles; i++ ) {
FS_ConvertPath( filenames[ i ] );
Q_strncpyz( filename, filenames[ i ], MAX_STRING_CHARS );
if( stripExt ) {
COM_StripExtension(filename, filename, sizeof(filename));
}
callback( filename );
}
FS_FreeFileList( filenames );
}
const char *FS_GetCurrentGameDir(void)
{
if(fs_gamedirvar->string[0])
return fs_gamedirvar->string;
return com_basegame->string;
}
// CVE-2006-2082
// compared requested pak against the names as we built them in FS_ReferencedPakNames
qboolean FS_VerifyPak( const char *pak ) {
char teststring[ BIG_INFO_STRING ];
searchpath_t *search;
for ( search = fs_searchpaths ; search ; search = search->next ) {
if ( search->pack ) {
Q_strncpyz( teststring, search->pack->pakGamename, sizeof( teststring ) );
Q_strcat( teststring, sizeof( teststring ), "/" );
Q_strcat( teststring, sizeof( teststring ), search->pack->pakBasename );
Q_strcat( teststring, sizeof( teststring ), ".pk3" );
if ( !Q_stricmp( teststring, pak ) ) {
return qtrue;
}
}
}
return qfalse;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3233_1 |
crossvul-cpp_data_bad_3229_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3229_0 |
crossvul-cpp_data_bad_2473_0 | /* bubblewrap
* Copyright (C) 2016 Alexander Larsson
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include <poll.h>
#include <sched.h>
#include <pwd.h>
#include <grp.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/eventfd.h>
#include <sys/fsuid.h>
#include <sys/signalfd.h>
#include <sys/capability.h>
#include <sys/prctl.h>
#include <linux/sched.h>
#include <linux/seccomp.h>
#include <linux/filter.h>
#include "utils.h"
#include "network.h"
#include "bind-mount.h"
#ifndef CLONE_NEWCGROUP
#define CLONE_NEWCGROUP 0x02000000 /* New cgroup namespace */
#endif
#ifndef TEMP_FAILURE_RETRY
#define TEMP_FAILURE_RETRY(expression) \
(__extension__ \
({ long int __result; \
do __result = (long int) (expression); \
while (__result == -1L && errno == EINTR); \
__result; }))
#endif
/* Globals to avoid having to use getuid(), since the uid/gid changes during runtime */
static uid_t real_uid;
static gid_t real_gid;
static uid_t overflow_uid;
static gid_t overflow_gid;
static bool is_privileged; /* See acquire_privs() */
static const char *argv0;
static const char *host_tty_dev;
static int proc_fd = -1;
static const char *opt_exec_label = NULL;
static const char *opt_file_label = NULL;
static bool opt_as_pid_1;
const char *opt_chdir_path = NULL;
bool opt_unshare_user = FALSE;
bool opt_unshare_user_try = FALSE;
bool opt_unshare_pid = FALSE;
bool opt_unshare_ipc = FALSE;
bool opt_unshare_net = FALSE;
bool opt_unshare_uts = FALSE;
bool opt_unshare_cgroup = FALSE;
bool opt_unshare_cgroup_try = FALSE;
bool opt_needs_devpts = FALSE;
bool opt_new_session = FALSE;
bool opt_die_with_parent = FALSE;
uid_t opt_sandbox_uid = -1;
gid_t opt_sandbox_gid = -1;
int opt_sync_fd = -1;
int opt_block_fd = -1;
int opt_userns_block_fd = -1;
int opt_info_fd = -1;
int opt_json_status_fd = -1;
int opt_seccomp_fd = -1;
const char *opt_sandbox_hostname = NULL;
char *opt_args_data = NULL; /* owned */
int opt_userns_fd = -1;
int opt_userns2_fd = -1;
int opt_pidns_fd = -1;
#define CAP_TO_MASK_0(x) (1L << ((x) & 31))
#define CAP_TO_MASK_1(x) CAP_TO_MASK_0(x - 32)
typedef struct _NsInfo NsInfo;
struct _NsInfo {
const char *name;
bool *do_unshare;
ino_t id;
};
static NsInfo ns_infos[] = {
{"cgroup", &opt_unshare_cgroup, 0},
{"ipc", &opt_unshare_ipc, 0},
{"mnt", NULL, 0},
{"net", &opt_unshare_net, 0},
{"pid", &opt_unshare_pid, 0},
/* user namespace info omitted because it
* is not (yet) valid when we obtain the
* namespace info (get un-shared later) */
{"uts", &opt_unshare_uts, 0},
{NULL, NULL, 0}
};
typedef enum {
SETUP_BIND_MOUNT,
SETUP_RO_BIND_MOUNT,
SETUP_DEV_BIND_MOUNT,
SETUP_MOUNT_PROC,
SETUP_MOUNT_DEV,
SETUP_MOUNT_TMPFS,
SETUP_MOUNT_MQUEUE,
SETUP_MAKE_DIR,
SETUP_MAKE_FILE,
SETUP_MAKE_BIND_FILE,
SETUP_MAKE_RO_BIND_FILE,
SETUP_MAKE_SYMLINK,
SETUP_REMOUNT_RO_NO_RECURSIVE,
SETUP_SET_HOSTNAME,
} SetupOpType;
typedef enum {
NO_CREATE_DEST = (1 << 0),
ALLOW_NOTEXIST = (2 << 0),
} SetupOpFlag;
typedef struct _SetupOp SetupOp;
struct _SetupOp
{
SetupOpType type;
const char *source;
const char *dest;
int fd;
SetupOpFlag flags;
SetupOp *next;
};
typedef struct _LockFile LockFile;
struct _LockFile
{
const char *path;
int fd;
LockFile *next;
};
static SetupOp *ops = NULL;
static SetupOp *last_op = NULL;
static LockFile *lock_files = NULL;
static LockFile *last_lock_file = NULL;
enum {
PRIV_SEP_OP_DONE,
PRIV_SEP_OP_BIND_MOUNT,
PRIV_SEP_OP_PROC_MOUNT,
PRIV_SEP_OP_TMPFS_MOUNT,
PRIV_SEP_OP_DEVPTS_MOUNT,
PRIV_SEP_OP_MQUEUE_MOUNT,
PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE,
PRIV_SEP_OP_SET_HOSTNAME,
};
typedef struct
{
uint32_t op;
uint32_t flags;
uint32_t arg1_offset;
uint32_t arg2_offset;
} PrivSepOp;
static SetupOp *
setup_op_new (SetupOpType type)
{
SetupOp *op = xcalloc (sizeof (SetupOp));
op->type = type;
op->fd = -1;
op->flags = 0;
if (last_op != NULL)
last_op->next = op;
else
ops = op;
last_op = op;
return op;
}
static LockFile *
lock_file_new (const char *path)
{
LockFile *lock = xcalloc (sizeof (LockFile));
lock->path = path;
if (last_lock_file != NULL)
last_lock_file->next = lock;
else
lock_files = lock;
last_lock_file = lock;
return lock;
}
static void
usage (int ecode, FILE *out)
{
fprintf (out, "usage: %s [OPTIONS...] [--] COMMAND [ARGS...]\n\n", argv0);
fprintf (out,
" --help Print this help\n"
" --version Print version\n"
" --args FD Parse NUL-separated args from FD\n"
" --unshare-all Unshare every namespace we support by default\n"
" --share-net Retain the network namespace (can only combine with --unshare-all)\n"
" --unshare-user Create new user namespace (may be automatically implied if not setuid)\n"
" --unshare-user-try Create new user namespace if possible else continue by skipping it\n"
" --unshare-ipc Create new ipc namespace\n"
" --unshare-pid Create new pid namespace\n"
" --unshare-net Create new network namespace\n"
" --unshare-uts Create new uts namespace\n"
" --unshare-cgroup Create new cgroup namespace\n"
" --unshare-cgroup-try Create new cgroup namespace if possible else continue by skipping it\n"
" --userns FD Use this user namespace (cannot combine with --unshare-user)\n"
" --userns2 FD After setup switch to this user namspace, only useful with --userns\n"
" --pidns FD Use this user namespace (as parent namespace if using --unshare-pid)\n"
" --uid UID Custom uid in the sandbox (requires --unshare-user or --userns)\n"
" --gid GID Custom gid in the sandbox (requires --unshare-user or --userns)\n"
" --hostname NAME Custom hostname in the sandbox (requires --unshare-uts)\n"
" --chdir DIR Change directory to DIR\n"
" --setenv VAR VALUE Set an environment variable\n"
" --unsetenv VAR Unset an environment variable\n"
" --lock-file DEST Take a lock on DEST while sandbox is running\n"
" --sync-fd FD Keep this fd open while sandbox is running\n"
" --bind SRC DEST Bind mount the host path SRC on DEST\n"
" --bind-try SRC DEST Equal to --bind but ignores non-existent SRC\n"
" --dev-bind SRC DEST Bind mount the host path SRC on DEST, allowing device access\n"
" --dev-bind-try SRC DEST Equal to --dev-bind but ignores non-existent SRC\n"
" --ro-bind SRC DEST Bind mount the host path SRC readonly on DEST\n"
" --ro-bind-try SRC DEST Equal to --ro-bind but ignores non-existent SRC\n"
" --remount-ro DEST Remount DEST as readonly; does not recursively remount\n"
" --exec-label LABEL Exec label for the sandbox\n"
" --file-label LABEL File label for temporary sandbox content\n"
" --proc DEST Mount new procfs on DEST\n"
" --dev DEST Mount new dev on DEST\n"
" --tmpfs DEST Mount new tmpfs on DEST\n"
" --mqueue DEST Mount new mqueue on DEST\n"
" --dir DEST Create dir at DEST\n"
" --file FD DEST Copy from FD to destination DEST\n"
" --bind-data FD DEST Copy from FD to file which is bind-mounted on DEST\n"
" --ro-bind-data FD DEST Copy from FD to file which is readonly bind-mounted on DEST\n"
" --symlink SRC DEST Create symlink at DEST with target SRC\n"
" --seccomp FD Load and use seccomp rules from FD\n"
" --block-fd FD Block on FD until some data to read is available\n"
" --userns-block-fd FD Block on FD until the user namespace is ready\n"
" --info-fd FD Write information about the running container to FD\n"
" --json-status-fd FD Write container status to FD as multiple JSON documents\n"
" --new-session Create a new terminal session\n"
" --die-with-parent Kills with SIGKILL child process (COMMAND) when bwrap or bwrap's parent dies.\n"
" --as-pid-1 Do not install a reaper process with PID=1\n"
" --cap-add CAP Add cap CAP when running as privileged user\n"
" --cap-drop CAP Drop cap CAP when running as privileged user\n"
);
exit (ecode);
}
/* If --die-with-parent was specified, use PDEATHSIG to ensure SIGKILL
* is sent to the current process when our parent dies.
*/
static void
handle_die_with_parent (void)
{
if (opt_die_with_parent && prctl (PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0) != 0)
die_with_error ("prctl");
}
static void
block_sigchild (void)
{
sigset_t mask;
int status;
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
if (sigprocmask (SIG_BLOCK, &mask, NULL) == -1)
die_with_error ("sigprocmask");
/* Reap any outstanding zombies that we may have inherited */
while (waitpid (-1, &status, WNOHANG) > 0)
;
}
static void
unblock_sigchild (void)
{
sigset_t mask;
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
if (sigprocmask (SIG_UNBLOCK, &mask, NULL) == -1)
die_with_error ("sigprocmask");
}
/* Closes all fd:s except 0,1,2 and the passed in array of extra fds */
static int
close_extra_fds (void *data, int fd)
{
int *extra_fds = (int *) data;
int i;
for (i = 0; extra_fds[i] != -1; i++)
if (fd == extra_fds[i])
return 0;
if (fd <= 2)
return 0;
close (fd);
return 0;
}
static int
propagate_exit_status (int status)
{
if (WIFEXITED (status))
return WEXITSTATUS (status);
/* The process died of a signal, we can't really report that, but we
* can at least be bash-compatible. The bash manpage says:
* The return value of a simple command is its
* exit status, or 128+n if the command is
* terminated by signal n.
*/
if (WIFSIGNALED (status))
return 128 + WTERMSIG (status);
/* Weird? */
return 255;
}
static void
dump_info (int fd, const char *output, bool exit_on_error)
{
size_t len = strlen (output);
if (write_to_fd (fd, output, len))
{
if (exit_on_error)
die_with_error ("Write to info_fd");
}
}
static void
report_child_exit_status (int exitc, int setup_finished_fd)
{
ssize_t s;
char data[2];
cleanup_free char *output = NULL;
if (opt_json_status_fd == -1 || setup_finished_fd == -1)
return;
s = TEMP_FAILURE_RETRY (read (setup_finished_fd, data, sizeof data));
if (s == -1 && errno != EAGAIN)
die_with_error ("read eventfd");
if (s != 1) // Is 0 if pipe closed before exec, is 2 if closed after exec.
return;
output = xasprintf ("{ \"exit-code\": %i }\n", exitc);
dump_info (opt_json_status_fd, output, FALSE);
close (opt_json_status_fd);
opt_json_status_fd = -1;
close (setup_finished_fd);
}
/* This stays around for as long as the initial process in the app does
* and when that exits it exits, propagating the exit status. We do this
* by having pid 1 in the sandbox detect this exit and tell the monitor
* the exit status via a eventfd. We also track the exit of the sandbox
* pid 1 via a signalfd for SIGCHLD, and exit with an error in this case.
* This is to catch e.g. problems during setup. */
static int
monitor_child (int event_fd, pid_t child_pid, int setup_finished_fd)
{
int res;
uint64_t val;
ssize_t s;
int signal_fd;
sigset_t mask;
struct pollfd fds[2];
int num_fds;
struct signalfd_siginfo fdsi;
int dont_close[] = {-1, -1, -1, -1};
int j = 0;
int exitc;
pid_t died_pid;
int died_status;
/* Close all extra fds in the monitoring process.
Any passed in fds have been passed on to the child anyway. */
if (event_fd != -1)
dont_close[j++] = event_fd;
if (opt_json_status_fd != -1)
dont_close[j++] = opt_json_status_fd;
if (setup_finished_fd != -1)
dont_close[j++] = setup_finished_fd;
assert (j < sizeof(dont_close)/sizeof(*dont_close));
fdwalk (proc_fd, close_extra_fds, dont_close);
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
signal_fd = signalfd (-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK);
if (signal_fd == -1)
die_with_error ("Can't create signalfd");
num_fds = 1;
fds[0].fd = signal_fd;
fds[0].events = POLLIN;
if (event_fd != -1)
{
fds[1].fd = event_fd;
fds[1].events = POLLIN;
num_fds++;
}
while (1)
{
fds[0].revents = fds[1].revents = 0;
res = poll (fds, num_fds, -1);
if (res == -1 && errno != EINTR)
die_with_error ("poll");
/* Always read from the eventfd first, if pid 2 died then pid 1 often
* dies too, and we could race, reporting that first and we'd lose
* the real exit status. */
if (event_fd != -1)
{
s = read (event_fd, &val, 8);
if (s == -1 && errno != EINTR && errno != EAGAIN)
die_with_error ("read eventfd");
else if (s == 8)
{
exitc = (int) val - 1;
report_child_exit_status (exitc, setup_finished_fd);
return exitc;
}
}
/* We need to read the signal_fd, or it will keep polling as read,
* however we ignore the details as we get them from waitpid
* below anyway */
s = read (signal_fd, &fdsi, sizeof (struct signalfd_siginfo));
if (s == -1 && errno != EINTR && errno != EAGAIN)
die_with_error ("read signalfd");
/* We may actually get several sigchld compressed into one
SIGCHLD, so we have to handle all of them. */
while ((died_pid = waitpid (-1, &died_status, WNOHANG)) > 0)
{
/* We may be getting sigchild from other children too. For instance if
someone created a child process, and then exec:ed bubblewrap. Ignore them */
if (died_pid == child_pid)
{
exitc = propagate_exit_status (died_status);
report_child_exit_status (exitc, setup_finished_fd);
return exitc;
}
}
}
die ("Should not be reached");
return 0;
}
/* This is pid 1 in the app sandbox. It is needed because we're using
* pid namespaces, and someone has to reap zombies in it. We also detect
* when the initial process (pid 2) dies and report its exit status to
* the monitor so that it can return it to the original spawner.
*
* When there are no other processes in the sandbox the wait will return
* ECHILD, and we then exit pid 1 to clean up the sandbox. */
static int
do_init (int event_fd, pid_t initial_pid, struct sock_fprog *seccomp_prog)
{
int initial_exit_status = 1;
LockFile *lock;
for (lock = lock_files; lock != NULL; lock = lock->next)
{
int fd = open (lock->path, O_RDONLY | O_CLOEXEC);
if (fd == -1)
die_with_error ("Unable to open lock file %s", lock->path);
struct flock l = {
.l_type = F_RDLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0
};
if (fcntl (fd, F_SETLK, &l) < 0)
die_with_error ("Unable to lock file %s", lock->path);
/* Keep fd open to hang on to lock */
lock->fd = fd;
}
/* Optionally bind our lifecycle to that of the caller */
handle_die_with_parent ();
if (seccomp_prog != NULL &&
prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, seccomp_prog) != 0)
die_with_error ("prctl(PR_SET_SECCOMP)");
while (TRUE)
{
pid_t child;
int status;
child = wait (&status);
if (child == initial_pid)
{
initial_exit_status = propagate_exit_status (status);
if(event_fd != -1)
{
uint64_t val;
int res UNUSED;
val = initial_exit_status + 1;
res = write (event_fd, &val, 8);
/* Ignore res, if e.g. the parent died and closed event_fd
we don't want to error out here */
}
}
if (child == -1 && errno != EINTR)
{
if (errno != ECHILD)
die_with_error ("init wait()");
break;
}
}
/* Close FDs. */
for (lock = lock_files; lock != NULL; lock = lock->next)
{
if (lock->fd >= 0)
{
close (lock->fd);
lock->fd = -1;
}
}
return initial_exit_status;
}
#define CAP_TO_MASK_0(x) (1L << ((x) & 31))
#define CAP_TO_MASK_1(x) CAP_TO_MASK_0(x - 32)
/* Set if --cap-add or --cap-drop were used */
static bool opt_cap_add_or_drop_used;
/* The capability set we'll target, used if above is true */
static uint32_t requested_caps[2] = {0, 0};
/* low 32bit caps needed */
/* CAP_SYS_PTRACE is needed to dereference the symlinks in /proc/<pid>/ns/, see namespaces(7) */
#define REQUIRED_CAPS_0 (CAP_TO_MASK_0 (CAP_SYS_ADMIN) | CAP_TO_MASK_0 (CAP_SYS_CHROOT) | CAP_TO_MASK_0 (CAP_NET_ADMIN) | CAP_TO_MASK_0 (CAP_SETUID) | CAP_TO_MASK_0 (CAP_SETGID) | CAP_TO_MASK_0 (CAP_SYS_PTRACE))
/* high 32bit caps needed */
#define REQUIRED_CAPS_1 0
static void
set_required_caps (void)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
/* Drop all non-require capabilities */
data[0].effective = REQUIRED_CAPS_0;
data[0].permitted = REQUIRED_CAPS_0;
data[0].inheritable = 0;
data[1].effective = REQUIRED_CAPS_1;
data[1].permitted = REQUIRED_CAPS_1;
data[1].inheritable = 0;
if (capset (&hdr, data) < 0)
die_with_error ("capset failed");
}
static void
drop_all_caps (bool keep_requested_caps)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (keep_requested_caps)
{
/* Avoid calling capset() unless we need to; currently
* systemd-nspawn at least is known to install a seccomp
* policy denying capset() for dubious reasons.
* <https://github.com/projectatomic/bubblewrap/pull/122>
*/
if (!opt_cap_add_or_drop_used && real_uid == 0)
{
assert (!is_privileged);
return;
}
data[0].effective = requested_caps[0];
data[0].permitted = requested_caps[0];
data[0].inheritable = requested_caps[0];
data[1].effective = requested_caps[1];
data[1].permitted = requested_caps[1];
data[1].inheritable = requested_caps[1];
}
if (capset (&hdr, data) < 0)
{
/* While the above logic ensures we don't call capset() for the primary
* process unless configured to do so, we still try to drop privileges for
* the init process unconditionally. Since due to the systemd seccomp
* filter that will fail, let's just ignore it.
*/
if (errno == EPERM && real_uid == 0 && !is_privileged)
return;
else
die_with_error ("capset failed");
}
}
static bool
has_caps (void)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (capget (&hdr, data) < 0)
die_with_error ("capget failed");
return data[0].permitted != 0 || data[1].permitted != 0;
}
/* Most of the code here is used both to add caps to the ambient capabilities
* and drop caps from the bounding set. Handle both cases here and add
* drop_cap_bounding_set/set_ambient_capabilities wrappers to facilitate its usage.
*/
static void
prctl_caps (uint32_t *caps, bool do_cap_bounding, bool do_set_ambient)
{
unsigned long cap;
/* We ignore both EINVAL and EPERM, as we are actually relying
* on PR_SET_NO_NEW_PRIVS to ensure the right capabilities are
* available. EPERM in particular can happen with old, buggy
* kernels. See:
* https://github.com/projectatomic/bubblewrap/pull/175#issuecomment-278051373
* https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/security/commoncap.c?id=160da84dbb39443fdade7151bc63a88f8e953077
*/
for (cap = 0; cap <= CAP_LAST_CAP; cap++)
{
bool keep = FALSE;
if (cap < 32)
{
if (CAP_TO_MASK_0 (cap) & caps[0])
keep = TRUE;
}
else
{
if (CAP_TO_MASK_1 (cap) & caps[1])
keep = TRUE;
}
if (keep && do_set_ambient)
{
#ifdef PR_CAP_AMBIENT
int res = prctl (PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, cap, 0, 0);
if (res == -1 && !(errno == EINVAL || errno == EPERM))
die_with_error ("Adding ambient capability %ld", cap);
#else
/* We ignore the EINVAL that results from not having PR_CAP_AMBIENT
* in the current kernel at runtime, so also ignore not having it
* in the current kernel headers at compile-time */
#endif
}
if (!keep && do_cap_bounding)
{
int res = prctl (PR_CAPBSET_DROP, cap, 0, 0, 0);
if (res == -1 && !(errno == EINVAL || errno == EPERM))
die_with_error ("Dropping capability %ld from bounds", cap);
}
}
}
static void
drop_cap_bounding_set (bool drop_all)
{
if (!drop_all)
prctl_caps (requested_caps, TRUE, FALSE);
else
{
uint32_t no_caps[2] = {0, 0};
prctl_caps (no_caps, TRUE, FALSE);
}
}
static void
set_ambient_capabilities (void)
{
if (is_privileged)
return;
prctl_caps (requested_caps, FALSE, TRUE);
}
/* This acquires the privileges that the bwrap will need it to work.
* If bwrap is not setuid, then this does nothing, and it relies on
* unprivileged user namespaces to be used. This case is
* "is_privileged = FALSE".
*
* If bwrap is setuid, then we do things in phases.
* The first part is run as euid 0, but with fsuid as the real user.
* The second part, inside the child, is run as the real user but with
* capabilities.
* And finally we drop all capabilities.
* The reason for the above dance is to avoid having the setup phase
* being able to read files the user can't, while at the same time
* working around various kernel issues. See below for details.
*/
static void
acquire_privs (void)
{
uid_t euid, new_fsuid;
euid = geteuid ();
/* Are we setuid ? */
if (real_uid != euid)
{
if (euid != 0)
die ("Unexpected setuid user %d, should be 0", euid);
is_privileged = TRUE;
/* We want to keep running as euid=0 until at the clone()
* operation because doing so will make the user namespace be
* owned by root, which makes it not ptrace:able by the user as
* it otherwise would be. After that we will run fully as the
* user, which is necessary e.g. to be able to read from a fuse
* mount from the user.
*
* However, we don't want to accidentally mis-use euid=0 for
* escalated filesystem access before the clone(), so we set
* fsuid to the uid.
*/
if (setfsuid (real_uid) < 0)
die_with_error ("Unable to set fsuid");
/* setfsuid can't properly report errors, check that it worked (as per manpage) */
new_fsuid = setfsuid (-1);
if (new_fsuid != real_uid)
die ("Unable to set fsuid (was %d)", (int)new_fsuid);
/* We never need capabilities after execve(), so lets drop everything from the bounding set */
drop_cap_bounding_set (TRUE);
/* Keep only the required capabilities for setup */
set_required_caps ();
}
else if (real_uid != 0 && has_caps ())
{
/* We have some capabilities in the non-setuid case, which should not happen.
Probably caused by the binary being setcap instead of setuid which we
don't support anymore */
die ("Unexpected capabilities but not setuid, old file caps config?");
}
else if (real_uid == 0)
{
/* If our uid is 0, default to inheriting all caps; the caller
* can drop them via --cap-drop. This is used by at least rpm-ostree.
* Note this needs to happen before the argument parsing of --cap-drop.
*/
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (capget (&hdr, data) < 0)
die_with_error ("capget (for uid == 0) failed");
requested_caps[0] = data[0].effective;
requested_caps[1] = data[1].effective;
}
/* Else, we try unprivileged user namespaces */
}
/* This is called once we're inside the namespace */
static void
switch_to_user_with_privs (void)
{
/* If we're in a new user namespace, we got back the bounding set, clear it again */
if (opt_unshare_user || opt_userns_fd != -1)
drop_cap_bounding_set (FALSE);
/* If we switched to a new user namespace it may allow other uids/gids, so switch to the target one */
if (opt_userns_fd != -1)
{
if (opt_sandbox_uid != real_uid && setuid (opt_sandbox_uid) < 0)
die_with_error ("unable to switch to uid %d", opt_sandbox_uid);
if (opt_sandbox_gid != real_gid && setgid (opt_sandbox_gid) < 0)
die_with_error ("unable to switch to gid %d", opt_sandbox_gid);
}
if (!is_privileged)
return;
/* Tell kernel not clear capabilities when later dropping root uid */
if (prctl (PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0)
die_with_error ("prctl(PR_SET_KEEPCAPS) failed");
if (setuid (opt_sandbox_uid) < 0)
die_with_error ("unable to drop root uid");
/* Regain effective required capabilities from permitted */
set_required_caps ();
}
/* Call setuid() and use capset() to adjust capabilities */
static void
drop_privs (bool keep_requested_caps)
{
assert (!keep_requested_caps || !is_privileged);
/* Drop root uid */
if (geteuid () == 0 && setuid (opt_sandbox_uid) < 0)
die_with_error ("unable to drop root uid");
drop_all_caps (keep_requested_caps);
/* We don't have any privs now, so mark us dumpable which makes /proc/self be owned by the user instead of root */
if (prctl (PR_SET_DUMPABLE, 1, 0, 0, 0) != 0)
die_with_error ("can't set dumpable");
}
static char *
get_newroot_path (const char *path)
{
while (*path == '/')
path++;
return strconcat ("/newroot/", path);
}
static char *
get_oldroot_path (const char *path)
{
while (*path == '/')
path++;
return strconcat ("/oldroot/", path);
}
static void
write_uid_gid_map (uid_t sandbox_uid,
uid_t parent_uid,
uid_t sandbox_gid,
uid_t parent_gid,
pid_t pid,
bool deny_groups,
bool map_root)
{
cleanup_free char *uid_map = NULL;
cleanup_free char *gid_map = NULL;
cleanup_free char *dir = NULL;
cleanup_fd int dir_fd = -1;
uid_t old_fsuid = -1;
if (pid == -1)
dir = xstrdup ("self");
else
dir = xasprintf ("%d", pid);
dir_fd = openat (proc_fd, dir, O_PATH);
if (dir_fd < 0)
die_with_error ("open /proc/%s failed", dir);
if (map_root && parent_uid != 0 && sandbox_uid != 0)
uid_map = xasprintf ("0 %d 1\n"
"%d %d 1\n", overflow_uid, sandbox_uid, parent_uid);
else
uid_map = xasprintf ("%d %d 1\n", sandbox_uid, parent_uid);
if (map_root && parent_gid != 0 && sandbox_gid != 0)
gid_map = xasprintf ("0 %d 1\n"
"%d %d 1\n", overflow_gid, sandbox_gid, parent_gid);
else
gid_map = xasprintf ("%d %d 1\n", sandbox_gid, parent_gid);
/* We have to be root to be allowed to write to the uid map
* for setuid apps, so temporary set fsuid to 0 */
if (is_privileged)
old_fsuid = setfsuid (0);
if (write_file_at (dir_fd, "uid_map", uid_map) != 0)
die_with_error ("setting up uid map");
if (deny_groups &&
write_file_at (dir_fd, "setgroups", "deny\n") != 0)
{
/* If /proc/[pid]/setgroups does not exist, assume we are
* running a linux kernel < 3.19, i.e. we live with the
* vulnerability known as CVE-2014-8989 in older kernels
* where setgroups does not exist.
*/
if (errno != ENOENT)
die_with_error ("error writing to setgroups");
}
if (write_file_at (dir_fd, "gid_map", gid_map) != 0)
die_with_error ("setting up gid map");
if (is_privileged)
{
setfsuid (old_fsuid);
if (setfsuid (-1) != real_uid)
die ("Unable to re-set fsuid");
}
}
static void
privileged_op (int privileged_op_socket,
uint32_t op,
uint32_t flags,
const char *arg1,
const char *arg2)
{
if (privileged_op_socket != -1)
{
uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */
PrivSepOp *op_buffer = (PrivSepOp *) buffer;
size_t buffer_size = sizeof (PrivSepOp);
uint32_t arg1_offset = 0, arg2_offset = 0;
/* We're unprivileged, send this request to the privileged part */
if (arg1 != NULL)
{
arg1_offset = buffer_size;
buffer_size += strlen (arg1) + 1;
}
if (arg2 != NULL)
{
arg2_offset = buffer_size;
buffer_size += strlen (arg2) + 1;
}
if (buffer_size >= sizeof (buffer))
die ("privilege separation operation to large");
op_buffer->op = op;
op_buffer->flags = flags;
op_buffer->arg1_offset = arg1_offset;
op_buffer->arg2_offset = arg2_offset;
if (arg1 != NULL)
strcpy ((char *) buffer + arg1_offset, arg1);
if (arg2 != NULL)
strcpy ((char *) buffer + arg2_offset, arg2);
if (write (privileged_op_socket, buffer, buffer_size) != buffer_size)
die ("Can't write to privileged_op_socket");
if (read (privileged_op_socket, buffer, 1) != 1)
die ("Can't read from privileged_op_socket");
return;
}
/*
* This runs a privileged request for the unprivileged setup
* code. Note that since the setup code is unprivileged it is not as
* trusted, so we need to verify that all requests only affect the
* child namespace as set up by the privileged parts of the setup,
* and that all the code is very careful about handling input.
*
* This means:
* * Bind mounts are safe, since we always use filesystem namespace. They
* must be recursive though, as otherwise you can use a non-recursive bind
* mount to access an otherwise over-mounted mountpoint.
* * Mounting proc, tmpfs, mqueue, devpts in the child namespace is assumed to
* be safe.
* * Remounting RO (even non-recursive) is safe because it decreases privileges.
* * sethostname() is safe only if we set up a UTS namespace
*/
switch (op)
{
case PRIV_SEP_OP_DONE:
break;
case PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE:
if (bind_mount (proc_fd, NULL, arg2, BIND_READONLY) != 0)
die_with_error ("Can't remount readonly on %s", arg2);
break;
case PRIV_SEP_OP_BIND_MOUNT:
/* We always bind directories recursively, otherwise this would let us
access files that are otherwise covered on the host */
if (bind_mount (proc_fd, arg1, arg2, BIND_RECURSIVE | flags) != 0)
die_with_error ("Can't bind mount %s on %s", arg1, arg2);
break;
case PRIV_SEP_OP_PROC_MOUNT:
if (mount ("proc", arg1, "proc", MS_NOSUID | MS_NOEXEC | MS_NODEV, NULL) != 0)
die_with_error ("Can't mount proc on %s", arg1);
break;
case PRIV_SEP_OP_TMPFS_MOUNT:
{
cleanup_free char *opt = label_mount ("mode=0755", opt_file_label);
if (mount ("tmpfs", arg1, "tmpfs", MS_NOSUID | MS_NODEV, opt) != 0)
die_with_error ("Can't mount tmpfs on %s", arg1);
break;
}
case PRIV_SEP_OP_DEVPTS_MOUNT:
if (mount ("devpts", arg1, "devpts", MS_NOSUID | MS_NOEXEC,
"newinstance,ptmxmode=0666,mode=620") != 0)
die_with_error ("Can't mount devpts on %s", arg1);
break;
case PRIV_SEP_OP_MQUEUE_MOUNT:
if (mount ("mqueue", arg1, "mqueue", 0, NULL) != 0)
die_with_error ("Can't mount mqueue on %s", arg1);
break;
case PRIV_SEP_OP_SET_HOSTNAME:
/* This is checked at the start, but lets verify it here in case
something manages to send hacked priv-sep operation requests. */
if (!opt_unshare_uts)
die ("Refusing to set hostname in original namespace");
if (sethostname (arg1, strlen(arg1)) != 0)
die_with_error ("Can't set hostname to %s", arg1);
break;
default:
die ("Unexpected privileged op %d", op);
}
}
/* This is run unprivileged in the child namespace but can request
* some privileged operations (also in the child namespace) via the
* privileged_op_socket.
*/
static void
setup_newroot (bool unshare_pid,
int privileged_op_socket)
{
SetupOp *op;
for (op = ops; op != NULL; op = op->next)
{
cleanup_free char *source = NULL;
cleanup_free char *dest = NULL;
int source_mode = 0;
int i;
if (op->source &&
op->type != SETUP_MAKE_SYMLINK)
{
source = get_oldroot_path (op->source);
source_mode = get_file_mode (source);
if (source_mode < 0)
{
if (op->flags & ALLOW_NOTEXIST && errno == ENOENT)
continue; /* Ignore and move on */
die_with_error("Can't get type of source %s", op->source);
}
}
if (op->dest &&
(op->flags & NO_CREATE_DEST) == 0)
{
dest = get_newroot_path (op->dest);
if (mkdir_with_parents (dest, 0755, FALSE) != 0)
die_with_error ("Can't mkdir parents for %s", op->dest);
}
switch (op->type)
{
case SETUP_RO_BIND_MOUNT:
case SETUP_DEV_BIND_MOUNT:
case SETUP_BIND_MOUNT:
if (source_mode == S_IFDIR)
{
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
}
else if (ensure_file (dest, 0666) != 0)
die_with_error ("Can't create file at %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT,
(op->type == SETUP_RO_BIND_MOUNT ? BIND_READONLY : 0) |
(op->type == SETUP_DEV_BIND_MOUNT ? BIND_DEVICES : 0),
source, dest);
break;
case SETUP_REMOUNT_RO_NO_RECURSIVE:
privileged_op (privileged_op_socket,
PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE, 0, NULL, dest);
break;
case SETUP_MOUNT_PROC:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
if (unshare_pid || opt_pidns_fd != -1)
{
/* Our own procfs */
privileged_op (privileged_op_socket,
PRIV_SEP_OP_PROC_MOUNT, 0,
dest, NULL);
}
else
{
/* Use system procfs, as we share pid namespace anyway */
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, 0,
"oldroot/proc", dest);
}
/* There are a bunch of weird old subdirs of /proc that could potentially be
problematic (for instance /proc/sysrq-trigger lets you shut down the machine
if you have write access). We should not have access to these as a non-privileged
user, but lets cover them anyway just to make sure */
const char *cover_proc_dirs[] = { "sys", "sysrq-trigger", "irq", "bus" };
for (i = 0; i < N_ELEMENTS (cover_proc_dirs); i++)
{
cleanup_free char *subdir = strconcat3 (dest, "/", cover_proc_dirs[i]);
if (access (subdir, W_OK) < 0)
{
/* The file is already read-only or doesn't exist. */
if (errno == EACCES || errno == ENOENT)
continue;
die_with_error ("Can't access %s", subdir);
}
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, BIND_READONLY,
subdir, subdir);
}
break;
case SETUP_MOUNT_DEV:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_TMPFS_MOUNT, 0,
dest, NULL);
static const char *const devnodes[] = { "null", "zero", "full", "random", "urandom", "tty" };
for (i = 0; i < N_ELEMENTS (devnodes); i++)
{
cleanup_free char *node_dest = strconcat3 (dest, "/", devnodes[i]);
cleanup_free char *node_src = strconcat ("/oldroot/dev/", devnodes[i]);
if (create_file (node_dest, 0666, NULL) != 0)
die_with_error ("Can't create file %s/%s", op->dest, devnodes[i]);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, BIND_DEVICES,
node_src, node_dest);
}
static const char *const stdionodes[] = { "stdin", "stdout", "stderr" };
for (i = 0; i < N_ELEMENTS (stdionodes); i++)
{
cleanup_free char *target = xasprintf ("/proc/self/fd/%d", i);
cleanup_free char *node_dest = strconcat3 (dest, "/", stdionodes[i]);
if (symlink (target, node_dest) < 0)
die_with_error ("Can't create symlink %s/%s", op->dest, stdionodes[i]);
}
/* /dev/fd and /dev/core - legacy, but both nspawn and docker do these */
{ cleanup_free char *dev_fd = strconcat (dest, "/fd");
if (symlink ("/proc/self/fd", dev_fd) < 0)
die_with_error ("Can't create symlink %s", dev_fd);
}
{ cleanup_free char *dev_core = strconcat (dest, "/core");
if (symlink ("/proc/kcore", dev_core) < 0)
die_with_error ("Can't create symlink %s", dev_core);
}
{
cleanup_free char *pts = strconcat (dest, "/pts");
cleanup_free char *ptmx = strconcat (dest, "/ptmx");
cleanup_free char *shm = strconcat (dest, "/shm");
if (mkdir (shm, 0755) == -1)
die_with_error ("Can't create %s/shm", op->dest);
if (mkdir (pts, 0755) == -1)
die_with_error ("Can't create %s/devpts", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_DEVPTS_MOUNT, 0, pts, NULL);
if (symlink ("pts/ptmx", ptmx) != 0)
die_with_error ("Can't make symlink at %s/ptmx", op->dest);
}
/* If stdout is a tty, that means the sandbox can write to the
outside-sandbox tty. In that case we also create a /dev/console
that points to this tty device. This should not cause any more
access than we already have, and it makes ttyname() work in the
sandbox. */
if (host_tty_dev != NULL && *host_tty_dev != 0)
{
cleanup_free char *src_tty_dev = strconcat ("/oldroot", host_tty_dev);
cleanup_free char *dest_console = strconcat (dest, "/console");
if (create_file (dest_console, 0666, NULL) != 0)
die_with_error ("creating %s/console", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, BIND_DEVICES,
src_tty_dev, dest_console);
}
break;
case SETUP_MOUNT_TMPFS:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_TMPFS_MOUNT, 0,
dest, NULL);
break;
case SETUP_MOUNT_MQUEUE:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_MQUEUE_MOUNT, 0,
dest, NULL);
break;
case SETUP_MAKE_DIR:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
break;
case SETUP_MAKE_FILE:
{
cleanup_fd int dest_fd = -1;
dest_fd = creat (dest, 0666);
if (dest_fd == -1)
die_with_error ("Can't create file %s", op->dest);
if (copy_file_data (op->fd, dest_fd) != 0)
die_with_error ("Can't write data to file %s", op->dest);
close (op->fd);
op->fd = -1;
}
break;
case SETUP_MAKE_BIND_FILE:
case SETUP_MAKE_RO_BIND_FILE:
{
cleanup_fd int dest_fd = -1;
char tempfile[] = "/bindfileXXXXXX";
dest_fd = mkstemp (tempfile);
if (dest_fd == -1)
die_with_error ("Can't create tmpfile for %s", op->dest);
if (copy_file_data (op->fd, dest_fd) != 0)
die_with_error ("Can't write data to file %s", op->dest);
close (op->fd);
op->fd = -1;
assert (dest != NULL);
if (ensure_file (dest, 0666) != 0)
die_with_error ("Can't create file at %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT,
(op->type == SETUP_MAKE_RO_BIND_FILE ? BIND_READONLY : 0),
tempfile, dest);
/* Remove the file so we're sure the app can't get to it in any other way.
Its outside the container chroot, so it shouldn't be possible, but lets
make it really sure. */
unlink (tempfile);
}
break;
case SETUP_MAKE_SYMLINK:
assert (op->source != NULL); /* guaranteed by the constructor */
if (symlink (op->source, dest) != 0)
die_with_error ("Can't make symlink at %s", op->dest);
break;
case SETUP_SET_HOSTNAME:
assert (op->dest != NULL); /* guaranteed by the constructor */
privileged_op (privileged_op_socket,
PRIV_SEP_OP_SET_HOSTNAME, 0,
op->dest, NULL);
break;
default:
die ("Unexpected type %d", op->type);
}
}
privileged_op (privileged_op_socket,
PRIV_SEP_OP_DONE, 0, NULL, NULL);
}
/* Do not leak file descriptors already used by setup_newroot () */
static void
close_ops_fd (void)
{
SetupOp *op;
for (op = ops; op != NULL; op = op->next)
{
if (op->fd != -1)
{
(void) close (op->fd);
op->fd = -1;
}
}
}
/* We need to resolve relative symlinks in the sandbox before we
chroot so that absolute symlinks are handled correctly. We also
need to do this after we've switched to the real uid so that
e.g. paths on fuse mounts work */
static void
resolve_symlinks_in_ops (void)
{
SetupOp *op;
for (op = ops; op != NULL; op = op->next)
{
const char *old_source;
switch (op->type)
{
case SETUP_RO_BIND_MOUNT:
case SETUP_DEV_BIND_MOUNT:
case SETUP_BIND_MOUNT:
old_source = op->source;
op->source = realpath (old_source, NULL);
if (op->source == NULL)
{
if (op->flags & ALLOW_NOTEXIST && errno == ENOENT)
op->source = old_source;
else
die_with_error("Can't find source path %s", old_source);
}
break;
default:
break;
}
}
}
static const char *
resolve_string_offset (void *buffer,
size_t buffer_size,
uint32_t offset)
{
if (offset == 0)
return NULL;
if (offset > buffer_size)
die ("Invalid string offset %d (buffer size %zd)", offset, buffer_size);
return (const char *) buffer + offset;
}
static uint32_t
read_priv_sec_op (int read_socket,
void *buffer,
size_t buffer_size,
uint32_t *flags,
const char **arg1,
const char **arg2)
{
const PrivSepOp *op = (const PrivSepOp *) buffer;
ssize_t rec_len;
do
rec_len = read (read_socket, buffer, buffer_size - 1);
while (rec_len == -1 && errno == EINTR);
if (rec_len < 0)
die_with_error ("Can't read from unprivileged helper");
if (rec_len == 0)
exit (1); /* Privileged helper died and printed error, so exit silently */
if (rec_len < sizeof (PrivSepOp))
die ("Invalid size %zd from unprivileged helper", rec_len);
/* Guarantee zero termination of any strings */
((char *) buffer)[rec_len] = 0;
*flags = op->flags;
*arg1 = resolve_string_offset (buffer, rec_len, op->arg1_offset);
*arg2 = resolve_string_offset (buffer, rec_len, op->arg2_offset);
return op->op;
}
static void __attribute__ ((noreturn))
print_version_and_exit (void)
{
printf ("%s\n", PACKAGE_STRING);
exit (0);
}
static void
parse_args_recurse (int *argcp,
const char ***argvp,
bool in_file,
int *total_parsed_argc_p)
{
SetupOp *op;
int argc = *argcp;
const char **argv = *argvp;
/* I can't imagine a case where someone wants more than this.
* If you do...you should be able to pass multiple files
* via a single tmpfs and linking them there, etc.
*
* We're adding this hardening due to precedent from
* http://googleprojectzero.blogspot.com/2014/08/the-poisoned-nul-byte-2014-edition.html
*
* I picked 9000 because the Internet told me to and it was hard to
* resist.
*/
static const uint32_t MAX_ARGS = 9000;
if (*total_parsed_argc_p > MAX_ARGS)
die ("Exceeded maximum number of arguments %u", MAX_ARGS);
while (argc > 0)
{
const char *arg = argv[0];
if (strcmp (arg, "--help") == 0)
{
usage (EXIT_SUCCESS, stdout);
}
else if (strcmp (arg, "--version") == 0)
{
print_version_and_exit ();
}
else if (strcmp (arg, "--args") == 0)
{
int the_fd;
char *endptr;
const char *p, *data_end;
size_t data_len;
cleanup_free const char **data_argv = NULL;
const char **data_argv_copy;
int data_argc;
int i;
if (in_file)
die ("--args not supported in arguments file");
if (argc < 2)
die ("--args takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
/* opt_args_data is essentially a recursive argv array, which we must
* keep allocated until exit time, since its argv entries get used
* by the other cases in parse_args_recurse() when we recurse. */
opt_args_data = load_file_data (the_fd, &data_len);
if (opt_args_data == NULL)
die_with_error ("Can't read --args data");
(void) close (the_fd);
data_end = opt_args_data + data_len;
data_argc = 0;
p = opt_args_data;
while (p != NULL && p < data_end)
{
data_argc++;
(*total_parsed_argc_p)++;
if (*total_parsed_argc_p > MAX_ARGS)
die ("Exceeded maximum number of arguments %u", MAX_ARGS);
p = memchr (p, 0, data_end - p);
if (p != NULL)
p++;
}
data_argv = xcalloc (sizeof (char *) * (data_argc + 1));
i = 0;
p = opt_args_data;
while (p != NULL && p < data_end)
{
/* Note: load_file_data always adds a nul terminator, so this is safe
* even for the last string. */
data_argv[i++] = p;
p = memchr (p, 0, data_end - p);
if (p != NULL)
p++;
}
data_argv_copy = data_argv; /* Don't change data_argv, we need to free it */
parse_args_recurse (&data_argc, &data_argv_copy, TRUE, total_parsed_argc_p);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--unshare-all") == 0)
{
/* Keep this in order with the older (legacy) --unshare arguments,
* we use the --try variants of user and cgroup, since we want
* to support systems/kernels without support for those.
*/
opt_unshare_user_try = opt_unshare_ipc = opt_unshare_pid =
opt_unshare_uts = opt_unshare_cgroup_try =
opt_unshare_net = TRUE;
}
/* Begin here the older individual --unshare variants */
else if (strcmp (arg, "--unshare-user") == 0)
{
opt_unshare_user = TRUE;
}
else if (strcmp (arg, "--unshare-user-try") == 0)
{
opt_unshare_user_try = TRUE;
}
else if (strcmp (arg, "--unshare-ipc") == 0)
{
opt_unshare_ipc = TRUE;
}
else if (strcmp (arg, "--unshare-pid") == 0)
{
opt_unshare_pid = TRUE;
}
else if (strcmp (arg, "--unshare-net") == 0)
{
opt_unshare_net = TRUE;
}
else if (strcmp (arg, "--unshare-uts") == 0)
{
opt_unshare_uts = TRUE;
}
else if (strcmp (arg, "--unshare-cgroup") == 0)
{
opt_unshare_cgroup = TRUE;
}
else if (strcmp (arg, "--unshare-cgroup-try") == 0)
{
opt_unshare_cgroup_try = TRUE;
}
/* Begin here the newer --share variants */
else if (strcmp (arg, "--share-net") == 0)
{
opt_unshare_net = FALSE;
}
/* End --share variants, other arguments begin */
else if (strcmp (arg, "--chdir") == 0)
{
if (argc < 2)
die ("--chdir takes one argument");
opt_chdir_path = argv[1];
argv++;
argc--;
}
else if (strcmp (arg, "--remount-ro") == 0)
{
if (argc < 2)
die ("--remount-ro takes one argument");
SetupOp *op = setup_op_new (SETUP_REMOUNT_RO_NO_RECURSIVE);
op->dest = argv[1];
argv++;
argc--;
}
else if (strcmp(arg, "--bind") == 0 ||
strcmp(arg, "--bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp(arg, "--ro-bind") == 0 ||
strcmp(arg, "--ro-bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_RO_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--ro-bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--dev-bind") == 0 ||
strcmp (arg, "--dev-bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_DEV_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--dev-bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--proc") == 0)
{
if (argc < 2)
die ("--proc takes an argument");
op = setup_op_new (SETUP_MOUNT_PROC);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--exec-label") == 0)
{
if (argc < 2)
die ("--exec-label takes an argument");
opt_exec_label = argv[1];
die_unless_label_valid (opt_exec_label);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--file-label") == 0)
{
if (argc < 2)
die ("--file-label takes an argument");
opt_file_label = argv[1];
die_unless_label_valid (opt_file_label);
if (label_create_file (opt_file_label))
die_with_error ("--file-label setup failed");
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--dev") == 0)
{
if (argc < 2)
die ("--dev takes an argument");
op = setup_op_new (SETUP_MOUNT_DEV);
op->dest = argv[1];
opt_needs_devpts = TRUE;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--tmpfs") == 0)
{
if (argc < 2)
die ("--tmpfs takes an argument");
op = setup_op_new (SETUP_MOUNT_TMPFS);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--mqueue") == 0)
{
if (argc < 2)
die ("--mqueue takes an argument");
op = setup_op_new (SETUP_MOUNT_MQUEUE);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--dir") == 0)
{
if (argc < 2)
die ("--dir takes an argument");
op = setup_op_new (SETUP_MAKE_DIR);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--file") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--file takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--bind-data") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--bind-data takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_BIND_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--ro-bind-data") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--ro-bind-data takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_RO_BIND_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--symlink") == 0)
{
if (argc < 3)
die ("--symlink takes two arguments");
op = setup_op_new (SETUP_MAKE_SYMLINK);
op->source = argv[1];
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--lock-file") == 0)
{
if (argc < 2)
die ("--lock-file takes an argument");
(void) lock_file_new (argv[1]);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--sync-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--sync-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_sync_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--block-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--block-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_block_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--userns-block-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--userns-block-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_userns_block_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--info-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--info-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_info_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--json-status-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--json-status-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_json_status_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--seccomp") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--seccomp takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_seccomp_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--userns") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--userns takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_userns_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--userns2") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--userns2 takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_userns2_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--pidns") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--pidns takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_pidns_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--setenv") == 0)
{
if (argc < 3)
die ("--setenv takes two arguments");
xsetenv (argv[1], argv[2], 1);
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--unsetenv") == 0)
{
if (argc < 2)
die ("--unsetenv takes an argument");
xunsetenv (argv[1]);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--uid") == 0)
{
int the_uid;
char *endptr;
if (argc < 2)
die ("--uid takes an argument");
the_uid = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_uid < 0)
die ("Invalid uid: %s", argv[1]);
opt_sandbox_uid = the_uid;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--gid") == 0)
{
int the_gid;
char *endptr;
if (argc < 2)
die ("--gid takes an argument");
the_gid = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_gid < 0)
die ("Invalid gid: %s", argv[1]);
opt_sandbox_gid = the_gid;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--hostname") == 0)
{
if (argc < 2)
die ("--hostname takes an argument");
op = setup_op_new (SETUP_SET_HOSTNAME);
op->dest = argv[1];
op->flags = NO_CREATE_DEST;
opt_sandbox_hostname = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--new-session") == 0)
{
opt_new_session = TRUE;
}
else if (strcmp (arg, "--die-with-parent") == 0)
{
opt_die_with_parent = TRUE;
}
else if (strcmp (arg, "--as-pid-1") == 0)
{
opt_as_pid_1 = TRUE;
}
else if (strcmp (arg, "--cap-add") == 0)
{
cap_value_t cap;
if (argc < 2)
die ("--cap-add takes an argument");
opt_cap_add_or_drop_used = TRUE;
if (strcasecmp (argv[1], "ALL") == 0)
{
requested_caps[0] = requested_caps[1] = 0xFFFFFFFF;
}
else
{
if (cap_from_name (argv[1], &cap) < 0)
die ("unknown cap: %s", argv[1]);
if (cap < 32)
requested_caps[0] |= CAP_TO_MASK_0 (cap);
else
requested_caps[1] |= CAP_TO_MASK_1 (cap - 32);
}
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--cap-drop") == 0)
{
cap_value_t cap;
if (argc < 2)
die ("--cap-drop takes an argument");
opt_cap_add_or_drop_used = TRUE;
if (strcasecmp (argv[1], "ALL") == 0)
{
requested_caps[0] = requested_caps[1] = 0;
}
else
{
if (cap_from_name (argv[1], &cap) < 0)
die ("unknown cap: %s", argv[1]);
if (cap < 32)
requested_caps[0] &= ~CAP_TO_MASK_0 (cap);
else
requested_caps[1] &= ~CAP_TO_MASK_1 (cap - 32);
}
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--") == 0)
{
argv += 1;
argc -= 1;
break;
}
else if (*arg == '-')
{
die ("Unknown option %s", arg);
}
else
{
break;
}
argv++;
argc--;
}
*argcp = argc;
*argvp = argv;
}
static void
parse_args (int *argcp,
const char ***argvp)
{
int total_parsed_argc = *argcp;
parse_args_recurse (argcp, argvp, FALSE, &total_parsed_argc);
}
static void
read_overflowids (void)
{
cleanup_free char *uid_data = NULL;
cleanup_free char *gid_data = NULL;
uid_data = load_file_at (AT_FDCWD, "/proc/sys/kernel/overflowuid");
if (uid_data == NULL)
die_with_error ("Can't read /proc/sys/kernel/overflowuid");
overflow_uid = strtol (uid_data, NULL, 10);
if (overflow_uid == 0)
die ("Can't parse /proc/sys/kernel/overflowuid");
gid_data = load_file_at (AT_FDCWD, "/proc/sys/kernel/overflowgid");
if (gid_data == NULL)
die_with_error ("Can't read /proc/sys/kernel/overflowgid");
overflow_gid = strtol (gid_data, NULL, 10);
if (overflow_gid == 0)
die ("Can't parse /proc/sys/kernel/overflowgid");
}
static void
namespace_ids_read (pid_t pid)
{
cleanup_free char *dir = NULL;
cleanup_fd int ns_fd = -1;
NsInfo *info;
dir = xasprintf ("%d/ns", pid);
ns_fd = openat (proc_fd, dir, O_PATH);
if (ns_fd < 0)
die_with_error ("open /proc/%s/ns failed", dir);
for (info = ns_infos; info->name; info++)
{
bool *do_unshare = info->do_unshare;
struct stat st;
int r;
/* if we don't unshare this ns, ignore it */
if (do_unshare && *do_unshare == FALSE)
continue;
r = fstatat (ns_fd, info->name, &st, 0);
/* if we can't get the information, ignore it */
if (r != 0)
continue;
info->id = st.st_ino;
}
}
static void
namespace_ids_write (int fd,
bool in_json)
{
NsInfo *info;
for (info = ns_infos; info->name; info++)
{
cleanup_free char *output = NULL;
const char *indent;
uintmax_t nsid;
nsid = (uintmax_t) info->id;
/* if we don't have the information, we don't write it */
if (nsid == 0)
continue;
indent = in_json ? " " : "\n ";
output = xasprintf (",%s\"%s-namespace\": %ju",
indent, info->name, nsid);
dump_info (fd, output, TRUE);
}
}
int
main (int argc,
char **argv)
{
mode_t old_umask;
const char *base_path = NULL;
int clone_flags;
char *old_cwd = NULL;
pid_t pid;
int event_fd = -1;
int child_wait_fd = -1;
int setup_finished_pipe[] = {-1, -1};
const char *new_cwd;
uid_t ns_uid;
gid_t ns_gid;
struct stat sbuf;
uint64_t val;
int res UNUSED;
cleanup_free char *seccomp_data = NULL;
size_t seccomp_len;
struct sock_fprog seccomp_prog;
cleanup_free char *args_data = NULL;
int intermediate_pids_sockets[2] = {-1, -1};
/* Handle --version early on before we try to acquire/drop
* any capabilities so it works in a build environment;
* right now flatpak's build runs bubblewrap --version.
* https://github.com/projectatomic/bubblewrap/issues/185
*/
if (argc == 2 && (strcmp (argv[1], "--version") == 0))
print_version_and_exit ();
real_uid = getuid ();
real_gid = getgid ();
/* Get the (optional) privileges we need */
acquire_privs ();
/* Never gain any more privs during exec */
if (prctl (PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0)
die_with_error ("prctl(PR_SET_NO_NEW_CAPS) failed");
/* The initial code is run with high permissions
(i.e. CAP_SYS_ADMIN), so take lots of care. */
read_overflowids ();
argv0 = argv[0];
if (isatty (1))
host_tty_dev = ttyname (1);
argv++;
argc--;
if (argc == 0)
usage (EXIT_FAILURE, stderr);
parse_args (&argc, (const char ***) &argv);
/* suck the args into a cleanup_free variable to control their lifecycle */
args_data = opt_args_data;
opt_args_data = NULL;
if ((requested_caps[0] || requested_caps[1]) && is_privileged)
die ("--cap-add in setuid mode can be used only by root");
if (opt_userns_block_fd != -1 && !opt_unshare_user)
die ("--userns-block-fd requires --unshare-user");
if (opt_userns_block_fd != -1 && opt_info_fd == -1)
die ("--userns-block-fd requires --info-fd");
if (opt_userns_fd != -1 && opt_unshare_user)
die ("--userns not compatible --unshare-user");
if (opt_userns_fd != -1 && opt_unshare_user_try)
die ("--userns not compatible --unshare-user-try");
/* Technically using setns() is probably safe even in the privileged
* case, because we got passed in a file descriptor to the
* namespace, and that can only be gotten if you have ptrace
* permissions against the target, and then you could do whatever to
* the namespace anyway.
*
* However, for practical reasons this isn't possible to use,
* because (as described in acquire_privs()) setuid bwrap causes
* root to own the namespaces that it creates, so you will not be
* able to access these namespaces anyway. So, best just not support
* it anway.
*/
if (opt_userns_fd != -1 && is_privileged)
die ("--userns doesn't work in setuid mode");
/* We have to do this if we weren't installed setuid (and we're not
* root), so let's just DWIM */
if (!is_privileged && getuid () != 0 && opt_userns_fd == -1)
opt_unshare_user = TRUE;
#ifdef ENABLE_REQUIRE_USERNS
/* In this build option, we require userns. */
if (is_privileged && getuid () != 0 && opt_userns_fd == -1)
opt_unshare_user = TRUE;
#endif
if (opt_unshare_user_try &&
stat ("/proc/self/ns/user", &sbuf) == 0)
{
bool disabled = FALSE;
/* RHEL7 has a kernel module parameter that lets you enable user namespaces */
if (stat ("/sys/module/user_namespace/parameters/enable", &sbuf) == 0)
{
cleanup_free char *enable = NULL;
enable = load_file_at (AT_FDCWD, "/sys/module/user_namespace/parameters/enable");
if (enable != NULL && enable[0] == 'N')
disabled = TRUE;
}
/* Check for max_user_namespaces */
if (stat ("/proc/sys/user/max_user_namespaces", &sbuf) == 0)
{
cleanup_free char *max_user_ns = NULL;
max_user_ns = load_file_at (AT_FDCWD, "/proc/sys/user/max_user_namespaces");
if (max_user_ns != NULL && strcmp(max_user_ns, "0\n") == 0)
disabled = TRUE;
}
/* Debian lets you disable *unprivileged* user namespaces. However this is not
a problem if we're privileged, and if we're not opt_unshare_user is TRUE
already, and there is not much we can do, its just a non-working setup. */
if (!disabled)
opt_unshare_user = TRUE;
}
if (argc == 0)
usage (EXIT_FAILURE, stderr);
__debug__ (("Creating root mount point\n"));
if (opt_sandbox_uid == -1)
opt_sandbox_uid = real_uid;
if (opt_sandbox_gid == -1)
opt_sandbox_gid = real_gid;
if (!opt_unshare_user && opt_userns_fd == -1 && opt_sandbox_uid != real_uid)
die ("Specifying --uid requires --unshare-user or --userns");
if (!opt_unshare_user && opt_userns_fd == -1 && opt_sandbox_gid != real_gid)
die ("Specifying --gid requires --unshare-user or --userns");
if (!opt_unshare_uts && opt_sandbox_hostname != NULL)
die ("Specifying --hostname requires --unshare-uts");
if (opt_as_pid_1 && !opt_unshare_pid)
die ("Specifying --as-pid-1 requires --unshare-pid");
if (opt_as_pid_1 && lock_files != NULL)
die ("Specifying --as-pid-1 and --lock-file is not permitted");
/* We need to read stuff from proc during the pivot_root dance, etc.
Lets keep a fd to it open */
proc_fd = open ("/proc", O_PATH);
if (proc_fd == -1)
die_with_error ("Can't open /proc");
/* We need *some* mountpoint where we can mount the root tmpfs.
* Because we use pivot_root, it won't appear to be mounted from
* the perspective of the sandboxed process, so we can use anywhere
* that is sure to exist, that is sure to not be a symlink controlled
* by someone malicious, and that we won't immediately need to
* access ourselves. */
base_path = "/tmp";
__debug__ (("creating new namespace\n"));
if (opt_unshare_pid && !opt_as_pid_1)
{
event_fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK);
if (event_fd == -1)
die_with_error ("eventfd()");
}
/* We block sigchild here so that we can use signalfd in the monitor. */
block_sigchild ();
clone_flags = SIGCHLD | CLONE_NEWNS;
if (opt_unshare_user)
clone_flags |= CLONE_NEWUSER;
if (opt_unshare_pid && opt_pidns_fd == -1)
clone_flags |= CLONE_NEWPID;
if (opt_unshare_net)
clone_flags |= CLONE_NEWNET;
if (opt_unshare_ipc)
clone_flags |= CLONE_NEWIPC;
if (opt_unshare_uts)
clone_flags |= CLONE_NEWUTS;
if (opt_unshare_cgroup)
{
if (stat ("/proc/self/ns/cgroup", &sbuf))
{
if (errno == ENOENT)
die ("Cannot create new cgroup namespace because the kernel does not support it");
else
die_with_error ("stat on /proc/self/ns/cgroup failed");
}
clone_flags |= CLONE_NEWCGROUP;
}
if (opt_unshare_cgroup_try)
{
opt_unshare_cgroup = !stat ("/proc/self/ns/cgroup", &sbuf);
if (opt_unshare_cgroup)
clone_flags |= CLONE_NEWCGROUP;
}
child_wait_fd = eventfd (0, EFD_CLOEXEC);
if (child_wait_fd == -1)
die_with_error ("eventfd()");
/* Track whether pre-exec setup finished if we're reporting process exit */
if (opt_json_status_fd != -1)
{
int ret;
ret = pipe2 (setup_finished_pipe, O_CLOEXEC);
if (ret == -1)
die_with_error ("pipe2()");
}
/* Switch to the custom user ns before the clone, gets us privs in that ns (assuming its a child of the current and thus allowed) */
if (opt_userns_fd > 0 && setns (opt_userns_fd, CLONE_NEWUSER) != 0)
{
if (errno == EINVAL)
die ("Joining the specified user namespace failed, it might not be a descendant of the current user namespace.");
die_with_error ("Joining specified user namespace failed");
}
/* Sometimes we have uninteresting intermediate pids during the setup, set up code to pass the real pid down */
if (opt_pidns_fd != -1)
{
/* Mark us as a subreaper, this way we can get exit status from grandchildren */
prctl (PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0);
create_pid_socketpair (intermediate_pids_sockets);
}
pid = raw_clone (clone_flags, NULL);
if (pid == -1)
{
if (opt_unshare_user)
{
if (errno == EINVAL)
die ("Creating new namespace failed, likely because the kernel does not support user namespaces. bwrap must be installed setuid on such systems.");
else if (errno == EPERM && !is_privileged)
die ("No permissions to creating new namespace, likely because the kernel does not allow non-privileged user namespaces. On e.g. debian this can be enabled with 'sysctl kernel.unprivileged_userns_clone=1'.");
}
die_with_error ("Creating new namespace failed");
}
ns_uid = opt_sandbox_uid;
ns_gid = opt_sandbox_gid;
if (pid != 0)
{
/* Parent, outside sandbox, privileged (initially) */
if (intermediate_pids_sockets[0] != -1)
{
close (intermediate_pids_sockets[1]);
pid = read_pid_from_socket (intermediate_pids_sockets[0]);
close (intermediate_pids_sockets[0]);
}
/* Discover namespace ids before we drop privileges */
namespace_ids_read (pid);
if (is_privileged && opt_unshare_user && opt_userns_block_fd == -1)
{
/* We're running as euid 0, but the uid we want to map is
* not 0. This means we're not allowed to write this from
* the child user namespace, so we do it from the parent.
*
* Also, we map uid/gid 0 in the namespace (to overflowuid)
* if opt_needs_devpts is true, because otherwise the mount
* of devpts fails due to root not being mapped.
*/
write_uid_gid_map (ns_uid, real_uid,
ns_gid, real_gid,
pid, TRUE, opt_needs_devpts);
}
/* Initial launched process, wait for pid 1 or exec:ed command to exit */
if (opt_userns2_fd > 0 && setns (opt_userns2_fd, CLONE_NEWUSER) != 0)
die_with_error ("Setting userns2 failed");
/* We don't need any privileges in the launcher, drop them immediately. */
drop_privs (FALSE);
/* Optionally bind our lifecycle to that of the parent */
handle_die_with_parent ();
if (opt_info_fd != -1)
{
cleanup_free char *output = xasprintf ("{\n \"child-pid\": %i", pid);
dump_info (opt_info_fd, output, TRUE);
namespace_ids_write (opt_info_fd, FALSE);
dump_info (opt_info_fd, "\n}\n", TRUE);
close (opt_info_fd);
}
if (opt_json_status_fd != -1)
{
cleanup_free char *output = xasprintf ("{ \"child-pid\": %i", pid);
dump_info (opt_json_status_fd, output, TRUE);
namespace_ids_write (opt_json_status_fd, TRUE);
dump_info (opt_json_status_fd, " }\n", TRUE);
}
if (opt_userns_block_fd != -1)
{
char b[1];
(void) TEMP_FAILURE_RETRY (read (opt_userns_block_fd, b, 1));
close (opt_userns_block_fd);
}
/* Let child run now that the uid maps are set up */
val = 1;
res = write (child_wait_fd, &val, 8);
/* Ignore res, if e.g. the child died and closed child_wait_fd we don't want to error out here */
close (child_wait_fd);
return monitor_child (event_fd, pid, setup_finished_pipe[0]);
}
if (opt_pidns_fd > 0)
{
if (setns (opt_pidns_fd, CLONE_NEWPID) != 0)
die_with_error ("Setting pidns failed");
/* fork to get the passed in pid ns */
fork_intermediate_child ();
/* We might both have specified an --pidns *and* --unshare-pid, so set up a new child pid namespace under the specified one */
if (opt_unshare_pid)
{
if (unshare (CLONE_NEWPID))
die_with_error ("unshare pid ns");
/* fork to get the new pid ns */
fork_intermediate_child ();
}
/* We're back, either in a child or grandchild, so message the actual pid to the monitor */
close (intermediate_pids_sockets[0]);
send_pid_on_socket (intermediate_pids_sockets[1]);
close (intermediate_pids_sockets[1]);
}
/* Child, in sandbox, privileged in the parent or in the user namespace (if --unshare-user).
*
* Note that for user namespaces we run as euid 0 during clone(), so
* the child user namespace is owned by euid 0., This means that the
* regular user namespace parent (with uid != 0) doesn't have any
* capabilities in it, which is nice as we can't exploit those. In
* particular the parent user namespace doesn't have CAP_PTRACE
* which would otherwise allow the parent to hijack of the child
* after this point.
*
* Unfortunately this also means you can't ptrace the final
* sandboxed process from outside the sandbox either.
*/
if (opt_info_fd != -1)
close (opt_info_fd);
if (opt_json_status_fd != -1)
close (opt_json_status_fd);
/* Wait for the parent to init uid/gid maps and drop caps */
res = read (child_wait_fd, &val, 8);
close (child_wait_fd);
/* At this point we can completely drop root uid, but retain the
* required permitted caps. This allow us to do full setup as
* the user uid, which makes e.g. fuse access work.
*/
switch_to_user_with_privs ();
if (opt_unshare_net)
loopback_setup (); /* Will exit if unsuccessful */
ns_uid = opt_sandbox_uid;
ns_gid = opt_sandbox_gid;
if (!is_privileged && opt_unshare_user && opt_userns_block_fd == -1)
{
/* In the unprivileged case we have to write the uid/gid maps in
* the child, because we have no caps in the parent */
if (opt_needs_devpts)
{
/* This is a bit hacky, but we need to first map the real uid/gid to
0, otherwise we can't mount the devpts filesystem because root is
not mapped. Later we will create another child user namespace and
map back to the real uid */
ns_uid = 0;
ns_gid = 0;
}
write_uid_gid_map (ns_uid, real_uid,
ns_gid, real_gid,
-1, TRUE, FALSE);
}
old_umask = umask (0);
/* Need to do this before the chroot, but after we're the real uid */
resolve_symlinks_in_ops ();
/* Mark everything as slave, so that we still
* receive mounts from the real root, but don't
* propagate mounts to the real root. */
if (mount (NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0)
die_with_error ("Failed to make / slave");
/* Create a tmpfs which we will use as / in the namespace */
if (mount ("tmpfs", base_path, "tmpfs", MS_NODEV | MS_NOSUID, NULL) != 0)
die_with_error ("Failed to mount tmpfs");
old_cwd = get_current_dir_name ();
/* Chdir to the new root tmpfs mount. This will be the CWD during
the entire setup. Access old or new root via "oldroot" and "newroot". */
if (chdir (base_path) != 0)
die_with_error ("chdir base_path");
/* We create a subdir "$base_path/newroot" for the new root, that
* way we can pivot_root to base_path, and put the old root at
* "$base_path/oldroot". This avoids problems accessing the oldroot
* dir if the user requested to bind mount something over / (or
* over /tmp, now that we use that for base_path). */
if (mkdir ("newroot", 0755))
die_with_error ("Creating newroot failed");
if (mount ("newroot", "newroot", NULL, MS_MGC_VAL | MS_BIND | MS_REC, NULL) < 0)
die_with_error ("setting up newroot bind");
if (mkdir ("oldroot", 0755))
die_with_error ("Creating oldroot failed");
if (pivot_root (base_path, "oldroot"))
die_with_error ("pivot_root");
if (chdir ("/") != 0)
die_with_error ("chdir / (base path)");
if (is_privileged)
{
pid_t child;
int privsep_sockets[2];
if (socketpair (AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, privsep_sockets) != 0)
die_with_error ("Can't create privsep socket");
child = fork ();
if (child == -1)
die_with_error ("Can't fork unprivileged helper");
if (child == 0)
{
/* Unprivileged setup process */
drop_privs (FALSE);
close (privsep_sockets[0]);
setup_newroot (opt_unshare_pid, privsep_sockets[1]);
exit (0);
}
else
{
int status;
uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */
uint32_t op, flags;
const char *arg1, *arg2;
cleanup_fd int unpriv_socket = -1;
unpriv_socket = privsep_sockets[0];
close (privsep_sockets[1]);
do
{
op = read_priv_sec_op (unpriv_socket, buffer, sizeof (buffer),
&flags, &arg1, &arg2);
privileged_op (-1, op, flags, arg1, arg2);
if (write (unpriv_socket, buffer, 1) != 1)
die ("Can't write to op_socket");
}
while (op != PRIV_SEP_OP_DONE);
waitpid (child, &status, 0);
/* Continue post setup */
}
}
else
{
setup_newroot (opt_unshare_pid, -1);
}
close_ops_fd ();
/* The old root better be rprivate or we will send unmount events to the parent namespace */
if (mount ("oldroot", "oldroot", NULL, MS_REC | MS_PRIVATE, NULL) != 0)
die_with_error ("Failed to make old root rprivate");
if (umount2 ("oldroot", MNT_DETACH))
die_with_error ("unmount old root");
/* This is our second pivot. It's like we're a Silicon Valley startup flush
* with cash but short on ideas!
*
* We're aiming to make /newroot the real root, and get rid of /oldroot. To do
* that we need a temporary place to store it before we can unmount it.
*/
{ cleanup_fd int oldrootfd = open ("/", O_DIRECTORY | O_RDONLY);
if (oldrootfd < 0)
die_with_error ("can't open /");
if (chdir ("/newroot") != 0)
die_with_error ("chdir /newroot");
/* While the documentation claims that put_old must be underneath
* new_root, it is perfectly fine to use the same directory as the
* kernel checks only if old_root is accessible from new_root.
*
* Both runc and LXC are using this "alternative" method for
* setting up the root of the container:
*
* https://github.com/opencontainers/runc/blob/master/libcontainer/rootfs_linux.go#L671
* https://github.com/lxc/lxc/blob/master/src/lxc/conf.c#L1121
*/
if (pivot_root (".", ".") != 0)
die_with_error ("pivot_root(/newroot)");
if (fchdir (oldrootfd) < 0)
die_with_error ("fchdir to oldroot");
if (umount2 (".", MNT_DETACH) < 0)
die_with_error ("umount old root");
if (chdir ("/") != 0)
die_with_error ("chdir /");
}
if (opt_userns2_fd > 0 && setns (opt_userns2_fd, CLONE_NEWUSER) != 0)
die_with_error ("Setting userns2 failed");
if (opt_unshare_user &&
(ns_uid != opt_sandbox_uid || ns_gid != opt_sandbox_gid) &&
opt_userns_block_fd == -1)
{
/* Now that devpts is mounted and we've no need for mount
permissions we can create a new userspace and map our uid
1:1 */
if (unshare (CLONE_NEWUSER))
die_with_error ("unshare user ns");
/* We're in a new user namespace, we got back the bounding set, clear it again */
drop_cap_bounding_set (FALSE);
write_uid_gid_map (opt_sandbox_uid, ns_uid,
opt_sandbox_gid, ns_gid,
-1, FALSE, FALSE);
}
/* All privileged ops are done now, so drop caps we don't need */
drop_privs (!is_privileged);
if (opt_block_fd != -1)
{
char b[1];
(void) TEMP_FAILURE_RETRY (read (opt_block_fd, b, 1));
close (opt_block_fd);
}
if (opt_seccomp_fd != -1)
{
seccomp_data = load_file_data (opt_seccomp_fd, &seccomp_len);
if (seccomp_data == NULL)
die_with_error ("Can't read seccomp data");
if (seccomp_len % 8 != 0)
die ("Invalid seccomp data, must be multiple of 8");
seccomp_prog.len = seccomp_len / 8;
seccomp_prog.filter = (struct sock_filter *) seccomp_data;
close (opt_seccomp_fd);
}
umask (old_umask);
new_cwd = "/";
if (opt_chdir_path)
{
if (chdir (opt_chdir_path))
die_with_error ("Can't chdir to %s", opt_chdir_path);
new_cwd = opt_chdir_path;
}
else if (chdir (old_cwd) == 0)
{
/* If the old cwd is mapped in the sandbox, go there */
new_cwd = old_cwd;
}
else
{
/* If the old cwd is not mapped, go to home */
const char *home = getenv ("HOME");
if (home != NULL &&
chdir (home) == 0)
new_cwd = home;
}
xsetenv ("PWD", new_cwd, 1);
free (old_cwd);
if (opt_new_session &&
setsid () == (pid_t) -1)
die_with_error ("setsid");
if (label_exec (opt_exec_label) == -1)
die_with_error ("label_exec %s", argv[0]);
__debug__ (("forking for child\n"));
if (!opt_as_pid_1 && (opt_unshare_pid || lock_files != NULL || opt_sync_fd != -1))
{
/* We have to have a pid 1 in the pid namespace, because
* otherwise we'll get a bunch of zombies as nothing reaps
* them. Alternatively if we're using sync_fd or lock_files we
* need some process to own these.
*/
pid = fork ();
if (pid == -1)
die_with_error ("Can't fork for pid 1");
if (pid != 0)
{
drop_all_caps (FALSE);
/* Close fds in pid 1, except stdio and optionally event_fd
(for syncing pid 2 lifetime with monitor_child) and
opt_sync_fd (for syncing sandbox lifetime with outside
process).
Any other fds will been passed on to the child though. */
{
int dont_close[3];
int j = 0;
if (event_fd != -1)
dont_close[j++] = event_fd;
if (opt_sync_fd != -1)
dont_close[j++] = opt_sync_fd;
dont_close[j++] = -1;
fdwalk (proc_fd, close_extra_fds, dont_close);
}
return do_init (event_fd, pid, seccomp_data != NULL ? &seccomp_prog : NULL);
}
}
__debug__ (("launch executable %s\n", argv[0]));
if (proc_fd != -1)
close (proc_fd);
/* If we are using --as-pid-1 leak the sync fd into the sandbox.
--sync-fd will still work unless the container process doesn't close this file. */
if (!opt_as_pid_1)
{
if (opt_sync_fd != -1)
close (opt_sync_fd);
}
/* We want sigchild in the child */
unblock_sigchild ();
/* Optionally bind our lifecycle */
handle_die_with_parent ();
if (!is_privileged)
set_ambient_capabilities ();
/* Should be the last thing before execve() so that filters don't
* need to handle anything above */
if (seccomp_data != NULL &&
prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &seccomp_prog) != 0)
die_with_error ("prctl(PR_SET_SECCOMP)");
if (setup_finished_pipe[1] != -1)
{
char data = 0;
res = write_to_fd (setup_finished_pipe[1], &data, 1);
/* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0]
we don't want to error out here */
}
if (execvp (argv[0], argv) == -1)
{
if (setup_finished_pipe[1] != -1)
{
int saved_errno = errno;
char data = 0;
res = write_to_fd (setup_finished_pipe[1], &data, 1);
errno = saved_errno;
/* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0]
we don't want to error out here */
}
die_with_error ("execvp %s", argv[0]);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_2473_0 |
crossvul-cpp_data_bad_3228_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3228_0 |
crossvul-cpp_data_good_3233_0 | /*
===========================================================================
Return to Castle Wolfenstein multiplayer GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (RTCW MP Source Code).
RTCW MP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW MP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW MP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
// cl_main.c -- client main loop
#include "client.h"
#include <limits.h>
#ifdef __linux__
#include <sys/stat.h>
#endif
#include "../sys/sys_local.h"
#include "../sys/sys_loadlib.h"
#ifdef USE_MUMBLE
#include "libmumblelink.h"
#endif
#ifdef USE_MUMBLE
cvar_t *cl_useMumble;
cvar_t *cl_mumbleScale;
#endif
#ifdef USE_VOIP
cvar_t *cl_voipUseVAD;
cvar_t *cl_voipVADThreshold;
cvar_t *cl_voipSend;
cvar_t *cl_voipSendTarget;
cvar_t *cl_voipGainDuringCapture;
cvar_t *cl_voipCaptureMult;
cvar_t *cl_voipShowMeter;
cvar_t *cl_voipProtocol;
cvar_t *cl_voip;
#endif
#ifdef USE_RENDERER_DLOPEN
cvar_t *cl_renderer;
#endif
cvar_t *cl_wavefilerecord;
cvar_t *cl_nodelta;
cvar_t *cl_debugMove;
cvar_t *cl_noprint;
#ifdef UPDATE_SERVER_NAME
cvar_t *cl_motd;
#endif
cvar_t *cl_autoupdate; // DHM - Nerve
cvar_t *rcon_client_password;
cvar_t *rconAddress;
cvar_t *cl_timeout;
cvar_t *cl_maxpackets;
cvar_t *cl_packetdup;
cvar_t *cl_timeNudge;
cvar_t *cl_showTimeDelta;
cvar_t *cl_freezeDemo;
cvar_t *cl_showPing;
cvar_t *cl_shownet = NULL; // NERVE - SMF - This is referenced in msg.c and we need to make sure it is NULL
cvar_t *cl_shownuments; // DHM - Nerve
cvar_t *cl_visibleClients; // DHM - Nerve
cvar_t *cl_showSend;
cvar_t *cl_showServerCommands; // NERVE - SMF
cvar_t *cl_timedemo;
cvar_t *cl_timedemoLog;
cvar_t *cl_autoRecordDemo;
cvar_t *cl_aviFrameRate;
cvar_t *cl_aviMotionJpeg;
cvar_t *cl_avidemo;
cvar_t *cl_forceavidemo;
cvar_t *cl_freelook;
cvar_t *cl_sensitivity;
cvar_t *cl_mouseAccel;
cvar_t *cl_mouseAccelOffset;
cvar_t *cl_mouseAccelStyle;
cvar_t *cl_showMouseRate;
cvar_t *m_pitch;
cvar_t *m_yaw;
cvar_t *m_forward;
cvar_t *m_side;
cvar_t *m_filter;
cvar_t *j_pitch;
cvar_t *j_yaw;
cvar_t *j_forward;
cvar_t *j_side;
cvar_t *j_up;
cvar_t *j_pitch_axis;
cvar_t *j_yaw_axis;
cvar_t *j_forward_axis;
cvar_t *j_side_axis;
cvar_t *j_up_axis;
cvar_t *cl_activeAction;
cvar_t *cl_motdString;
cvar_t *cl_allowDownload;
cvar_t *cl_conXOffset;
cvar_t *cl_inGameVideo;
cvar_t *cl_serverStatusResendTime;
cvar_t *cl_missionStats;
cvar_t *cl_waitForFire;
// NERVE - SMF - localization
cvar_t *cl_language;
cvar_t *cl_debugTranslation;
// -NERVE - SMF
// DHM - Nerve :: Auto-Update
cvar_t *cl_updateavailable;
cvar_t *cl_updatefiles;
// DHM - Nerve
cvar_t *cl_lanForcePackets;
cvar_t *cl_guid;
cvar_t *cl_guidServerUniq;
cvar_t *cl_consoleKeys;
cvar_t *cl_rate;
clientActive_t cl;
clientConnection_t clc;
clientStatic_t cls;
vm_t *cgvm;
char cl_reconnectArgs[MAX_OSPATH];
char cl_oldGame[MAX_QPATH];
qboolean cl_oldGameSet;
// Structure containing functions exported from refresh DLL
refexport_t re;
#ifdef USE_RENDERER_DLOPEN
static void *rendererLib = NULL;
#endif
ping_t cl_pinglist[MAX_PINGREQUESTS];
typedef struct serverStatus_s
{
char string[BIG_INFO_STRING];
netadr_t address;
int time, startTime;
qboolean pending;
qboolean print;
qboolean retrieved;
} serverStatus_t;
serverStatus_t cl_serverStatusList[MAX_SERVERSTATUSREQUESTS];
// DHM - Nerve :: Have we heard from the auto-update server this session?
qboolean autoupdateChecked;
qboolean autoupdateStarted;
// TTimo : moved from char* to array (was getting the char* from va(), broke on big downloads)
char autoupdateFilename[MAX_QPATH];
// "updates" shifted from -7
#define AUTOUPDATE_DIR "ni]Zm^l"
#define AUTOUPDATE_DIR_SHIFT 7
static int noGameRestart = qfalse;
extern void SV_BotFrame( int time );
void CL_CheckForResend( void );
void CL_ShowIP_f( void );
void CL_ServerStatus_f( void );
void CL_ServerStatusResponse( netadr_t from, msg_t *msg );
void CL_SaveTranslations_f( void );
void CL_LoadTranslations_f( void );
/*
===============
CL_CDDialog
Called by Com_Error when a cd is needed
===============
*/
void CL_CDDialog( void ) {
cls.cddialog = qtrue; // start it next frame
}
#ifdef USE_MUMBLE
static
void CL_UpdateMumble(void)
{
vec3_t pos, forward, up;
float scale = cl_mumbleScale->value;
float tmp;
if(!cl_useMumble->integer)
return;
// !!! FIXME: not sure if this is even close to correct.
AngleVectors( cl.snap.ps.viewangles, forward, NULL, up);
pos[0] = cl.snap.ps.origin[0] * scale;
pos[1] = cl.snap.ps.origin[2] * scale;
pos[2] = cl.snap.ps.origin[1] * scale;
tmp = forward[1];
forward[1] = forward[2];
forward[2] = tmp;
tmp = up[1];
up[1] = up[2];
up[2] = tmp;
if(cl_useMumble->integer > 1) {
fprintf(stderr, "%f %f %f, %f %f %f, %f %f %f\n",
pos[0], pos[1], pos[2],
forward[0], forward[1], forward[2],
up[0], up[1], up[2]);
}
mumble_update_coordinates(pos, forward, up);
}
#endif
#ifdef USE_VOIP
static
void CL_UpdateVoipIgnore(const char *idstr, qboolean ignore)
{
if ((*idstr >= '0') && (*idstr <= '9')) {
const int id = atoi(idstr);
if ((id >= 0) && (id < MAX_CLIENTS)) {
clc.voipIgnore[id] = ignore;
CL_AddReliableCommand(va("voip %s %d",
ignore ? "ignore" : "unignore", id), qfalse);
Com_Printf("VoIP: %s ignoring player #%d\n",
ignore ? "Now" : "No longer", id);
return;
}
}
Com_Printf("VoIP: invalid player ID#\n");
}
static
void CL_UpdateVoipGain(const char *idstr, float gain)
{
if ((*idstr >= '0') && (*idstr <= '9')) {
const int id = atoi(idstr);
if (gain < 0.0f)
gain = 0.0f;
if ((id >= 0) && (id < MAX_CLIENTS)) {
clc.voipGain[id] = gain;
Com_Printf("VoIP: player #%d gain now set to %f\n", id, gain);
}
}
}
void CL_Voip_f( void )
{
const char *cmd = Cmd_Argv(1);
const char *reason = NULL;
if (clc.state != CA_ACTIVE)
reason = "Not connected to a server";
else if (!clc.voipCodecInitialized)
reason = "Voip codec not initialized";
else if (!clc.voipEnabled)
reason = "Server doesn't support VoIP";
else if (!clc.demoplaying && (Cvar_VariableValue("g_gametype") == GT_SINGLE_PLAYER || Cvar_VariableValue("ui_singlePlayerActive")))
reason = "running in single-player mode";
if (reason != NULL) {
Com_Printf("VoIP: command ignored: %s\n", reason);
return;
}
if (strcmp(cmd, "ignore") == 0) {
CL_UpdateVoipIgnore(Cmd_Argv(2), qtrue);
} else if (strcmp(cmd, "unignore") == 0) {
CL_UpdateVoipIgnore(Cmd_Argv(2), qfalse);
} else if (strcmp(cmd, "gain") == 0) {
if (Cmd_Argc() > 3) {
CL_UpdateVoipGain(Cmd_Argv(2), atof(Cmd_Argv(3)));
} else if (Q_isanumber(Cmd_Argv(2))) {
int id = atoi(Cmd_Argv(2));
if (id >= 0 && id < MAX_CLIENTS) {
Com_Printf("VoIP: current gain for player #%d "
"is %f\n", id, clc.voipGain[id]);
} else {
Com_Printf("VoIP: invalid player ID#\n");
}
} else {
Com_Printf("usage: voip gain <playerID#> [value]\n");
}
} else if (strcmp(cmd, "muteall") == 0) {
Com_Printf("VoIP: muting incoming voice\n");
CL_AddReliableCommand("voip muteall", qfalse);
clc.voipMuteAll = qtrue;
} else if (strcmp(cmd, "unmuteall") == 0) {
Com_Printf("VoIP: unmuting incoming voice\n");
CL_AddReliableCommand("voip unmuteall", qfalse);
clc.voipMuteAll = qfalse;
} else {
Com_Printf("usage: voip [un]ignore <playerID#>\n"
" voip [un]muteall\n"
" voip gain <playerID#> [value]\n");
}
}
static
void CL_VoipNewGeneration(void)
{
// don't have a zero generation so new clients won't match, and don't
// wrap to negative so MSG_ReadLong() doesn't "fail."
clc.voipOutgoingGeneration++;
if (clc.voipOutgoingGeneration <= 0)
clc.voipOutgoingGeneration = 1;
clc.voipPower = 0.0f;
clc.voipOutgoingSequence = 0;
opus_encoder_ctl(clc.opusEncoder, OPUS_RESET_STATE);
}
/*
===============
CL_VoipParseTargets
sets clc.voipTargets according to cl_voipSendTarget
Generally we don't want who's listening to change during a transmission,
so this is only called when the key is first pressed
===============
*/
void CL_VoipParseTargets(void)
{
const char *target = cl_voipSendTarget->string;
char *end;
int val;
Com_Memset(clc.voipTargets, 0, sizeof(clc.voipTargets));
clc.voipFlags &= ~VOIP_SPATIAL;
while(target)
{
while(*target == ',' || *target == ' ')
target++;
if(!*target)
break;
if(isdigit(*target))
{
val = strtol(target, &end, 10);
target = end;
}
else
{
if(!Q_stricmpn(target, "all", 3))
{
Com_Memset(clc.voipTargets, ~0, sizeof(clc.voipTargets));
return;
}
if(!Q_stricmpn(target, "spatial", 7))
{
clc.voipFlags |= VOIP_SPATIAL;
target += 7;
continue;
}
else
{
if(!Q_stricmpn(target, "attacker", 8))
{
val = VM_Call(cgvm, CG_LAST_ATTACKER);
target += 8;
}
else if(!Q_stricmpn(target, "crosshair", 9))
{
val = VM_Call(cgvm, CG_CROSSHAIR_PLAYER);
target += 9;
}
else
{
while(*target && *target != ',' && *target != ' ')
target++;
continue;
}
if(val < 0)
continue;
}
}
if(val < 0 || val >= MAX_CLIENTS)
{
Com_Printf(S_COLOR_YELLOW "WARNING: VoIP "
"target %d is not a valid client "
"number\n", val);
continue;
}
clc.voipTargets[val / 8] |= 1 << (val % 8);
}
}
/*
===============
CL_CaptureVoip
Record more audio from the hardware if required and encode it into Opus
data for later transmission.
===============
*/
static
void CL_CaptureVoip(void)
{
const float audioMult = cl_voipCaptureMult->value;
const qboolean useVad = (cl_voipUseVAD->integer != 0);
qboolean initialFrame = qfalse;
qboolean finalFrame = qfalse;
#if USE_MUMBLE
// if we're using Mumble, don't try to handle VoIP transmission ourselves.
if (cl_useMumble->integer)
return;
#endif
// If your data rate is too low, you'll get Connection Interrupted warnings
// when VoIP packets arrive, even if you have a broadband connection.
// This might work on rates lower than 25000, but for safety's sake, we'll
// just demand it. Who doesn't have at least a DSL line now, anyhow? If
// you don't, you don't need VoIP. :)
if (cl_voip->modified || cl_rate->modified) {
if ((cl_voip->integer) && (cl_rate->integer < 25000)) {
Com_Printf(S_COLOR_YELLOW "Your network rate is too slow for VoIP.\n");
Com_Printf("Set 'Data Rate' to 'LAN/Cable/xDSL' in 'Setup/System/Network'.\n");
Com_Printf("Until then, VoIP is disabled.\n");
Cvar_Set("cl_voip", "0");
}
Cvar_Set("cl_voipProtocol", cl_voip->integer ? "opus" : "");
cl_voip->modified = qfalse;
cl_rate->modified = qfalse;
}
if (!clc.voipCodecInitialized)
return; // just in case this gets called at a bad time.
if (clc.voipOutgoingDataSize > 0)
return; // packet is pending transmission, don't record more yet.
if (cl_voipUseVAD->modified) {
Cvar_Set("cl_voipSend", (useVad) ? "1" : "0");
cl_voipUseVAD->modified = qfalse;
}
if ((useVad) && (!cl_voipSend->integer))
Cvar_Set("cl_voipSend", "1"); // lots of things reset this.
if (cl_voipSend->modified) {
qboolean dontCapture = qfalse;
if (clc.state != CA_ACTIVE)
dontCapture = qtrue; // not connected to a server.
else if (!clc.voipEnabled)
dontCapture = qtrue; // server doesn't support VoIP.
else if (clc.demoplaying)
dontCapture = qtrue; // playing back a demo.
else if ( cl_voip->integer == 0 )
dontCapture = qtrue; // client has VoIP support disabled.
else if ( audioMult == 0.0f )
dontCapture = qtrue; // basically silenced incoming audio.
cl_voipSend->modified = qfalse;
if(dontCapture)
{
Cvar_Set("cl_voipSend", "0");
return;
}
if (cl_voipSend->integer) {
initialFrame = qtrue;
} else {
finalFrame = qtrue;
}
}
// try to get more audio data from the sound card...
if (initialFrame) {
S_MasterGain(Com_Clamp(0.0f, 1.0f, cl_voipGainDuringCapture->value));
S_StartCapture();
CL_VoipNewGeneration();
CL_VoipParseTargets();
}
if ((cl_voipSend->integer) || (finalFrame)) { // user wants to capture audio?
int samples = S_AvailableCaptureSamples();
const int packetSamples = (finalFrame) ? VOIP_MAX_FRAME_SAMPLES : VOIP_MAX_PACKET_SAMPLES;
// enough data buffered in audio hardware to process yet?
if (samples >= packetSamples) {
// audio capture is always MONO16.
static int16_t sampbuffer[VOIP_MAX_PACKET_SAMPLES];
float voipPower = 0.0f;
int voipFrames;
int i, bytes;
if (samples > VOIP_MAX_PACKET_SAMPLES)
samples = VOIP_MAX_PACKET_SAMPLES;
// !!! FIXME: maybe separate recording from encoding, so voipPower
// !!! FIXME: updates faster than 4Hz?
samples -= samples % VOIP_MAX_FRAME_SAMPLES;
if (samples != 120 && samples != 240 && samples != 480 && samples != 960 && samples != 1920 && samples != 2880 ) {
Com_Printf("Voip: bad number of samples %d\n", samples);
return;
}
voipFrames = samples / VOIP_MAX_FRAME_SAMPLES;
S_Capture(samples, (byte *) sampbuffer); // grab from audio card.
// check the "power" of this packet...
for (i = 0; i < samples; i++) {
const float flsamp = (float) sampbuffer[i];
const float s = fabs(flsamp);
voipPower += s * s;
sampbuffer[i] = (int16_t) ((flsamp) * audioMult);
}
// encode raw audio samples into Opus data...
bytes = opus_encode(clc.opusEncoder, sampbuffer, samples,
(unsigned char *) clc.voipOutgoingData,
sizeof (clc.voipOutgoingData));
if ( bytes <= 0 ) {
Com_DPrintf("VoIP: Error encoding %d samples\n", samples);
bytes = 0;
}
clc.voipPower = (voipPower / (32768.0f * 32768.0f *
((float) samples))) * 100.0f;
if ((useVad) && (clc.voipPower < cl_voipVADThreshold->value)) {
CL_VoipNewGeneration(); // no "talk" for at least 1/4 second.
} else {
clc.voipOutgoingDataSize = bytes;
clc.voipOutgoingDataFrames = voipFrames;
Com_DPrintf("VoIP: Send %d frames, %d bytes, %f power\n",
voipFrames, bytes, clc.voipPower);
#if 0
static FILE *encio = NULL;
if (encio == NULL) encio = fopen("voip-outgoing-encoded.bin", "wb");
if (encio != NULL) { fwrite(clc.voipOutgoingData, bytes, 1, encio); fflush(encio); }
static FILE *decio = NULL;
if (decio == NULL) decio = fopen("voip-outgoing-decoded.bin", "wb");
if (decio != NULL) { fwrite(sampbuffer, voipFrames * VOIP_MAX_FRAME_SAMPLES * 2, 1, decio); fflush(decio); }
#endif
}
}
}
// User requested we stop recording, and we've now processed the last of
// any previously-buffered data. Pause the capture device, etc.
if (finalFrame) {
S_StopCapture();
S_MasterGain(1.0f);
clc.voipPower = 0.0f; // force this value so it doesn't linger.
}
}
#endif
/*
=======================================================================
CLIENT RELIABLE COMMAND COMMUNICATION
=======================================================================
*/
/*
======================
CL_AddReliableCommand
The given command will be transmitted to the server, and is gauranteed to
not have future usercmd_t executed before it is executed
======================
*/
void CL_AddReliableCommand(const char *cmd, qboolean isDisconnectCmd)
{
int unacknowledged = clc.reliableSequence - clc.reliableAcknowledge;
// if we would be losing an old command that hasn't been acknowledged,
// we must drop the connection
// also leave one slot open for the disconnect command in this case.
if ((isDisconnectCmd && unacknowledged > MAX_RELIABLE_COMMANDS) ||
(!isDisconnectCmd && unacknowledged >= MAX_RELIABLE_COMMANDS))
{
if(com_errorEntered)
return;
else
Com_Error(ERR_DROP, "Client command overflow");
}
Q_strncpyz(clc.reliableCommands[++clc.reliableSequence & (MAX_RELIABLE_COMMANDS - 1)],
cmd, sizeof(*clc.reliableCommands));
}
/*
=======================================================================
CLIENT SIDE DEMO RECORDING
=======================================================================
*/
/*
====================
CL_WriteDemoMessage
Dumps the current net message, prefixed by the length
====================
*/
void CL_WriteDemoMessage( msg_t *msg, int headerBytes ) {
int len, swlen;
// write the packet sequence
len = clc.serverMessageSequence;
swlen = LittleLong( len );
FS_Write( &swlen, 4, clc.demofile );
// skip the packet sequencing information
len = msg->cursize - headerBytes;
swlen = LittleLong( len );
FS_Write( &swlen, 4, clc.demofile );
FS_Write( msg->data + headerBytes, len, clc.demofile );
}
/*
====================
CL_StopRecording_f
stop recording a demo
====================
*/
void CL_StopRecord_f( void ) {
int len;
if ( !clc.demorecording ) {
Com_Printf( "Not recording a demo.\n" );
return;
}
// finish up
len = -1;
FS_Write( &len, 4, clc.demofile );
FS_Write( &len, 4, clc.demofile );
FS_FCloseFile( clc.demofile );
clc.demofile = 0;
clc.demorecording = qfalse;
Com_Printf( "Stopped demo.\n" );
}
/*
==================
CL_DemoFilename
==================
*/
void CL_DemoFilename( int number, char *fileName, int fileNameSize ) {
int a,b,c,d;
if(number < 0 || number > 9999)
number = 9999;
a = number / 1000;
number -= a * 1000;
b = number / 100;
number -= b * 100;
c = number / 10;
number -= c * 10;
d = number;
Com_sprintf( fileName, fileNameSize, "demo%i%i%i%i"
, a, b, c, d );
}
/*
====================
CL_Record_f
record <demoname>
Begins recording a demo from the current position
====================
*/
static char demoName[MAX_QPATH]; // compiler bug workaround
void CL_Record_f( void ) {
char name[MAX_OSPATH];
byte bufData[MAX_MSGLEN];
msg_t buf;
int i;
int len;
entityState_t *ent;
entityState_t nullstate;
char *s;
if ( Cmd_Argc() > 2 ) {
Com_Printf( "record <demoname>\n" );
return;
}
if ( clc.demorecording ) {
Com_Printf( "Already recording.\n" );
return;
}
if ( clc.state != CA_ACTIVE ) {
Com_Printf( "You must be in a level to record.\n" );
return;
}
// sync 0 doesn't prevent recording, so not forcing it off .. everyone does g_sync 1 ; record ; g_sync 0 ..
if ( NET_IsLocalAddress( clc.serverAddress ) && !Cvar_VariableValue( "g_synchronousClients" ) ) {
Com_Printf (S_COLOR_YELLOW "WARNING: You should set 'g_synchronousClients 1' for smoother demo recording\n");
}
if ( Cmd_Argc() == 2 ) {
s = Cmd_Argv( 1 );
Q_strncpyz( demoName, s, sizeof( demoName ) );
#ifdef LEGACY_PROTOCOL
if(clc.compat)
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_legacyprotocol->integer);
else
#endif
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_protocol->integer);
} else {
int number;
// scan for a free demo name
for ( number = 0 ; number <= 9999 ; number++ ) {
CL_DemoFilename( number, demoName, sizeof( demoName ) );
#ifdef LEGACY_PROTOCOL
if(clc.compat)
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_legacyprotocol->integer);
else
#endif
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_protocol->integer);
if (!FS_FileExists(name))
break; // file doesn't exist
}
}
// open the demo file
Com_Printf( "recording to %s.\n", name );
clc.demofile = FS_FOpenFileWrite( name );
if ( !clc.demofile ) {
Com_Printf( "ERROR: couldn't open.\n" );
return;
}
clc.demorecording = qtrue;
Q_strncpyz( clc.demoName, demoName, sizeof( clc.demoName ) );
// don't start saving messages until a non-delta compressed message is received
clc.demowaiting = qtrue;
// write out the gamestate message
MSG_Init( &buf, bufData, sizeof( bufData ) );
MSG_Bitstream( &buf );
// NOTE, MRE: all server->client messages now acknowledge
MSG_WriteLong( &buf, clc.reliableSequence );
MSG_WriteByte( &buf, svc_gamestate );
MSG_WriteLong( &buf, clc.serverCommandSequence );
// configstrings
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
if ( !cl.gameState.stringOffsets[i] ) {
continue;
}
s = cl.gameState.stringData + cl.gameState.stringOffsets[i];
MSG_WriteByte( &buf, svc_configstring );
MSG_WriteShort( &buf, i );
MSG_WriteBigString( &buf, s );
}
// baselines
Com_Memset( &nullstate, 0, sizeof( nullstate ) );
for ( i = 0; i < MAX_GENTITIES ; i++ ) {
ent = &cl.entityBaselines[i];
if ( !ent->number ) {
continue;
}
MSG_WriteByte( &buf, svc_baseline );
MSG_WriteDeltaEntity( &buf, &nullstate, ent, qtrue );
}
MSG_WriteByte( &buf, svc_EOF );
// finished writing the gamestate stuff
// write the client num
MSG_WriteLong( &buf, clc.clientNum );
// write the checksum feed
MSG_WriteLong( &buf, clc.checksumFeed );
// finished writing the client packet
MSG_WriteByte( &buf, svc_EOF );
// write it to the demo file
len = LittleLong( clc.serverMessageSequence - 1 );
FS_Write( &len, 4, clc.demofile );
len = LittleLong( buf.cursize );
FS_Write( &len, 4, clc.demofile );
FS_Write( buf.data, buf.cursize, clc.demofile );
// the rest of the demo file will be copied from net messages
}
/*
=======================================================================
CLIENT SIDE DEMO PLAYBACK
=======================================================================
*/
/*
=================
CL_DemoFrameDurationSDev
=================
*/
static float CL_DemoFrameDurationSDev( void )
{
int i;
int numFrames;
float mean = 0.0f;
float variance = 0.0f;
if( ( clc.timeDemoFrames - 1 ) > MAX_TIMEDEMO_DURATIONS )
numFrames = MAX_TIMEDEMO_DURATIONS;
else
numFrames = clc.timeDemoFrames - 1;
for( i = 0; i < numFrames; i++ )
mean += clc.timeDemoDurations[ i ];
mean /= numFrames;
for( i = 0; i < numFrames; i++ )
{
float x = clc.timeDemoDurations[ i ];
variance += ( ( x - mean ) * ( x - mean ) );
}
variance /= numFrames;
return sqrt( variance );
}
/*
=================
CL_DemoCompleted
=================
*/
void CL_DemoCompleted( void )
{
char buffer[ MAX_STRING_CHARS ];
if( cl_timedemo && cl_timedemo->integer )
{
int time;
time = Sys_Milliseconds() - clc.timeDemoStart;
if( time > 0 )
{
// Millisecond times are frame durations:
// minimum/average/maximum/std deviation
Com_sprintf( buffer, sizeof( buffer ),
"%i frames %3.1f seconds %3.1f fps %d.0/%.1f/%d.0/%.1f ms\n",
clc.timeDemoFrames,
time/1000.0,
clc.timeDemoFrames*1000.0 / time,
clc.timeDemoMinDuration,
time / (float)clc.timeDemoFrames,
clc.timeDemoMaxDuration,
CL_DemoFrameDurationSDev( ) );
Com_Printf( "%s", buffer );
// Write a log of all the frame durations
if( cl_timedemoLog && strlen( cl_timedemoLog->string ) > 0 )
{
int i;
int numFrames;
fileHandle_t f;
if( ( clc.timeDemoFrames - 1 ) > MAX_TIMEDEMO_DURATIONS )
numFrames = MAX_TIMEDEMO_DURATIONS;
else
numFrames = clc.timeDemoFrames - 1;
f = FS_FOpenFileWrite( cl_timedemoLog->string );
if( f )
{
FS_Printf( f, "# %s", buffer );
for( i = 0; i < numFrames; i++ )
FS_Printf( f, "%d\n", clc.timeDemoDurations[ i ] );
FS_FCloseFile( f );
Com_Printf( "%s written\n", cl_timedemoLog->string );
}
else
{
Com_Printf( "Couldn't open %s for writing\n",
cl_timedemoLog->string );
}
}
}
}
CL_Disconnect( qtrue );
CL_NextDemo();
}
/*
=================
CL_ReadDemoMessage
=================
*/
void CL_ReadDemoMessage( void ) {
int r;
msg_t buf;
byte bufData[ MAX_MSGLEN ];
int s;
if ( !clc.demofile ) {
CL_DemoCompleted();
return;
}
// get the sequence number
r = FS_Read( &s, 4, clc.demofile );
if ( r != 4 ) {
CL_DemoCompleted();
return;
}
clc.serverMessageSequence = LittleLong( s );
// init the message
MSG_Init( &buf, bufData, sizeof( bufData ) );
// get the length
r = FS_Read( &buf.cursize, 4, clc.demofile );
if ( r != 4 ) {
CL_DemoCompleted();
return;
}
buf.cursize = LittleLong( buf.cursize );
if ( buf.cursize == -1 ) {
CL_DemoCompleted();
return;
}
if ( buf.cursize > buf.maxsize ) {
Com_Error( ERR_DROP, "CL_ReadDemoMessage: demoMsglen > MAX_MSGLEN" );
}
r = FS_Read( buf.data, buf.cursize, clc.demofile );
if ( r != buf.cursize ) {
Com_Printf( "Demo file was truncated.\n" );
CL_DemoCompleted();
return;
}
clc.lastPacketTime = cls.realtime;
buf.readcount = 0;
CL_ParseServerMessage( &buf );
}
/*
====================
CL_WalkDemoExt
====================
*/
static int CL_WalkDemoExt(char *arg, char *name, int *demofile)
{
int i = 0;
*demofile = 0;
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer > 0)
{
Com_sprintf(name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, com_legacyprotocol->integer);
FS_FOpenFileRead(name, demofile, qtrue);
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return com_legacyprotocol->integer;
}
}
if(com_protocol->integer != com_legacyprotocol->integer)
#endif
{
Com_sprintf(name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, com_protocol->integer);
FS_FOpenFileRead(name, demofile, qtrue);
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return com_protocol->integer;
}
}
Com_Printf("Not found: %s\n", name);
while(demo_protocols[i])
{
#ifdef LEGACY_PROTOCOL
if(demo_protocols[i] == com_legacyprotocol->integer)
continue;
#endif
if(demo_protocols[i] == com_protocol->integer)
continue;
Com_sprintf (name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, demo_protocols[i]);
FS_FOpenFileRead( name, demofile, qtrue );
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return demo_protocols[i];
}
else
Com_Printf("Not found: %s\n", name);
i++;
}
return -1;
}
/*
====================
CL_CompleteDemoName
====================
*/
static void CL_CompleteDemoName( char *args, int argNum )
{
if( argNum == 2 )
{
char demoExt[ 16 ];
Com_sprintf(demoExt, sizeof(demoExt), ".%s%d", DEMOEXT, com_protocol->integer);
Field_CompleteFilename( "demos", demoExt, qtrue, qtrue );
}
}
/*
====================
CL_PlayDemo_f
demo <demoname>
====================
*/
void CL_PlayDemo_f( void ) {
char name[MAX_OSPATH];
char *arg, *ext_test;
int protocol, i;
char retry[MAX_OSPATH];
if (Cmd_Argc() != 2) {
Com_Printf ("demo <demoname>\n");
return;
}
// make sure a local server is killed
// 2 means don't force disconnect of local client
Cvar_Set( "sv_killserver", "2" );
// open the demo file
arg = Cmd_Argv(1);
CL_Disconnect( qtrue );
// check for an extension .DEMOEXT_?? (?? is protocol)
ext_test = strrchr(arg, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMOEXT, ARRAY_LEN(DEMOEXT) - 1))
{
protocol = atoi(ext_test + ARRAY_LEN(DEMOEXT));
for(i = 0; demo_protocols[i]; i++)
{
if(demo_protocols[i] == protocol)
break;
}
if(demo_protocols[i] || protocol == com_protocol->integer
#ifdef LEGACY_PROTOCOL
|| protocol == com_legacyprotocol->integer
#endif
)
{
Com_sprintf(name, sizeof(name), "demos/%s", arg);
FS_FOpenFileRead(name, &clc.demofile, qtrue);
}
else
{
int len;
Com_Printf("Protocol %d not supported for demos\n", protocol);
len = ext_test - arg;
if(len >= ARRAY_LEN(retry))
len = ARRAY_LEN(retry) - 1;
Q_strncpyz(retry, arg, len + 1);
retry[len] = '\0';
protocol = CL_WalkDemoExt(retry, name, &clc.demofile);
}
}
else
protocol = CL_WalkDemoExt(arg, name, &clc.demofile);
if (!clc.demofile) {
Com_Error( ERR_DROP, "couldn't open %s", name);
return;
}
Q_strncpyz( clc.demoName, arg, sizeof( clc.demoName ) );
Con_Close();
clc.state = CA_CONNECTED;
clc.demoplaying = qtrue;
Q_strncpyz( clc.servername, arg, sizeof( clc.servername ) );
#ifdef LEGACY_PROTOCOL
if(protocol <= com_legacyprotocol->integer)
clc.compat = qtrue;
else
clc.compat = qfalse;
#endif
// read demo messages until connected
while ( clc.state >= CA_CONNECTED && clc.state < CA_PRIMED ) {
CL_ReadDemoMessage();
}
// don't get the first snapshot this frame, to prevent the long
// time from the gamestate load from messing causing a time skip
clc.firstDemoFrameSkipped = qfalse;
}
/*
====================
CL_StartDemoLoop
Closing the main menu will restart the demo loop
====================
*/
void CL_StartDemoLoop( void ) {
// start the demo loop again
Cbuf_AddText( "d1\n" );
Key_SetCatcher( 0 );
}
/*
==================
CL_NextDemo
Called when a demo or cinematic finishes
If the "nextdemo" cvar is set, that command will be issued
==================
*/
void CL_NextDemo( void ) {
char v[MAX_STRING_CHARS];
Q_strncpyz( v, Cvar_VariableString( "nextdemo" ), sizeof( v ) );
v[MAX_STRING_CHARS - 1] = 0;
Com_DPrintf( "CL_NextDemo: %s\n", v );
if ( !v[0] ) {
return;
}
Cvar_Set( "nextdemo","" );
Cbuf_AddText( v );
Cbuf_AddText( "\n" );
Cbuf_Execute();
}
/*
====================
Wave file saving functions
====================
void CL_WriteWaveOpen() {
// we will just save it as a 16bit stereo 22050kz pcm file
clc.wavefile = FS_FOpenFileWrite( "demodata.pcm" );
clc.wavetime = -1;
}
void CL_WriteWaveClose() {
// and we're outta here
FS_FCloseFile( clc.wavefile );
}
extern int s_soundtime;
extern portable_samplepair_t *paintbuffer;
void CL_WriteWaveFilePacket() {
int total, i;
if ( clc.wavetime == -1 ) {
clc.wavetime = s_soundtime;
return;
}
total = s_soundtime - clc.wavetime;
clc.wavetime = s_soundtime;
for ( i = 0; i < total; i++ ) {
int parm;
short out;
parm = ( paintbuffer[i].left ) >> 8;
if ( parm > 32767 ) {
parm = 32767;
}
if ( parm < -32768 ) {
parm = -32768;
}
out = parm;
FS_Write( &out, 2, clc.wavefile );
parm = ( paintbuffer[i].right ) >> 8;
if ( parm > 32767 ) {
parm = 32767;
}
if ( parm < -32768 ) {
parm = -32768;
}
out = parm;
FS_Write( &out, 2, clc.wavefile );
}
}
*/
//======================================================================
/*
=====================
CL_ShutdownAll
=====================
*/
void CL_ShutdownAll(qboolean shutdownRef)
{
if(CL_VideoRecording())
CL_CloseAVI();
if(clc.demorecording)
CL_StopRecord_f();
#ifdef USE_CURL
CL_cURL_Shutdown();
#endif
// clear sounds
S_DisableSounds();
// shutdown CGame
CL_ShutdownCGame();
// shutdown UI
CL_ShutdownUI();
// shutdown the renderer
if(shutdownRef)
CL_ShutdownRef();
else if(re.Shutdown)
re.Shutdown(qfalse); // don't destroy window or context
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.rendererStarted = qfalse;
cls.soundRegistered = qfalse;
}
/*
=================
CL_ClearMemory
Called by Com_GameRestart
=================
*/
void CL_ClearMemory(qboolean shutdownRef)
{
// shutdown all the client stuff
CL_ShutdownAll(shutdownRef);
// if not running a server clear the whole hunk
if ( !com_sv_running->integer ) {
// clear the whole hunk
Hunk_Clear();
// clear collision map data
CM_ClearMap();
} else {
// clear all the client data on the hunk
Hunk_ClearToMark();
}
}
/*
=================
CL_FlushMemory
Called by CL_MapLoading, CL_Connect_f, CL_PlayDemo_f, and CL_ParseGamestate the only
ways a client gets into a game
Also called by Com_Error
=================
*/
void CL_FlushMemory(void)
{
CL_ClearMemory(qfalse);
CL_StartHunkUsers(qfalse);
}
/*
=====================
CL_MapLoading
A local server is starting to load a map, so update the
screen to let the user know about it, then dump all client
memory on the hunk from cgame, ui, and renderer
=====================
*/
void CL_MapLoading( void ) {
if ( com_dedicated->integer ) {
clc.state = CA_DISCONNECTED;
Key_SetCatcher( KEYCATCH_CONSOLE );
return;
}
if ( !com_cl_running->integer ) {
return;
}
Con_Close();
Key_SetCatcher( 0 );
// if we are already connected to the local host, stay connected
if ( clc.state >= CA_CONNECTED && !Q_stricmp( clc.servername, "localhost" ) ) {
clc.state = CA_CONNECTED; // so the connect screen is drawn
Com_Memset( cls.updateInfoString, 0, sizeof( cls.updateInfoString ) );
Com_Memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) );
Com_Memset( &cl.gameState, 0, sizeof( cl.gameState ) );
clc.lastPacketSentTime = -9999;
SCR_UpdateScreen();
} else {
// clear nextmap so the cinematic shutdown doesn't execute it
Cvar_Set( "nextmap", "" );
CL_Disconnect( qtrue );
Q_strncpyz( clc.servername, "localhost", sizeof(clc.servername) );
clc.state = CA_CHALLENGING; // so the connect screen is drawn
Key_SetCatcher( 0 );
SCR_UpdateScreen();
clc.connectTime = -RETRANSMIT_TIMEOUT;
NET_StringToAdr( clc.servername, &clc.serverAddress, NA_UNSPEC);
// we don't need a challenge on the localhost
CL_CheckForResend();
}
}
/*
=====================
CL_ClearState
Called before parsing a gamestate
=====================
*/
void CL_ClearState( void ) {
// S_StopAllSounds();
memset( &cl, 0, sizeof( cl ) );
}
/*
====================
CL_UpdateGUID
update cl_guid using QKEY_FILE and optional prefix
====================
*/
static void CL_UpdateGUID( const char *prefix, int prefix_len )
{
#if !defined( USE_PBMD5 )
fileHandle_t f;
int len;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
if( len != QKEY_SIZE )
Cvar_Set( "cl_guid", "" );
else
Cvar_Set( "cl_guid", Com_MD5File( QKEY_FILE, QKEY_SIZE,
prefix, prefix_len ) );
#else
if ( !Q_stricmp( cl_cdkey, " " ) )
{
Cvar_Set( "cl_guid", "NO_GUID" );
return;
}
if ( !Q_stricmp( cl_guid->string, "unknown" ) )
Cvar_Set( "cl_guid", Com_PBMD5File( cl_cdkey ) );
else
return;
#endif
}
static void CL_OldGame(void)
{
if(cl_oldGameSet)
{
// change back to previous fs_game
cl_oldGameSet = qfalse;
Cvar_Set2("fs_game", cl_oldGame, qtrue);
FS_ConditionalRestart(clc.checksumFeed, qfalse);
}
}
/*
=====================
CL_Disconnect
Called when a connection, demo, or cinematic is being terminated.
Goes from a connected state to either a menu state or a console state
Sends a disconnect message to the server
This is also called on Com_Error and Com_Quit, so it shouldn't cause any errors
=====================
*/
void CL_Disconnect( qboolean showMainMenu ) {
if ( !com_cl_running || !com_cl_running->integer ) {
return;
}
// shutting down the client so enter full screen ui mode
Cvar_Set( "r_uiFullScreen", "1" );
if ( clc.demorecording ) {
CL_StopRecord_f();
}
if ( clc.download ) {
FS_FCloseFile( clc.download );
clc.download = 0;
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
#ifdef USE_MUMBLE
if (cl_useMumble->integer && mumble_islinked()) {
Com_Printf("Mumble: Unlinking from Mumble application\n");
mumble_unlink();
}
#endif
#ifdef USE_VOIP
if (cl_voipSend->integer) {
int tmp = cl_voipUseVAD->integer;
cl_voipUseVAD->integer = 0; // disable this for a moment.
clc.voipOutgoingDataSize = 0; // dump any pending VoIP transmission.
Cvar_Set("cl_voipSend", "0");
CL_CaptureVoip(); // clean up any state...
cl_voipUseVAD->integer = tmp;
}
if (clc.voipCodecInitialized) {
int i;
opus_encoder_destroy(clc.opusEncoder);
for (i = 0; i < MAX_CLIENTS; i++) {
opus_decoder_destroy(clc.opusDecoder[i]);
}
clc.voipCodecInitialized = qfalse;
}
Cmd_RemoveCommand ("voip");
#endif
if ( clc.demofile ) {
FS_FCloseFile( clc.demofile );
clc.demofile = 0;
}
if ( uivm && showMainMenu ) {
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NONE );
}
SCR_StopCinematic();
S_ClearSoundBuffer();
// send a disconnect message to the server
// send it a few times in case one is dropped
if ( clc.state >= CA_CONNECTED ) {
CL_AddReliableCommand("disconnect", qtrue);
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
// Remove pure paks
FS_PureServerSetLoadedPaks("", "");
FS_PureServerSetReferencedPaks( "", "" );
CL_ClearState();
// wipe the client connection
Com_Memset( &clc, 0, sizeof( clc ) );
clc.state = CA_DISCONNECTED;
// allow cheats locally
Cvar_Set( "sv_cheats", "1" );
// not connected to a pure server anymore
cl_connectedToPureServer = qfalse;
#ifdef USE_VOIP
// not connected to voip server anymore.
clc.voipEnabled = qfalse;
#endif
// Stop recording any video
if( CL_VideoRecording( ) ) {
// Finish rendering current frame
SCR_UpdateScreen( );
CL_CloseAVI( );
}
CL_UpdateGUID( NULL, 0 );
if(!noGameRestart)
CL_OldGame();
else
noGameRestart = qfalse;
}
/*
===================
CL_ForwardCommandToServer
adds the current command line as a clientCommand
things like godmode, noclip, etc, are commands directed to the server,
so when they are typed in at the console, they will need to be forwarded.
===================
*/
void CL_ForwardCommandToServer( const char *string ) {
char *cmd;
cmd = Cmd_Argv( 0 );
// ignore key up commands
if ( cmd[0] == '-' ) {
return;
}
if ( clc.demoplaying || clc.state < CA_CONNECTED || cmd[0] == '+' ) {
Com_Printf ("Unknown command \"%s" S_COLOR_WHITE "\"\n", cmd);
return;
}
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand(string, qfalse);
} else {
CL_AddReliableCommand(cmd, qfalse);
}
}
/*
===================
CL_RequestMotd
===================
*/
void CL_RequestMotd( void ) {
#ifdef UPDATE_SERVER_NAME
char info[MAX_INFO_STRING];
if ( !cl_motd->integer ) {
return;
}
Com_Printf( "Resolving %s\n", UPDATE_SERVER_NAME );
if ( !NET_StringToAdr( UPDATE_SERVER_NAME, &cls.updateServer, NA_IP ) ) {
Com_Printf( "Couldn't resolve address\n" );
return;
}
cls.updateServer.port = BigShort( PORT_UPDATE );
Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", UPDATE_SERVER_NAME,
cls.updateServer.ip[0], cls.updateServer.ip[1],
cls.updateServer.ip[2], cls.updateServer.ip[3],
BigShort( cls.updateServer.port ) );
info[0] = 0;
Com_sprintf( cls.updateChallenge, sizeof( cls.updateChallenge ), "%i", ( (rand() << 16 ) ^ rand() ) ^ Com_Milliseconds() );
Info_SetValueForKey( info, "challenge", cls.updateChallenge );
Info_SetValueForKey( info, "renderer", cls.glconfig.renderer_string );
Info_SetValueForKey( info, "version", com_version->string );
NET_OutOfBandPrint( NS_CLIENT, cls.updateServer, "getmotd \"%s\"\n", info );
#endif
}
/*
===================
CL_RequestAuthorization
Authorization server protocol
-----------------------------
All commands are text in Q3 out of band packets (leading 0xff 0xff 0xff 0xff).
Whenever the client tries to get a challenge from the server it wants to
connect to, it also blindly fires off a packet to the authorize server:
getKeyAuthorize <challenge> <cdkey>
cdkey may be "demo"
#OLD The authorize server returns a:
#OLD
#OLD keyAthorize <challenge> <accept | deny>
#OLD
#OLD A client will be accepted if the cdkey is valid and it has not been used by any other IP
#OLD address in the last 15 minutes.
The server sends a:
getIpAuthorize <challenge> <ip>
The authorize server returns a:
ipAuthorize <challenge> <accept | deny | demo | unknown >
A client will be accepted if a valid cdkey was sent by that ip (only) in the last 15 minutes.
If no response is received from the authorize server after two tries, the client will be let
in anyway.
===================
*/
#ifndef STANDALONE
#ifdef USE_AUTHORIZE_SERVER
void CL_RequestAuthorization( void ) {
char nums[64];
int i, j, l;
cvar_t *fs;
if ( !cls.authorizeServer.port ) {
Com_Printf( "Resolving %s\n", AUTHORIZE_SERVER_NAME );
if ( !NET_StringToAdr( AUTHORIZE_SERVER_NAME, &cls.authorizeServer, NA_IP ) ) {
Com_Printf( "Couldn't resolve address\n" );
return;
}
cls.authorizeServer.port = BigShort( PORT_AUTHORIZE );
Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", AUTHORIZE_SERVER_NAME,
cls.authorizeServer.ip[0], cls.authorizeServer.ip[1],
cls.authorizeServer.ip[2], cls.authorizeServer.ip[3],
BigShort( cls.authorizeServer.port ) );
}
if ( cls.authorizeServer.type == NA_BAD ) {
return;
}
// only grab the alphanumeric values from the cdkey, to avoid any dashes or spaces
j = 0;
l = strlen( cl_cdkey );
if ( l > 32 ) {
l = 32;
}
for ( i = 0 ; i < l ; i++ ) {
if ( ( cl_cdkey[i] >= '0' && cl_cdkey[i] <= '9' )
|| ( cl_cdkey[i] >= 'a' && cl_cdkey[i] <= 'z' )
|| ( cl_cdkey[i] >= 'A' && cl_cdkey[i] <= 'Z' ) ) {
nums[j] = cl_cdkey[i];
j++;
}
}
nums[j] = 0;
fs = Cvar_Get( "cl_anonymous", "0", CVAR_INIT | CVAR_SYSTEMINFO );
NET_OutOfBandPrint(NS_CLIENT, cls.authorizeServer, "getKeyAuthorize %i %s", fs->integer, nums );
}
#endif
#endif
/*
======================================================================
CONSOLE COMMANDS
======================================================================
*/
/*
==================
CL_ForwardToServer_f
==================
*/
void CL_ForwardToServer_f( void ) {
if ( clc.state != CA_ACTIVE || clc.demoplaying ) {
Com_Printf( "Not connected to a server.\n" );
return;
}
// don't forward the first argument
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand(Cmd_Args(), qfalse);
}
}
/*
==================
CL_Disconnect_f
==================
*/
void CL_Disconnect_f( void ) {
SCR_StopCinematic();
Cvar_Set("ui_singlePlayerActive", "0");
if ( clc.state != CA_DISCONNECTED && clc.state != CA_CINEMATIC ) {
Com_Error( ERR_DISCONNECT, "Disconnected from server" );
}
}
/*
================
CL_Reconnect_f
================
*/
void CL_Reconnect_f( void ) {
if ( !strlen( cl_reconnectArgs ) )
return;
Cvar_Set("ui_singlePlayerActive", "0");
Cbuf_AddText( va("connect %s\n", cl_reconnectArgs ) );
}
/*
================
CL_Connect_f
================
*/
void CL_Connect_f( void ) {
char *server;
const char *serverString;
int argc = Cmd_Argc();
netadrtype_t family = NA_UNSPEC;
if ( argc != 2 && argc != 3 ) {
Com_Printf( "usage: connect [-4|-6] server\n");
return;
}
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
// save arguments for reconnect
Q_strncpyz( cl_reconnectArgs, Cmd_Args(), sizeof( cl_reconnectArgs ) );
Cvar_Set("ui_singlePlayerActive", "0");
S_StopAllSounds(); // NERVE - SMF
// starting to load a map so we get out of full screen ui mode
Cvar_Set( "r_uiFullScreen", "0" );
// fire a message off to the motd server
CL_RequestMotd();
// clear any previous "server full" type messages
clc.serverMessage[0] = 0;
if ( com_sv_running->integer && !strcmp( server, "localhost" ) ) {
// if running a local server, kill it
SV_Shutdown( "Server quit" );
}
// make sure a local server is killed
Cvar_Set( "sv_killserver", "1" );
SV_Frame( 0 );
noGameRestart = qtrue;
CL_Disconnect( qtrue );
Con_Close();
Q_strncpyz( clc.servername, server, sizeof(clc.servername) );
if (!NET_StringToAdr(clc.servername, &clc.serverAddress, family) ) {
Com_Printf( "Bad server address\n" );
clc.state = CA_DISCONNECTED;
return;
}
if ( clc.serverAddress.port == 0 ) {
clc.serverAddress.port = BigShort( PORT_SERVER );
}
serverString = NET_AdrToStringwPort(clc.serverAddress);
Com_Printf( "%s resolved to %s\n", clc.servername, serverString);
if( cl_guidServerUniq->integer )
CL_UpdateGUID( serverString, strlen( serverString ) );
else
CL_UpdateGUID( NULL, 0 );
// if we aren't playing on a lan, we need to authenticate
// with the cd key
if(NET_IsLocalAddress(clc.serverAddress))
clc.state = CA_CHALLENGING;
else
{
clc.state = CA_CONNECTING;
// Set a client challenge number that ideally is mirrored back by the server.
clc.challenge = ((rand() << 16) ^ rand()) ^ Com_Milliseconds();
}
// show_bug.cgi?id=507
// prepare to catch a connection process that would turn bad
Cvar_Set( "com_errorDiagnoseIP", NET_AdrToString( clc.serverAddress ) );
// ATVI Wolfenstein Misc #439
// we need to setup a correct default for this, otherwise the first val we set might reappear
Cvar_Set( "com_errorMessage", "" );
Key_SetCatcher( 0 );
clc.connectTime = -99999; // CL_CheckForResend() will fire immediately
clc.connectPacketCount = 0;
// server connection string
Cvar_Set( "cl_currentServerAddress", server );
// NERVE - SMF - reset some cvars
Cvar_Set( "mp_playerType", "0" );
Cvar_Set( "mp_currentPlayerType", "0" );
Cvar_Set( "mp_weapon", "0" );
Cvar_Set( "mp_team", "0" );
Cvar_Set( "mp_currentTeam", "0" );
Cvar_Set( "ui_limboOptions", "0" );
Cvar_Set( "ui_limboPrevOptions", "0" );
Cvar_Set( "ui_limboObjective", "0" );
// -NERVE - SMF
}
#define MAX_RCON_MESSAGE 1024
/*
==================
CL_CompleteRcon
==================
*/
static void CL_CompleteRcon( char *args, int argNum )
{
if( argNum == 2 )
{
// Skip "rcon "
char *p = Com_SkipTokens( args, 1, " " );
if( p > args )
Field_CompleteCommand( p, qtrue, qtrue );
}
}
/*
=====================
CL_Rcon_f
Send the rest of the command line over as
an unconnected command.
=====================
*/
void CL_Rcon_f( void ) {
char message[MAX_RCON_MESSAGE];
netadr_t to;
if ( !rcon_client_password->string[0] ) {
Com_Printf( "You must set 'rconpassword' before\n"
"issuing an rcon command.\n" );
return;
}
message[0] = -1;
message[1] = -1;
message[2] = -1;
message[3] = -1;
message[4] = 0;
Q_strcat (message, MAX_RCON_MESSAGE, "rcon ");
Q_strcat (message, MAX_RCON_MESSAGE, rcon_client_password->string);
Q_strcat (message, MAX_RCON_MESSAGE, " ");
Q_strcat (message, MAX_RCON_MESSAGE, Cmd_Cmd()+5);
if ( clc.state >= CA_CONNECTED ) {
to = clc.netchan.remoteAddress;
} else {
if ( !strlen( rconAddress->string ) ) {
Com_Printf( "You must either be connected,\n"
"or set the 'rconAddress' cvar\n"
"to issue rcon commands\n" );
return;
}
NET_StringToAdr (rconAddress->string, &to, NA_UNSPEC);
if ( to.port == 0 ) {
to.port = BigShort( PORT_SERVER );
}
}
NET_SendPacket( NS_CLIENT, strlen( message ) + 1, message, to );
}
/*
=================
CL_SendPureChecksums
=================
*/
void CL_SendPureChecksums( void ) {
char cMsg[MAX_INFO_VALUE];
// if we are pure we need to send back a command with our referenced pk3 checksums
Com_sprintf(cMsg, sizeof(cMsg), "cp %d %s", cl.serverId, FS_ReferencedPakPureChecksums());
CL_AddReliableCommand(cMsg, qfalse);
}
/*
=================
CL_ResetPureClientAtServer
=================
*/
void CL_ResetPureClientAtServer( void ) {
CL_AddReliableCommand("vdr", qfalse);
}
/*
=================
CL_Vid_Restart_f
Restart the video subsystem
we also have to reload the UI and CGame because the renderer
doesn't know what graphics to reload
=================
*/
void CL_Vid_Restart_f( void ) {
// RF, don't show percent bar, since the memory usage will just sit at the same level anyway
Cvar_Set( "com_expectedhunkusage", "-1" );
// Settings may have changed so stop recording now
if( CL_VideoRecording( ) ) {
CL_CloseAVI( );
}
if(clc.demorecording)
CL_StopRecord_f();
// don't let them loop during the restart
S_StopAllSounds();
if(!FS_ConditionalRestart(clc.checksumFeed, qtrue))
{
// if not running a server clear the whole hunk
if(com_sv_running->integer)
{
// clear all the client data on the hunk
Hunk_ClearToMark();
}
else
{
// clear the whole hunk
Hunk_Clear();
}
// shutdown the UI
CL_ShutdownUI();
// shutdown the CGame
CL_ShutdownCGame();
// shutdown the renderer and clear the renderer interface
CL_ShutdownRef();
// client is no longer pure untill new checksums are sent
CL_ResetPureClientAtServer();
// clear pak references
FS_ClearPakReferences( FS_UI_REF | FS_CGAME_REF );
// reinitialize the filesystem if the game directory or checksum has changed
S_BeginRegistration(); // all sound handles are now invalid
cls.rendererStarted = qfalse;
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.soundRegistered = qfalse;
autoupdateChecked = qfalse;
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
// initialize the renderer interface
CL_InitRef();
// startup all the client stuff
CL_StartHunkUsers(qfalse);
// start the cgame if connected
if(clc.state > CA_CONNECTED && clc.state != CA_CINEMATIC)
{
cls.cgameStarted = qtrue;
CL_InitCGame();
// send pure checksums
CL_SendPureChecksums();
}
}
}
/*
=================
CL_UI_Restart_f
Restart the ui subsystem
=================
*/
void CL_UI_Restart_f( void ) { // NERVE - SMF
// shutdown the UI
CL_ShutdownUI();
autoupdateChecked = qfalse;
// init the UI
CL_InitUI();
}
/*
=================
CL_Snd_Shutdown
Shut down the sound subsystem
=================
*/
void CL_Snd_Shutdown(void)
{
S_Shutdown();
cls.soundStarted = qfalse;
}
/*
=================
CL_Snd_Restart_f
Restart the sound subsystem
The cgame and game must also be forced to restart because
handles will be invalid
=================
*/
void CL_Snd_Restart_f(void)
{
CL_Snd_Shutdown();
// sound will be reinitialized by vid_restart
CL_Vid_Restart_f();
}
/*
==================
CL_PK3List_f
==================
*/
void CL_OpenedPK3List_f( void ) {
Com_Printf( "Opened PK3 Names: %s\n", FS_LoadedPakNames() );
}
/*
==================
CL_PureList_f
==================
*/
void CL_ReferencedPK3List_f( void ) {
Com_Printf( "Referenced PK3 Names: %s\n", FS_ReferencedPakNames() );
}
/*
==================
CL_Configstrings_f
==================
*/
void CL_Configstrings_f( void ) {
int i;
int ofs;
if ( clc.state != CA_ACTIVE ) {
Com_Printf( "Not connected to a server.\n" );
return;
}
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
ofs = cl.gameState.stringOffsets[ i ];
if ( !ofs ) {
continue;
}
Com_Printf( "%4i: %s\n", i, cl.gameState.stringData + ofs );
}
}
/*
==============
CL_Clientinfo_f
==============
*/
void CL_Clientinfo_f( void ) {
Com_Printf( "--------- Client Information ---------\n" );
Com_Printf( "state: %i\n", clc.state );
Com_Printf( "Server: %s\n", clc.servername );
Com_Printf( "User info settings:\n" );
Info_Print( Cvar_InfoString( CVAR_USERINFO ) );
Com_Printf( "--------------------------------------\n" );
}
//====================================================================
/*
=================
CL_DownloadsComplete
Called when all downloading has been completed
=================
*/
void CL_DownloadsComplete( void ) {
#ifndef _WIN32
char *fs_write_path;
#endif
char *fn;
// DHM - Nerve :: Auto-update (not finished yet)
if ( autoupdateStarted ) {
if ( strlen( autoupdateFilename ) > 4 ) {
#ifdef _WIN32
// win32's Sys_StartProcess prepends the current dir
fn = va( "%s/%s", FS_ShiftStr( AUTOUPDATE_DIR, AUTOUPDATE_DIR_SHIFT ), autoupdateFilename );
#else
fs_write_path = Cvar_VariableString( "fs_homepath" );
fn = FS_BuildOSPath( fs_write_path, FS_ShiftStr( AUTOUPDATE_DIR, AUTOUPDATE_DIR_SHIFT ), autoupdateFilename );
#ifdef __linux__
Sys_Chmod( fn, S_IXUSR );
#endif
#endif
Sys_StartProcess( fn, qtrue );
}
autoupdateStarted = qfalse;
CL_Disconnect( qtrue );
return;
}
#ifdef USE_CURL
// if we downloaded with cURL
if(clc.cURLUsed) {
clc.cURLUsed = qfalse;
CL_cURL_Shutdown();
if( clc.cURLDisconnected ) {
if(clc.downloadRestart) {
FS_Restart(clc.checksumFeed);
clc.downloadRestart = qfalse;
}
clc.cURLDisconnected = qfalse;
CL_Reconnect_f();
return;
}
}
#endif
// if we downloaded files we need to restart the file system
if ( clc.downloadRestart ) {
clc.downloadRestart = qfalse;
FS_Restart( clc.checksumFeed ); // We possibly downloaded a pak, restart the file system to load it
// inform the server so we get new gamestate info
CL_AddReliableCommand( "donedl", qfalse );
// by sending the donedl command we request a new gamestate
// so we don't want to load stuff yet
return;
}
// let the client game init and load data
clc.state = CA_LOADING;
Com_EventLoop();
// if the gamestate was changed by calling Com_EventLoop
// then we loaded everything already and we don't want to do it again.
if ( clc.state != CA_LOADING ) {
return;
}
// starting to load a map so we get out of full screen ui mode
Cvar_Set( "r_uiFullScreen", "0" );
// flush client memory and start loading stuff
// this will also (re)load the UI
// if this is a local client then only the client part of the hunk
// will be cleared, note that this is done after the hunk mark has been set
CL_FlushMemory();
// initialize the CGame
cls.cgameStarted = qtrue;
CL_InitCGame();
// set pure checksums
CL_SendPureChecksums();
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
/*
=================
CL_BeginDownload
Requests a file to download from the server. Stores it in the current
game directory.
=================
*/
void CL_BeginDownload( const char *localName, const char *remoteName ) {
Com_DPrintf( "***** CL_BeginDownload *****\n"
"Localname: %s\n"
"Remotename: %s\n"
"****************************\n", localName, remoteName );
Q_strncpyz( clc.downloadName, localName, sizeof( clc.downloadName ) );
Com_sprintf( clc.downloadTempName, sizeof( clc.downloadTempName ), "%s.tmp", localName );
// Set so UI gets access to it
Cvar_Set( "cl_downloadName", remoteName );
Cvar_Set( "cl_downloadSize", "0" );
Cvar_Set( "cl_downloadCount", "0" );
Cvar_SetValue( "cl_downloadTime", cls.realtime );
clc.downloadBlock = 0; // Starting new file
clc.downloadCount = 0;
CL_AddReliableCommand( va( "download %s", remoteName ), qfalse );
}
/*
=================
CL_NextDownload
A download completed or failed
=================
*/
void CL_NextDownload( void ) {
char *s;
char *remoteName, *localName;
qboolean useCURL = qfalse;
// A download has finished, check whether this matches a referenced checksum
if( *clc.downloadName && !autoupdateStarted ) {
char *zippath = FS_BuildOSPath(Cvar_VariableString("fs_homepath"), clc.downloadName, "");
zippath[strlen(zippath)-1] = '\0';
if(!FS_CompareZipChecksum(zippath))
Com_Error(ERR_DROP, "Incorrect checksum for file: %s", clc.downloadName);
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set("cl_downloadName", "");
// We are looking to start a download here
if ( *clc.downloadList ) {
s = clc.downloadList;
// format is:
// @remotename@localname@remotename@localname, etc.
if ( *s == '@' ) {
s++;
}
remoteName = s;
if ( ( s = strchr( s, '@' ) ) == NULL ) {
CL_DownloadsComplete();
return;
}
*s++ = 0;
localName = s;
if ( ( s = strchr( s, '@' ) ) != NULL ) {
*s++ = 0;
} else {
s = localName + strlen( localName ); // point at the nul byte
}
#ifdef USE_CURL
if(!(cl_allowDownload->integer & DLF_NO_REDIRECT)) {
if(clc.sv_allowDownload & DLF_NO_REDIRECT) {
Com_Printf("WARNING: server does not "
"allow download redirection "
"(sv_allowDownload is %d)\n",
clc.sv_allowDownload);
}
else if(!*clc.sv_dlURL) {
Com_Printf("WARNING: server allows "
"download redirection, but does not "
"have sv_dlURL set\n");
}
else if(!CL_cURL_Init()) {
Com_Printf("WARNING: could not load "
"cURL library\n");
}
else {
CL_cURL_BeginDownload(localName, va("%s/%s",
clc.sv_dlURL, remoteName));
useCURL = qtrue;
}
}
else if(!(clc.sv_allowDownload & DLF_NO_REDIRECT)) {
Com_Printf("WARNING: server allows download "
"redirection, but it disabled by client "
"configuration (cl_allowDownload is %d)\n",
cl_allowDownload->integer);
}
#endif /* USE_CURL */
if(!useCURL) {
if((cl_allowDownload->integer & DLF_NO_UDP)) {
Com_Error(ERR_DROP, "UDP Downloads are "
"disabled on your client. "
"(cl_allowDownload is %d)",
cl_allowDownload->integer);
return;
}
else {
CL_BeginDownload( localName, remoteName );
}
}
clc.downloadRestart = qtrue;
// move over the rest
memmove( clc.downloadList, s, strlen( s ) + 1 );
return;
}
CL_DownloadsComplete();
}
/*
=================
CL_InitDownloads
After receiving a valid game state, we valid the cgame and local zip files here
and determine if we need to download them
=================
*/
void CL_InitDownloads( void ) {
#ifndef PRE_RELEASE_DEMO
char missingfiles[1024];
char *dir = FS_ShiftStr( AUTOUPDATE_DIR, AUTOUPDATE_DIR_SHIFT );
if ( autoupdateStarted && NET_CompareAdr( cls.autoupdateServer, clc.serverAddress ) ) {
if ( strlen( cl_updatefiles->string ) > 4 ) {
Q_strncpyz( autoupdateFilename, cl_updatefiles->string, sizeof( autoupdateFilename ) );
Q_strncpyz( clc.downloadList, va( "@%s/%s@%s/%s", dir, cl_updatefiles->string, dir, cl_updatefiles->string ), MAX_INFO_STRING );
clc.state = CA_CONNECTED;
CL_NextDownload();
return;
}
} else {
if ( !(cl_allowDownload->integer & DLF_ENABLE) ) {
// autodownload is disabled on the client
// but it's possible that some referenced files on the server are missing
// whatever autodownlad configuration, store missing files in a cvar, use later in the ui maybe
if ( FS_ComparePaks( missingfiles, sizeof( missingfiles ), qfalse ) ) {
Cvar_Set( "com_missingFiles", missingfiles );
} else {
Cvar_Set( "com_missingFiles", "" );
}
Com_Printf( "\nWARNING: You are missing some files referenced by the server:\n%s"
"You might not be able to join the game\n"
"Go to the setting menu to turn on autodownload, or get the file elsewhere\n\n", missingfiles );
}
else if ( FS_ComparePaks( clc.downloadList, sizeof( clc.downloadList ), qtrue ) ) {
// this gets printed to UI, i18n
Com_Printf( CL_TranslateStringBuf( "Need paks: %s\n" ), clc.downloadList );
if ( *clc.downloadList ) {
// if autodownloading is not enabled on the server
clc.state = CA_CONNECTED;
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
CL_NextDownload();
return;
}
}
}
#endif
CL_DownloadsComplete();
}
/*
=================
CL_CheckForResend
Resend a connect message if the last one has timed out
=================
*/
void CL_CheckForResend( void ) {
int port;
char info[MAX_INFO_STRING];
char data[MAX_INFO_STRING + 10];
// don't send anything if playing back a demo
if ( clc.demoplaying ) {
return;
}
// resend if we haven't gotten a reply yet
if ( clc.state != CA_CONNECTING && clc.state != CA_CHALLENGING ) {
return;
}
if ( cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT ) {
return;
}
clc.connectTime = cls.realtime; // for retransmit requests
clc.connectPacketCount++;
switch ( clc.state ) {
case CA_CONNECTING:
// requesting a challenge .. IPv6 users always get in as authorize server supports no ipv6.
#ifndef STANDALONE
#ifdef USE_AUTHORIZE_SERVER
if (!com_standalone->integer && clc.serverAddress.type == NA_IP && !Sys_IsLANAddress( clc.serverAddress ) )
CL_RequestAuthorization();
#endif
#endif
// The challenge request shall be followed by a client challenge so no malicious server can hijack this connection.
// Add the gamename so the server knows we're running the correct game or can reject the client
// with a meaningful message
Com_sprintf(data, sizeof(data), "getchallenge %d %s", clc.challenge, com_gamename->string);
NET_OutOfBandPrint(NS_CLIENT, clc.serverAddress, "%s", data);
break;
case CA_CHALLENGING:
// sending back the challenge
port = Cvar_VariableValue( "net_qport" );
Q_strncpyz( info, Cvar_InfoString( CVAR_USERINFO ), sizeof( info ) );
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer == com_protocol->integer)
clc.compat = qtrue;
if(clc.compat)
Info_SetValueForKey(info, "protocol", va("%i", com_legacyprotocol->integer));
else
#endif
Info_SetValueForKey( info, "protocol", va("%i", com_protocol->integer ) );
Info_SetValueForKey( info, "qport", va( "%i", port ) );
Info_SetValueForKey( info, "challenge", va( "%i", clc.challenge ) );
Com_sprintf( data, sizeof(data), "connect \"%s\"", info );
NET_OutOfBandData( NS_CLIENT, clc.serverAddress, (byte *) data, strlen ( data ) );
// the most current userinfo has been sent, so watch for any
// newer changes to userinfo variables
cvar_modifiedFlags &= ~CVAR_USERINFO;
break;
default:
Com_Error( ERR_FATAL, "CL_CheckForResend: bad clc.state" );
}
}
/*
===================
CL_MotdPacket
===================
*/
void CL_MotdPacket( netadr_t from ) {
#ifdef UPDATE_SERVER_NAME
char *challenge;
char *info;
// if not from our server, ignore it
if ( !NET_CompareAdr( from, cls.updateServer ) ) {
return;
}
info = Cmd_Argv( 1 );
// check challenge
challenge = Info_ValueForKey( info, "challenge" );
if ( strcmp( challenge, cls.updateChallenge ) ) {
return;
}
challenge = Info_ValueForKey( info, "motd" );
Q_strncpyz( cls.updateInfoString, info, sizeof( cls.updateInfoString ) );
Cvar_Set( "cl_motdString", challenge );
#endif
}
/*
===================
CL_PrintPackets
an OOB message from server, with potential markups
print OOB are the only messages we handle markups in
[err_dialog]: used to indicate that the connection should be aborted
no further information, just do an error diagnostic screen afterwards
[err_prot]: HACK. This is a protocol error. The client uses a custom
protocol error message (client sided) in the diagnostic window.
The space for the error message on the connection screen is limited
to 256 chars.
===================
*/
void CL_PrintPacket( netadr_t from, msg_t *msg ) {
char *s;
s = MSG_ReadBigString( msg );
if ( !Q_stricmpn( s, "[err_dialog]", 12 ) ) {
Q_strncpyz( clc.serverMessage, s + 12, sizeof( clc.serverMessage ) );
Cvar_Set( "com_errorMessage", clc.serverMessage );
} else if ( !Q_stricmpn( s, "[err_prot]", 10 ) ) {
Q_strncpyz( clc.serverMessage, s + 10, sizeof( clc.serverMessage ) );
Cvar_Set( "com_errorMessage", CL_TranslateStringBuf( PROTOCOL_MISMATCH_ERROR_LONG ) );
} else {
Q_strncpyz( clc.serverMessage, s, sizeof( clc.serverMessage ) );
}
Com_Printf( "%s", clc.serverMessage );
}
/*
===================
CL_InitServerInfo
===================
*/
void CL_InitServerInfo( serverInfo_t *server, netadr_t *address ) {
server->adr = *address;
server->clients = 0;
server->hostName[0] = '\0';
server->mapName[0] = '\0';
server->maxClients = 0;
server->maxPing = 0;
server->minPing = 0;
server->ping = -1;
server->game[0] = '\0';
server->gameType = 0;
server->netType = 0;
server->allowAnonymous = 0;
server->friendlyFire = 0; // NERVE - SMF
server->maxlives = 0; // NERVE - SMF
server->tourney = 0; // NERVE - SMF
server->punkbuster = 0; // DHM - Nerve
server->gameName[0] = '\0'; // Arnout
server->antilag = 0;
server->g_humanplayers = 0;
server->g_needpass = 0;
}
#define MAX_SERVERSPERPACKET 256
/*
===================
CL_ServersResponsePacket
===================
*/
void CL_ServersResponsePacket( const netadr_t* from, msg_t *msg, qboolean extended ) {
int i, j, count, total;
netadr_t addresses[MAX_SERVERSPERPACKET];
int numservers;
byte* buffptr;
byte* buffend;
Com_Printf( "CL_ServersResponsePacket\n" );
if ( cls.numglobalservers == -1 ) {
// state to detect lack of servers or lack of response
cls.numglobalservers = 0;
cls.numGlobalServerAddresses = 0;
}
// parse through server response string
numservers = 0;
buffptr = msg->data;
buffend = buffptr + msg->cursize;
// advance to initial token
do
{
if(*buffptr == '\\' || (extended && *buffptr == '/'))
break;
buffptr++;
} while (buffptr < buffend);
while (buffptr + 1 < buffend)
{
// IPv4 address
if (*buffptr == '\\')
{
buffptr++;
if (buffend - buffptr < sizeof(addresses[numservers].ip) + sizeof(addresses[numservers].port) + 1)
break;
for(i = 0; i < sizeof(addresses[numservers].ip); i++)
addresses[numservers].ip[i] = *buffptr++;
addresses[numservers].type = NA_IP;
}
// IPv6 address, if it's an extended response
else if (extended && *buffptr == '/')
{
buffptr++;
if (buffend - buffptr < sizeof(addresses[numservers].ip6) + sizeof(addresses[numservers].port) + 1)
break;
for(i = 0; i < sizeof(addresses[numservers].ip6); i++)
addresses[numservers].ip6[i] = *buffptr++;
addresses[numservers].type = NA_IP6;
addresses[numservers].scope_id = from->scope_id;
}
else
// syntax error!
break;
// parse out port
addresses[numservers].port = (*buffptr++) << 8;
addresses[numservers].port += *buffptr++;
addresses[numservers].port = BigShort( addresses[numservers].port );
// syntax check
if (*buffptr != '\\' && *buffptr != '/')
break;
numservers++;
if (numservers >= MAX_SERVERSPERPACKET)
break;
}
count = cls.numglobalservers;
for (i = 0; i < numservers && count < MAX_GLOBAL_SERVERS; i++) {
// build net address
serverInfo_t *server = &cls.globalServers[count];
// Tequila: It's possible to have sent many master server requests. Then
// we may receive many times the same addresses from the master server.
// We just avoid to add a server if it is still in the global servers list.
for (j = 0; j < count; j++)
{
if (NET_CompareAdr(cls.globalServers[j].adr, addresses[i]))
break;
}
if (j < count)
continue;
CL_InitServerInfo( server, &addresses[i] );
// advance to next slot
count++;
}
// if getting the global list
if ( count >= MAX_GLOBAL_SERVERS && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS )
{
// if we couldn't store the servers in the main list anymore
for (; i < numservers && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS; i++)
{
// just store the addresses in an additional list
cls.globalServerAddresses[cls.numGlobalServerAddresses++] = addresses[i];
}
}
cls.numglobalservers = count;
total = count + cls.numGlobalServerAddresses;
Com_Printf( "%d servers parsed (total %d)\n", numservers, total );
}
/*
=================
CL_ConnectionlessPacket
Responses to broadcasts, etc
=================
*/
void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) {
char *s;
char *c;
int challenge = 0;
MSG_BeginReadingOOB( msg );
MSG_ReadLong( msg ); // skip the -1
s = MSG_ReadStringLine( msg );
Cmd_TokenizeString( s );
c = Cmd_Argv( 0 );
Com_DPrintf ("CL packet %s: %s\n", NET_AdrToStringwPort(from), c);
// challenge from the server we are connecting to
if (!Q_stricmp(c, "challengeResponse"))
{
char *strver;
int ver;
if (clc.state != CA_CONNECTING)
{
Com_DPrintf("Unwanted challenge response received. Ignored.\n");
return;
}
c = Cmd_Argv( 3 );
if(*c)
challenge = atoi(c);
strver = Cmd_Argv( 4 );
if(*strver)
{
ver = atoi(strver);
if(ver != com_protocol->integer)
{
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer > 0)
{
// Server is ioq3 but has a different protocol than we do.
// Fall back to idq3 protocol.
clc.compat = qtrue;
Com_Printf(S_COLOR_YELLOW "Warning: Server reports protocol version %d, "
"we have %d. Trying legacy protocol %d.\n",
ver, com_protocol->integer, com_legacyprotocol->integer);
}
else
#endif
{
Com_Printf(S_COLOR_YELLOW "Warning: Server reports protocol version %d, we have %d. "
"Trying anyways.\n", ver, com_protocol->integer);
}
}
}
#ifdef LEGACY_PROTOCOL
else
clc.compat = qtrue;
if(clc.compat)
{
if(!NET_CompareAdr(from, clc.serverAddress))
{
// This challenge response is not coming from the expected address.
// Check whether we have a matching client challenge to prevent
// connection hi-jacking.
if(!*c || challenge != clc.challenge)
{
Com_DPrintf("Challenge response received from unexpected source. Ignored.\n");
return;
}
}
}
else
#endif
{
if(!*c || challenge != clc.challenge)
{
Com_Printf("Bad challenge for challengeResponse. Ignored.\n");
return;
}
}
// start sending challenge response instead of challenge request packets
clc.challenge = atoi(Cmd_Argv(1));
if ( Cmd_Argc() > 2 ) {
clc.onlyVisibleClients = atoi( Cmd_Argv( 2 ) ); // DHM - Nerve
} else {
clc.onlyVisibleClients = 0;
}
clc.state = CA_CHALLENGING;
clc.connectPacketCount = 0;
clc.connectTime = -99999;
// take this address as the new server address. This allows
// a server proxy to hand off connections to multiple servers
clc.serverAddress = from;
Com_DPrintf ("challengeResponse: %d\n", clc.challenge);
return;
}
// server connection
if ( !Q_stricmp( c, "connectResponse" ) ) {
if ( clc.state >= CA_CONNECTED ) {
Com_Printf( "Dup connect received. Ignored.\n" );
return;
}
if ( clc.state != CA_CHALLENGING ) {
Com_Printf( "connectResponse packet while not connecting. Ignored.\n" );
return;
}
if ( !NET_CompareAdr( from, clc.serverAddress ) ) {
Com_Printf( "connectResponse from wrong address. Ignored.\n" );
return;
}
#ifdef LEGACY_PROTOCOL
if(!clc.compat)
#endif
{
c = Cmd_Argv(1);
if(*c)
challenge = atoi(c);
else
{
Com_Printf("Bad connectResponse received. Ignored.\n");
return;
}
if(challenge != clc.challenge)
{
Com_Printf("ConnectResponse with bad challenge received. Ignored.\n");
return;
}
}
// DHM - Nerve :: If we have completed a connection to the Auto-Update server...
if ( autoupdateChecked && NET_CompareAdr( cls.autoupdateServer, clc.serverAddress ) ) {
// Mark the client as being in the process of getting an update
if ( cl_updateavailable->integer ) {
autoupdateStarted = qtrue;
}
}
#ifdef LEGACY_PROTOCOL
Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableValue("net_qport"),
clc.challenge, clc.compat);
#else
Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableValue("net_qport"),
clc.challenge, qfalse);
#endif
clc.state = CA_CONNECTED;
clc.lastPacketSentTime = -9999; // send first packet immediately
return;
}
// server responding to an info broadcast
if ( !Q_stricmp( c, "infoResponse" ) ) {
CL_ServerInfoPacket( from, msg );
return;
}
// server responding to a get playerlist
if ( !Q_stricmp( c, "statusResponse" ) ) {
CL_ServerStatusResponse( from, msg );
return;
}
// echo request from server
if ( !Q_stricmp( c, "echo" ) ) {
NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv( 1 ) );
return;
}
// cd check
if ( !Q_stricmp( c, "keyAuthorize" ) ) {
// we don't use these now, so dump them on the floor
return;
}
// global MOTD from id
if ( !Q_stricmp( c, "motd" ) ) {
CL_MotdPacket( from );
return;
}
// echo request from server
if ( !Q_stricmp( c, "print" ) ) {
s = MSG_ReadString( msg );
Q_strncpyz( clc.serverMessage, s, sizeof( clc.serverMessage ) );
Com_Printf( "%s", s );
return;
}
// DHM - Nerve :: Auto-update server response message
if ( !Q_stricmp( c, "updateResponse" ) ) {
CL_UpdateInfoPacket( from );
return;
}
// list of servers sent back by a master server (classic)
if ( !Q_strncmp( c, "getserversResponse", 18 ) ) {
CL_ServersResponsePacket( &from, msg, qfalse );
return;
}
// list of servers sent back by a master server (extended)
if ( !Q_strncmp(c, "getserversExtResponse", 21) ) {
CL_ServersResponsePacket( &from, msg, qtrue );
return;
}
Com_DPrintf( "Unknown connectionless packet command.\n" );
}
/*
=================
CL_PacketEvent
A packet has arrived from the main event loop
=================
*/
void CL_PacketEvent( netadr_t from, msg_t *msg ) {
int headerBytes;
clc.lastPacketTime = cls.realtime;
if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) {
CL_ConnectionlessPacket( from, msg );
return;
}
if ( clc.state < CA_CONNECTED ) {
return; // can't be a valid sequenced packet
}
if ( msg->cursize < 4 ) {
Com_Printf ("%s: Runt packet\n", NET_AdrToStringwPort( from ));
return;
}
//
// packet from server
//
if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
Com_DPrintf( "%s:sequenced packet without connection\n"
, NET_AdrToStringwPort( from ) );
// FIXME: send a client disconnect?
return;
}
if ( !CL_Netchan_Process( &clc.netchan, msg ) ) {
return; // out of order, duplicated, etc
}
// the header is different lengths for reliable and unreliable messages
headerBytes = msg->readcount;
// track the last message received so it can be returned in
// client messages, allowing the server to detect a dropped
// gamestate
clc.serverMessageSequence = LittleLong( *(int *)msg->data );
clc.lastPacketTime = cls.realtime;
CL_ParseServerMessage( msg );
//
// we don't know if it is ok to save a demo message until
// after we have parsed the frame
//
if ( clc.demorecording && !clc.demowaiting ) {
CL_WriteDemoMessage( msg, headerBytes );
}
}
/*
==================
CL_CheckTimeout
==================
*/
void CL_CheckTimeout( void ) {
//
// check timeout
//
if ( ( !CL_CheckPaused() || !sv_paused->integer )
&& clc.state >= CA_CONNECTED && clc.state != CA_CINEMATIC
&& cls.realtime - clc.lastPacketTime > cl_timeout->value * 1000 ) {
if ( ++cl.timeoutcount > 5 ) { // timeoutcount saves debugger
Com_Printf( "\nServer connection timed out.\n" );
CL_Disconnect( qtrue );
return;
}
} else {
cl.timeoutcount = 0;
}
}
/*
==================
CL_CheckPaused
Check whether client has been paused.
==================
*/
qboolean CL_CheckPaused(void)
{
// if cl_paused->modified is set, the cvar has only been changed in
// this frame. Keep paused in this frame to ensure the server doesn't
// lag behind.
if(cl_paused->integer || cl_paused->modified)
return qtrue;
return qfalse;
}
//============================================================================
/*
==================
CL_CheckUserinfo
==================
*/
void CL_CheckUserinfo( void ) {
// don't add reliable commands when not yet connected
if(clc.state < CA_CONNECTED)
return;
// don't overflow the reliable command buffer when paused
if(CL_CheckPaused())
return;
// send a reliable userinfo update if needed
if ( cvar_modifiedFlags & CVAR_USERINFO ) {
cvar_modifiedFlags &= ~CVAR_USERINFO;
CL_AddReliableCommand(va("userinfo \"%s\"", Cvar_InfoString( CVAR_USERINFO ) ), qfalse);
}
}
/*
==================
CL_Frame
==================
*/
void CL_Frame( int msec ) {
if ( !com_cl_running->integer ) {
return;
}
#ifdef USE_CURL
if(clc.downloadCURLM) {
CL_cURL_PerformDownload();
// we can't process frames normally when in disconnected
// download mode since the ui vm expects clc.state to be
// CA_CONNECTED
if(clc.cURLDisconnected) {
cls.realFrametime = msec;
cls.frametime = msec;
cls.realtime += cls.frametime;
SCR_UpdateScreen();
S_Update();
Con_RunConsole();
cls.framecount++;
return;
}
}
#endif
if ( cls.cddialog ) {
// bring up the cd error dialog if needed
cls.cddialog = qfalse;
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NEED_CD );
} else if ( clc.state == CA_DISCONNECTED && !( Key_GetCatcher( ) & KEYCATCH_UI )
&& !com_sv_running->integer && uivm ) {
// if disconnected, bring up the menu
S_StopAllSounds();
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_MAIN );
}
// if recording an avi, lock to a fixed fps
if ( ( CL_VideoRecording( ) && cl_aviFrameRate->integer && msec ) || ( cl_avidemo->integer && msec ) ) {
// save the current screen
if ( clc.state == CA_ACTIVE || cl_forceavidemo->integer ) {
if ( cl_avidemo->integer ) { // Legacy (screenshot) method
Cbuf_ExecuteText( EXEC_NOW, "screenshot silent\n" );
// fixed time for next frame
msec = ( 1000 / cl_avidemo->integer ) * com_timescale->value;
if ( msec == 0 ) {
msec = 1;
}
} else { // ioquake3 method
float fps = MIN(cl_aviFrameRate->value * com_timescale->value, 1000.0f);
float frameDuration = MAX(1000.0f / fps, 1.0f) + clc.aviVideoFrameRemainder;
CL_TakeVideoFrame( );
msec = (int)frameDuration;
clc.aviVideoFrameRemainder = frameDuration - msec;
}
}
}
if( cl_autoRecordDemo->integer ) {
if( clc.state == CA_ACTIVE && !clc.demorecording && !clc.demoplaying ) {
// If not recording a demo, and we should be, start one
qtime_t now;
char *nowString;
char *p;
char mapName[ MAX_QPATH ];
char serverName[ MAX_OSPATH ];
Com_RealTime( &now );
nowString = va( "%04d%02d%02d%02d%02d%02d",
1900 + now.tm_year,
1 + now.tm_mon,
now.tm_mday,
now.tm_hour,
now.tm_min,
now.tm_sec );
Q_strncpyz( serverName, clc.servername, MAX_OSPATH );
// Replace the ":" in the address as it is not a valid
// file name character
p = strstr( serverName, ":" );
if( p ) {
*p = '.';
}
Q_strncpyz( mapName, COM_SkipPath( cl.mapname ), sizeof( cl.mapname ) );
COM_StripExtension(mapName, mapName, sizeof(mapName));
Cbuf_ExecuteText( EXEC_NOW,
va( "record %s-%s-%s", nowString, serverName, mapName ) );
}
else if( clc.state != CA_ACTIVE && clc.demorecording ) {
// Recording, but not CA_ACTIVE, so stop recording
CL_StopRecord_f( );
}
}
// save the msec before checking pause
cls.realFrametime = msec;
// decide the simulation time
cls.frametime = msec;
cls.realtime += cls.frametime;
if ( cl_timegraph->integer ) {
SCR_DebugGraph ( cls.realFrametime * 0.25 );
}
// see if we need to update any userinfo
CL_CheckUserinfo();
// if we haven't gotten a packet in a long time,
// drop the connection
CL_CheckTimeout();
// send intentions now
CL_SendCmd();
// resend a connection request if necessary
CL_CheckForResend();
// decide on the serverTime to render
CL_SetCGameTime();
// update the screen
SCR_UpdateScreen();
// update audio
S_Update();
#ifdef USE_VOIP
CL_CaptureVoip();
#endif
#ifdef USE_MUMBLE
CL_UpdateMumble();
#endif
// advance local effects for next frame
SCR_RunCinematic();
Con_RunConsole();
cls.framecount++;
}
//============================================================================
// Ridah, startup-caching system
typedef struct {
char name[MAX_QPATH];
int hits;
int lastSetIndex;
} cacheItem_t;
typedef enum {
CACHE_SOUNDS,
CACHE_MODELS,
CACHE_IMAGES,
CACHE_NUMGROUPS
} cacheGroup_t;
static cacheItem_t cacheGroups[CACHE_NUMGROUPS] = {
{{'s','o','u','n','d',0}, CACHE_SOUNDS},
{{'m','o','d','e','l',0}, CACHE_MODELS},
{{'i','m','a','g','e',0}, CACHE_IMAGES},
};
#define MAX_CACHE_ITEMS 4096
#define CACHE_HIT_RATIO 0.75 // if hit on this percentage of maps, it'll get cached
static int cacheIndex;
static cacheItem_t cacheItems[CACHE_NUMGROUPS][MAX_CACHE_ITEMS];
static void CL_Cache_StartGather_f( void ) {
cacheIndex = 0;
memset( cacheItems, 0, sizeof( cacheItems ) );
Cvar_Set( "cl_cacheGathering", "1" );
}
static void CL_Cache_UsedFile_f( void ) {
char groupStr[MAX_QPATH];
char itemStr[MAX_QPATH];
int i,group;
cacheItem_t *item;
if ( Cmd_Argc() < 2 ) {
Com_Error( ERR_DROP, "usedfile without enough parameters\n" );
return;
}
strcpy( groupStr, Cmd_Argv( 1 ) );
strcpy( itemStr, Cmd_Argv( 2 ) );
for ( i = 3; i < Cmd_Argc(); i++ ) {
strcat( itemStr, " " );
strcat( itemStr, Cmd_Argv( i ) );
}
Q_strlwr( itemStr );
// find the cache group
for ( i = 0; i < CACHE_NUMGROUPS; i++ ) {
if ( !Q_strncmp( groupStr, cacheGroups[i].name, MAX_QPATH ) ) {
break;
}
}
if ( i == CACHE_NUMGROUPS ) {
Com_Error( ERR_DROP, "usedfile without a valid cache group\n" );
return;
}
// see if it's already there
group = i;
for ( i = 0, item = cacheItems[group]; i < MAX_CACHE_ITEMS; i++, item++ ) {
if ( !item->name[0] ) {
// didn't find it, so add it here
Q_strncpyz( item->name, itemStr, MAX_QPATH );
if ( cacheIndex > 9999 ) { // hack, but yeh
item->hits = cacheIndex;
} else {
item->hits++;
}
item->lastSetIndex = cacheIndex;
break;
}
if ( item->name[0] == itemStr[0] && !Q_strncmp( item->name, itemStr, MAX_QPATH ) ) {
if ( item->lastSetIndex != cacheIndex ) {
item->hits++;
item->lastSetIndex = cacheIndex;
}
break;
}
}
}
static void CL_Cache_SetIndex_f( void ) {
if ( Cmd_Argc() < 2 ) {
Com_Error( ERR_DROP, "setindex needs an index\n" );
return;
}
cacheIndex = atoi( Cmd_Argv( 1 ) );
}
static void CL_Cache_MapChange_f( void ) {
cacheIndex++;
}
static void CL_Cache_EndGather_f( void ) {
// save the frequently used files to the cache list file
int i, j, handle, cachePass;
char filename[MAX_QPATH];
cachePass = (int)floor( (float)cacheIndex * CACHE_HIT_RATIO );
for ( i = 0; i < CACHE_NUMGROUPS; i++ ) {
Q_strncpyz( filename, cacheGroups[i].name, MAX_QPATH );
Q_strcat( filename, MAX_QPATH, ".cache" );
handle = FS_FOpenFileWrite( filename );
for ( j = 0; j < MAX_CACHE_ITEMS; j++ ) {
// if it's a valid filename, and it's been hit enough times, cache it
if ( cacheItems[i][j].hits >= cachePass && strstr( cacheItems[i][j].name, "/" ) ) {
FS_Write( cacheItems[i][j].name, strlen( cacheItems[i][j].name ), handle );
FS_Write( "\n", 1, handle );
}
}
FS_FCloseFile( handle );
}
Cvar_Set( "cl_cacheGathering", "0" );
}
// done.
//============================================================================
/*
================
CL_SetRecommended_f
================
*/
void CL_SetRecommended_f( void ) {
Com_SetRecommended();
}
/*
================
CL_RefPrintf
DLL glue
================
*/
static __attribute__ ((format (printf, 2, 3))) void QDECL CL_RefPrintf( int print_level, const char *fmt, ...) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof ( msg ), fmt, argptr );
va_end( argptr );
if ( print_level == PRINT_ALL ) {
Com_Printf( "%s", msg );
} else if ( print_level == PRINT_WARNING ) {
Com_Printf( S_COLOR_YELLOW "%s", msg ); // yellow
} else if ( print_level == PRINT_DEVELOPER ) {
Com_DPrintf( S_COLOR_RED "%s", msg ); // red
}
}
/*
============
CL_ShutdownRef
============
*/
void CL_ShutdownRef( void ) {
if ( re.Shutdown ) {
re.Shutdown( qtrue );
}
memset( &re, 0, sizeof( re ) );
#ifdef USE_RENDERER_DLOPEN
if ( rendererLib ) {
Sys_UnloadLibrary( rendererLib );
rendererLib = NULL;
}
#endif
}
/*
============
CL_InitRenderer
============
*/
void CL_InitRenderer( void ) {
// this sets up the renderer and calls R_Init
re.BeginRegistration( &cls.glconfig );
// load character sets
cls.charSetShader = re.RegisterShader( "gfx/2d/hudchars" );
cls.whiteShader = re.RegisterShader( "white" );
cls.consoleShader = re.RegisterShader( "console-16bit" ); // JPW NERVE shader works with 16bit
cls.consoleShader2 = re.RegisterShader( "console2-16bit" ); // JPW NERVE same
g_console_field_width = cls.glconfig.vidWidth / SMALLCHAR_WIDTH - 2;
g_consoleField.widthInChars = g_console_field_width;
}
/*
============================
CL_StartHunkUsers
After the server has cleared the hunk, these will need to be restarted
This is the only place that any of these functions are called from
============================
*/
void CL_StartHunkUsers( qboolean rendererOnly ) {
if ( !com_cl_running ) {
return;
}
if ( !com_cl_running->integer ) {
return;
}
if ( !cls.rendererStarted ) {
cls.rendererStarted = qtrue;
CL_InitRenderer();
}
if ( rendererOnly ) {
return;
}
if ( !cls.soundStarted ) {
cls.soundStarted = qtrue;
S_Init();
}
if ( !cls.soundRegistered ) {
cls.soundRegistered = qtrue;
S_BeginRegistration();
}
if( com_dedicated->integer ) {
return;
}
if ( !cls.uiStarted ) {
cls.uiStarted = qtrue;
CL_InitUI();
}
}
int CL_ScaledMilliseconds( void ) {
return Sys_Milliseconds() * com_timescale->value;
}
// DHM - Nerve
void CL_CheckAutoUpdate( void ) {
int validServerNum = 0;
int i = 0, rnd = 0;
netadr_t temp;
char *servername;
if ( !cl_autoupdate->integer ) {
return;
}
// Only check once per session
if ( autoupdateChecked ) {
return;
}
srand( Com_Milliseconds() );
// Find out how many update servers have valid DNS listings
for ( i = 0; i < MAX_AUTOUPDATE_SERVERS; i++ ) {
if ( NET_StringToAdr( cls.autoupdateServerNames[i], &temp, NA_UNSPEC ) ) {
validServerNum++;
}
}
// Pick a random server
if ( validServerNum > 1 ) {
rnd = rand() % validServerNum;
} else {
rnd = 0;
}
servername = cls.autoupdateServerNames[rnd];
Com_DPrintf( "Resolving AutoUpdate Server... " );
if ( !NET_StringToAdr( servername, &cls.autoupdateServer, NA_UNSPEC ) ) {
Com_DPrintf( "Couldn't resolve first address, trying default..." );
// Fall back to the first one
if ( !NET_StringToAdr( cls.autoupdateServerNames[0], &cls.autoupdateServer, NA_UNSPEC ) ) {
Com_DPrintf( "Failed to resolve any Auto-update servers.\n" );
autoupdateChecked = qtrue;
return;
}
}
cls.autoupdateServer.port = BigShort( PORT_SERVER );
Com_DPrintf( "%i.%i.%i.%i:%i\n", cls.autoupdateServer.ip[0], cls.autoupdateServer.ip[1],
cls.autoupdateServer.ip[2], cls.autoupdateServer.ip[3],
BigShort( cls.autoupdateServer.port ) );
NET_OutOfBandPrint( NS_CLIENT, cls.autoupdateServer, "getUpdateInfo \"%s\" \"%s\"-\"%s\"\n", Q3_VERSION, OS_STRING, ARCH_STRING );
CL_RequestMotd();
autoupdateChecked = qtrue;
}
void CL_GetAutoUpdate( void ) {
// Don't try and get an update if we haven't checked for one
if ( !autoupdateChecked ) {
return;
}
// Make sure there's a valid update file to request
if ( strlen( cl_updatefiles->string ) < 5 ) {
return;
}
Com_DPrintf( "Connecting to auto-update server...\n" );
S_StopAllSounds(); // NERVE - SMF
// starting to load a map so we get out of full screen ui mode
Cvar_Set( "r_uiFullScreen", "0" );
// clear any previous "server full" type messages
clc.serverMessage[0] = 0;
if ( com_sv_running->integer ) {
// if running a local server, kill it
SV_Shutdown( "Server quit\n" );
}
// make sure a local server is killed
Cvar_Set( "sv_killserver", "1" );
SV_Frame( 0 );
CL_Disconnect( qtrue );
Con_Close();
Q_strncpyz( clc.servername, "Auto-Updater", sizeof( clc.servername ) );
if ( cls.autoupdateServer.type == NA_BAD ) {
Com_Printf( "Bad server address\n" );
clc.state = CA_DISCONNECTED;
return;
}
// Copy auto-update server address to Server connect address
memcpy( &clc.serverAddress, &cls.autoupdateServer, sizeof( netadr_t ) );
Com_DPrintf( "%s resolved to %i.%i.%i.%i:%i\n", clc.servername,
clc.serverAddress.ip[0], clc.serverAddress.ip[1],
clc.serverAddress.ip[2], clc.serverAddress.ip[3],
BigShort( clc.serverAddress.port ) );
clc.state = CA_CONNECTING;
Key_SetCatcher( 0 );
clc.connectTime = -99999; // CL_CheckForResend() will fire immediately
clc.connectPacketCount = 0;
// server connection string
Cvar_Set( "cl_currentServerAddress", "Auto-Updater" );
}
// DHM - Nerve
/*
============
CL_RefMalloc
============
*/
#ifdef ZONE_DEBUG
void *CL_RefMallocDebug( int size, char *label, char *file, int line ) {
return Z_TagMallocDebug( size, TAG_RENDERER, label, file, line );
}
#else
void *CL_RefMalloc( int size ) {
return Z_TagMalloc( size, TAG_RENDERER );
}
#endif
/*
============
CL_RefTagFree
============
*/
void CL_RefTagFree( void ) {
Z_FreeTags( TAG_RENDERER );
return;
}
/*
============
CL_InitRef
============
*/
void CL_InitRef( void ) {
refimport_t ri;
refexport_t *ret;
#ifdef USE_RENDERER_DLOPEN
GetRefAPI_t GetRefAPI;
char dllName[MAX_OSPATH];
#endif
Com_Printf( "----- Initializing Renderer ----\n" );
#ifdef USE_RENDERER_DLOPEN
cl_renderer = Cvar_Get("cl_renderer", "opengl1", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED);
Com_sprintf(dllName, sizeof(dllName), "renderer_mp_%s_" ARCH_STRING DLL_EXT, cl_renderer->string);
if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString))
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Cvar_ForceReset("cl_renderer");
Com_sprintf(dllName, sizeof(dllName), "renderer_mp_opengl1_" ARCH_STRING DLL_EXT);
rendererLib = Sys_LoadDll(dllName, qfalse);
}
if(!rendererLib)
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Com_Error(ERR_FATAL, "Failed to load renderer");
}
GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI");
if(!GetRefAPI)
{
Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError());
}
#endif
ri.Cmd_AddCommand = Cmd_AddCommand;
ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
ri.Cmd_Argc = Cmd_Argc;
ri.Cmd_Argv = Cmd_Argv;
ri.Cmd_ExecuteText = Cbuf_ExecuteText;
ri.Printf = CL_RefPrintf;
ri.Error = Com_Error;
ri.Milliseconds = CL_ScaledMilliseconds;
#ifdef ZONE_DEBUG
ri.Z_MallocDebug = CL_RefMallocDebug;
#else
ri.Z_Malloc = CL_RefMalloc;
#endif
ri.Free = Z_Free;
ri.Tag_Free = CL_RefTagFree;
ri.Hunk_Clear = Hunk_ClearToMark;
#ifdef HUNK_DEBUG
ri.Hunk_AllocDebug = Hunk_AllocDebug;
#else
ri.Hunk_Alloc = Hunk_Alloc;
#endif
ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
ri.CM_ClusterPVS = CM_ClusterPVS;
ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
ri.FS_ReadFile = FS_ReadFile;
ri.FS_FreeFile = FS_FreeFile;
ri.FS_WriteFile = FS_WriteFile;
ri.FS_FreeFileList = FS_FreeFileList;
ri.FS_ListFiles = FS_ListFiles;
ri.FS_FileIsInPAK = FS_FileIsInPAK;
ri.FS_FileExists = FS_FileExists;
ri.Cvar_Get = Cvar_Get;
ri.Cvar_Set = Cvar_Set;
ri.Cvar_SetValue = Cvar_SetValue;
ri.Cvar_CheckRange = Cvar_CheckRange;
ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
// cinematic stuff
ri.CIN_UploadCinematic = CIN_UploadCinematic;
ri.CIN_PlayCinematic = CIN_PlayCinematic;
ri.CIN_RunCinematic = CIN_RunCinematic;
ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;
ri.IN_Init = IN_Init;
ri.IN_Shutdown = IN_Shutdown;
ri.IN_Restart = IN_Restart;
ri.ftol = Q_ftol;
ri.Sys_SetEnv = Sys_SetEnv;
ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit;
ri.Sys_GLimpInit = Sys_GLimpInit;
ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;
ret = GetRefAPI( REF_API_VERSION, &ri );
if ( !ret ) {
Com_Error( ERR_FATAL, "Couldn't initialize refresh" );
}
re = *ret;
Com_Printf( "---- Renderer Initialization Complete ----\n" );
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
}
// RF, trap manual client damage commands so users can't issue them manually
void CL_ClientDamageCommand( void ) {
// do nothing
}
#if defined (__i386__)
#define BIN_STRING "x86"
#endif
// NERVE - SMF
void CL_startSingleplayer_f( void ) {
char binName[MAX_OSPATH];
#if defined(_WIN64) || defined(__WIN64__)
Com_sprintf(binName, sizeof(binName), "ioWolfSP." ARCH_STRING ".exe");
Sys_StartProcess( binName, qtrue );
#elif defined(_WIN32) || defined(__WIN32__)
Com_sprintf(binName, sizeof(binName), "ioWolfSP." BIN_STRING ".exe");
Sys_StartProcess( binName, qtrue );
#elif defined(__i386__) && (!defined(_WIN32) || !defined(__WIN32__))
Com_sprintf(binName, sizeof(binName), "./iowolfsp." BIN_STRING );
Sys_StartProcess( binName, qtrue );
#else
Com_sprintf(binName, sizeof(binName), "./iowolfsp." ARCH_STRING );
Sys_StartProcess( binName, qtrue );
#endif
}
void CL_SaveTranslations_f( void ) {
CL_SaveTransTable( "scripts/translation.cfg", qfalse );
}
void CL_SaveNewTranslations_f( void ) {
char fileName[512];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: SaveNewTranslations <filename>\n" );
return;
}
strcpy( fileName, va( "translations/%s.cfg", Cmd_Argv( 1 ) ) );
CL_SaveTransTable( fileName, qtrue );
}
void CL_LoadTranslations_f( void ) {
CL_ReloadTranslation();
}
// -NERVE - SMF
//===========================================================================================
/*
===============
CL_Video_f
video
video [filename]
===============
*/
void CL_Video_f( void )
{
char filename[ MAX_OSPATH ];
int i, last;
if( !clc.demoplaying )
{
Com_Printf( "The video command can only be used when playing back demos\n" );
return;
}
if( Cmd_Argc( ) == 2 )
{
// explicit filename
Com_sprintf( filename, MAX_OSPATH, "videos/%s.avi", Cmd_Argv( 1 ) );
}
else
{
// scan for a free filename
for( i = 0; i <= 9999; i++ )
{
int a, b, c, d;
last = i;
a = last / 1000;
last -= a * 1000;
b = last / 100;
last -= b * 100;
c = last / 10;
last -= c * 10;
d = last;
Com_sprintf( filename, MAX_OSPATH, "videos/video%d%d%d%d.avi", a, b, c, d );
if( !FS_FileExists( filename ) )
break; // file doesn't exist
}
if( i > 9999 )
{
Com_Printf( S_COLOR_RED "ERROR: no free file names to create video\n" );
return;
}
}
CL_OpenAVIForWriting( filename );
}
/*
===============
CL_StopVideo_f
===============
*/
void CL_StopVideo_f( void )
{
CL_CloseAVI( );
}
/*
===============
CL_GenerateQKey
test to see if a valid QKEY_FILE exists. If one does not, try to generate
it by filling it with 2048 bytes of random data.
===============
*/
static void CL_GenerateQKey(void)
{
int len = 0;
unsigned char buff[ QKEY_SIZE ];
fileHandle_t f;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
if( len == QKEY_SIZE ) {
Com_Printf( "RTCWKEY found.\n" );
return;
}
else {
if( len > 0 ) {
Com_Printf( "RTCWKEY file size != %d, regenerating\n",
QKEY_SIZE );
}
Com_Printf( "RTCWKEY building random string\n" );
Com_RandomBytes( buff, sizeof(buff) );
f = FS_SV_FOpenFileWrite( QKEY_FILE );
if( !f ) {
Com_Printf( "RTCWKEY could not open %s for write\n",
QKEY_FILE );
return;
}
FS_Write( buff, sizeof(buff), f );
FS_FCloseFile( f );
Com_Printf( "RTCWKEY generated\n" );
}
}
/*
====================
CL_Init
====================
*/
void CL_Init( void ) {
Com_Printf( "----- Client Initialization -----\n" );
Con_Init();
if(!com_fullyInitialized)
{
CL_ClearState();
clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
cl_oldGameSet = qfalse;
}
cls.realtime = 0;
CL_InitInput();
//
// register our variables
//
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
#ifdef UPDATE_SERVER_NAME
cl_motd = Cvar_Get( "cl_motd", "1", 0 );
#endif
cl_autoupdate = Cvar_Get( "cl_autoupdate", "0", CVAR_ARCHIVE );
cl_timeout = Cvar_Get( "cl_timeout", "200", 0 );
cl_wavefilerecord = Cvar_Get( "cl_wavefilerecord", "0", CVAR_TEMP );
cl_timeNudge = Cvar_Get( "cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get( "cl_shownet", "0", CVAR_TEMP );
cl_shownuments = Cvar_Get( "cl_shownuments", "0", CVAR_TEMP );
cl_visibleClients = Cvar_Get( "cl_visibleClients", "0", CVAR_TEMP );
cl_showServerCommands = Cvar_Get( "cl_showServerCommands", "0", 0 );
cl_showSend = Cvar_Get( "cl_showSend", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get( "cl_showTimeDelta", "0", CVAR_TEMP );
cl_freezeDemo = Cvar_Get( "cl_freezeDemo", "0", CVAR_TEMP );
rcon_client_password = Cvar_Get( "rconPassword", "", CVAR_TEMP );
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_timedemo = Cvar_Get( "timedemo", "0", 0 );
cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE);
cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE);
cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE);
cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE);
cl_avidemo = Cvar_Get( "cl_avidemo", "0", 0 );
cl_forceavidemo = Cvar_Get( "cl_forceavidemo", "0", 0 );
rconAddress = Cvar_Get( "rconAddress", "", 0 );
cl_yawspeed = Cvar_Get( "cl_yawspeed", "140", CVAR_ARCHIVE );
cl_pitchspeed = Cvar_Get( "cl_pitchspeed", "140", CVAR_ARCHIVE );
cl_anglespeedkey = Cvar_Get( "cl_anglespeedkey", "1.5", 0 );
cl_maxpackets = Cvar_Get( "cl_maxpackets", "38", CVAR_ARCHIVE );
cl_packetdup = Cvar_Get( "cl_packetdup", "1", CVAR_ARCHIVE );
cl_showPing = Cvar_Get( "cl_showPing", "0", CVAR_ARCHIVE );
cl_run = Cvar_Get( "cl_run", "1", CVAR_ARCHIVE );
cl_sensitivity = Cvar_Get( "sensitivity", "5", CVAR_ARCHIVE );
cl_mouseAccel = Cvar_Get( "cl_mouseAccel", "0", CVAR_ARCHIVE );
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE );
// 0: legacy mouse acceleration
// 1: new implementation
cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE );
// offset for the power function (for style 1, ignored otherwise)
// this should be set to the max rate value
cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE );
Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse);
cl_showMouseRate = Cvar_Get( "cl_showmouserate", "0", 0 );
cl_allowDownload = Cvar_Get( "cl_allowDownload", "1", CVAR_ARCHIVE );
#ifdef USE_CURL_DLOPEN
cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE | CVAR_PROTECTED);
#endif
// init autoswitch so the ui will have it correctly even
// if the cgame hasn't been started
// -NERVE - SMF - disabled autoswitch by default
Cvar_Get( "cg_autoswitch", "0", CVAR_ARCHIVE );
// Rafael - particle switch
Cvar_Get( "cg_wolfparticles", "1", CVAR_ARCHIVE );
// done
cl_conXOffset = Cvar_Get( "cl_conXOffset", "0", 0 );
cl_inGameVideo = Cvar_Get( "r_inGameVideo", "1", CVAR_ARCHIVE );
cl_serverStatusResendTime = Cvar_Get( "cl_serverStatusResendTime", "750", 0 );
// RF
cl_recoilPitch = Cvar_Get( "cg_recoilPitch", "0", CVAR_ROM );
cl_bypassMouseInput = Cvar_Get( "cl_bypassMouseInput", "0", 0 ); //CVAR_ROM ); // NERVE - SMF
m_pitch = Cvar_Get( "m_pitch", "0.022", CVAR_ARCHIVE );
m_yaw = Cvar_Get( "m_yaw", "0.022", CVAR_ARCHIVE );
m_forward = Cvar_Get( "m_forward", "0.25", CVAR_ARCHIVE );
m_side = Cvar_Get( "m_side", "0.25", CVAR_ARCHIVE );
m_filter = Cvar_Get( "m_filter", "0", CVAR_ARCHIVE );
j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE);
j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE);
j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE);
j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE);
j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE);
j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE);
j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE);
j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE);
j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE);
j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE);
Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM );
Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE );
cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE);
cl_guid = Cvar_Get( "cl_guid", "unknown", CVAR_USERINFO | CVAR_ROM );
cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE);
// ~ and `, as keys and characters
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE);
// NERVE - SMF
Cvar_Get( "cg_drawCompass", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_drawNotifyText", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_quickMessageAlt", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_popupLimboMenu", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_descriptiveText", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_drawTeamOverlay", "2", CVAR_ARCHIVE );
Cvar_Get( "cg_uselessNostalgia", "0", CVAR_ARCHIVE ); // JPW NERVE
Cvar_Get( "cg_drawGun", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_cursorHints", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_voiceSpriteTime", "6000", CVAR_ARCHIVE );
Cvar_Get( "cg_teamChatsOnly", "0", CVAR_ARCHIVE );
Cvar_Get( "cg_noVoiceChats", "0", CVAR_ARCHIVE );
Cvar_Get( "cg_noVoiceText", "0", CVAR_ARCHIVE );
Cvar_Get( "cg_crosshairSize", "48", CVAR_ARCHIVE );
Cvar_Get( "cg_drawCrosshair", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_zoomDefaultSniper", "20", CVAR_ARCHIVE );
Cvar_Get( "cg_zoomstepsniper", "2", CVAR_ARCHIVE );
Cvar_Get( "mp_playerType", "0", 0 );
Cvar_Get( "mp_currentPlayerType", "0", 0 );
Cvar_Get( "mp_weapon", "0", 0 );
Cvar_Get( "mp_team", "0", 0 );
Cvar_Get( "mp_currentTeam", "0", 0 );
// -NERVE - SMF
// userinfo
Cvar_Get( "name", "WolfPlayer", CVAR_USERINFO | CVAR_ARCHIVE );
cl_rate = Cvar_Get( "rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE ); // NERVE - SMF - changed from 3000
Cvar_Get( "snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "model", "multi", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "head", "default", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "color", "4", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "sex", "male", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "password", "", CVAR_USERINFO );
Cvar_Get( "cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE );
#ifdef USE_MUMBLE
cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH);
cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE);
#endif
#ifdef USE_VOIP
cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0);
cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0);
cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE);
cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE);
cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE);
cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE);
cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE);
cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE);
Cvar_CheckRange( cl_voip, 0, 1, qtrue );
cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM);
#endif
//----(SA) added
Cvar_Get( "cg_autoactivate", "1", CVAR_USERINFO | CVAR_ARCHIVE );
//----(SA) end
// cgame might not be initialized before menu is used
Cvar_Get( "cg_viewsize", "100", CVAR_ARCHIVE );
// Make sure cg_stereoSeparation is zero as that variable is deprecated and should not be used anymore.
Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM);
Cvar_Get( "cg_autoReload", "1", CVAR_ARCHIVE | CVAR_USERINFO );
cl_missionStats = Cvar_Get( "g_missionStats", "0", CVAR_ROM );
cl_waitForFire = Cvar_Get( "cl_waitForFire", "0", CVAR_ROM );
// NERVE - SMF - localization
cl_language = Cvar_Get( "cl_language", "0", CVAR_ARCHIVE );
cl_debugTranslation = Cvar_Get( "cl_debugTranslation", "0", 0 );
// -NERVE - SMF
// DHM - Nerve :: Auto-update
cl_updateavailable = Cvar_Get( "cl_updateavailable", "0", CVAR_ROM );
cl_updatefiles = Cvar_Get( "cl_updatefiles", "", CVAR_ROM );
Q_strncpyz( cls.autoupdateServerNames[0], AUTOUPDATE_SERVER1_NAME, MAX_QPATH );
Q_strncpyz( cls.autoupdateServerNames[1], AUTOUPDATE_SERVER2_NAME, MAX_QPATH );
Q_strncpyz( cls.autoupdateServerNames[2], AUTOUPDATE_SERVER3_NAME, MAX_QPATH );
Q_strncpyz( cls.autoupdateServerNames[3], AUTOUPDATE_SERVER4_NAME, MAX_QPATH );
Q_strncpyz( cls.autoupdateServerNames[4], AUTOUPDATE_SERVER5_NAME, MAX_QPATH );
// DHM - Nerve
//
// register our commands
//
Cmd_AddCommand( "cmd", CL_ForwardToServer_f );
Cmd_AddCommand( "configstrings", CL_Configstrings_f );
Cmd_AddCommand( "clientinfo", CL_Clientinfo_f );
Cmd_AddCommand( "snd_restart", CL_Snd_Restart_f );
Cmd_AddCommand( "vid_restart", CL_Vid_Restart_f );
Cmd_AddCommand( "ui_restart", CL_UI_Restart_f ); // NERVE - SMF
Cmd_AddCommand( "disconnect", CL_Disconnect_f );
Cmd_AddCommand( "record", CL_Record_f );
Cmd_AddCommand( "demo", CL_PlayDemo_f );
Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName );
Cmd_AddCommand( "cinematic", CL_PlayCinematic_f );
Cmd_AddCommand( "stoprecord", CL_StopRecord_f );
Cmd_AddCommand( "connect", CL_Connect_f );
Cmd_AddCommand( "reconnect", CL_Reconnect_f );
Cmd_AddCommand( "localservers", CL_LocalServers_f );
Cmd_AddCommand( "globalservers", CL_GlobalServers_f );
Cmd_AddCommand( "rcon", CL_Rcon_f );
Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon );
Cmd_AddCommand( "ping", CL_Ping_f );
Cmd_AddCommand( "serverstatus", CL_ServerStatus_f );
Cmd_AddCommand( "showip", CL_ShowIP_f );
Cmd_AddCommand( "fs_openedList", CL_OpenedPK3List_f );
Cmd_AddCommand( "fs_referencedList", CL_ReferencedPK3List_f );
Cmd_AddCommand ("video", CL_Video_f );
Cmd_AddCommand ("stopvideo", CL_StopVideo_f );
// Ridah, startup-caching system
Cmd_AddCommand( "cache_startgather", CL_Cache_StartGather_f );
Cmd_AddCommand( "cache_usedfile", CL_Cache_UsedFile_f );
Cmd_AddCommand( "cache_setindex", CL_Cache_SetIndex_f );
Cmd_AddCommand( "cache_mapchange", CL_Cache_MapChange_f );
Cmd_AddCommand( "cache_endgather", CL_Cache_EndGather_f );
Cmd_AddCommand( "updatehunkusage", CL_UpdateLevelHunkUsage );
Cmd_AddCommand( "updatescreen", SCR_UpdateScreen );
// done.
Cmd_AddCommand( "SaveTranslations", CL_SaveTranslations_f ); // NERVE - SMF - localization
Cmd_AddCommand( "SaveNewTranslations", CL_SaveNewTranslations_f ); // NERVE - SMF - localization
Cmd_AddCommand( "LoadTranslations", CL_LoadTranslations_f ); // NERVE - SMF - localization
// NERVE - SMF - don't do this in multiplayer
// RF, add this command so clients can't bind a key to send client damage commands to the server
// Cmd_AddCommand( "cld", CL_ClientDamageCommand );
Cmd_AddCommand( "startSingleplayer", CL_startSingleplayer_f ); // NERVE - SMF
Cmd_AddCommand( "setRecommended", CL_SetRecommended_f );
CL_InitRef();
SCR_Init();
// Cbuf_Execute();
Cvar_Set( "cl_running", "1" );
// DHM - Nerve
autoupdateChecked = qfalse;
autoupdateStarted = qfalse;
CL_InitTranslation(); // NERVE - SMF - localization
CL_GenerateQKey();
CL_UpdateGUID( NULL, 0 );
Com_Printf( "----- Client Initialization Complete -----\n" );
}
/*
===============
CL_Shutdown
===============
*/
void CL_Shutdown( char *finalmsg, qboolean disconnect, qboolean quit ) {
static qboolean recursive = qfalse;
// check whether the client is running at all.
if(!(com_cl_running && com_cl_running->integer))
return;
Com_Printf( "----- Client Shutdown (%s) -----\n", finalmsg );
if ( recursive ) {
Com_Printf( "WARNING: Recursive shutdown\n" );
return;
}
recursive = qtrue;
noGameRestart = quit;
if(disconnect)
CL_Disconnect(qtrue);
CL_ClearMemory(qtrue);
CL_Snd_Shutdown();
Cmd_RemoveCommand( "cmd" );
Cmd_RemoveCommand( "configstrings" );
Cmd_RemoveCommand ("clientinfo");
Cmd_RemoveCommand( "snd_restart" );
Cmd_RemoveCommand( "vid_restart" );
Cmd_RemoveCommand( "ui_restart" );
Cmd_RemoveCommand( "disconnect" );
Cmd_RemoveCommand( "record" );
Cmd_RemoveCommand( "demo" );
Cmd_RemoveCommand( "cinematic" );
Cmd_RemoveCommand( "stoprecord" );
Cmd_RemoveCommand( "connect" );
Cmd_RemoveCommand ("reconnect");
Cmd_RemoveCommand( "localservers" );
Cmd_RemoveCommand( "globalservers" );
Cmd_RemoveCommand( "rcon" );
Cmd_RemoveCommand( "ping" );
Cmd_RemoveCommand( "serverstatus" );
Cmd_RemoveCommand( "showip" );
Cmd_RemoveCommand ("fs_openedList");
Cmd_RemoveCommand ("fs_referencedList");
Cmd_RemoveCommand( "model" );
Cmd_RemoveCommand ("video");
Cmd_RemoveCommand ("stopvideo");
// Ridah, startup-caching system
Cmd_RemoveCommand( "cache_startgather" );
Cmd_RemoveCommand( "cache_usedfile" );
Cmd_RemoveCommand( "cache_setindex" );
Cmd_RemoveCommand( "cache_mapchange" );
Cmd_RemoveCommand( "cache_endgather" );
Cmd_RemoveCommand( "updatehunkusage" );
// done.
Cmd_RemoveCommand( "updatescreen" );
Cmd_RemoveCommand( "SaveTranslations" ); // NERVE - SMF - localization
Cmd_RemoveCommand( "SaveNewTranslations" ); // NERVE - SMF - localization
Cmd_RemoveCommand( "LoadTranslations" ); // NERVE - SMF - localization
Cmd_RemoveCommand( "startSingleplayer" ); // NERVE - SMF
Cmd_RemoveCommand( "setRecommended" );
CL_ShutdownInput();
Con_Shutdown();
Cvar_Set( "cl_running", "0" );
recursive = qfalse;
memset( &cls, 0, sizeof( cls ) );
Key_SetCatcher( 0 );
Com_Printf( "-----------------------\n" );
}
static void CL_SetServerInfo( serverInfo_t *server, const char *info, int ping ) {
if ( server ) {
if ( info ) {
server->clients = atoi( Info_ValueForKey( info, "clients" ) );
Q_strncpyz( server->hostName,Info_ValueForKey( info, "hostname" ), MAX_NAME_LENGTH );
Q_strncpyz( server->mapName, Info_ValueForKey( info, "mapname" ), MAX_NAME_LENGTH );
server->maxClients = atoi( Info_ValueForKey( info, "sv_maxclients" ) );
Q_strncpyz( server->game,Info_ValueForKey( info, "game" ), MAX_NAME_LENGTH );
server->gameType = atoi( Info_ValueForKey( info, "gametype" ) );
server->netType = atoi( Info_ValueForKey( info, "nettype" ) );
server->minPing = atoi( Info_ValueForKey( info, "minping" ) );
server->maxPing = atoi( Info_ValueForKey( info, "maxping" ) );
server->allowAnonymous = atoi( Info_ValueForKey( info, "sv_allowAnonymous" ) );
server->friendlyFire = atoi( Info_ValueForKey( info, "friendlyFire" ) ); // NERVE - SMF
server->maxlives = atoi( Info_ValueForKey( info, "maxlives" ) ); // NERVE - SMF
server->tourney = atoi( Info_ValueForKey( info, "tourney" ) ); // NERVE - SMF
server->punkbuster = atoi( Info_ValueForKey( info, "punkbuster" ) ); // DHM - Nerve
Q_strncpyz( server->gameName, Info_ValueForKey( info, "gamename" ), MAX_NAME_LENGTH ); // Arnout
server->antilag = atoi( Info_ValueForKey( info, "g_antilag" ) );
server->g_humanplayers = atoi( Info_ValueForKey( info, "g_humanplayers" ) );
server->g_needpass = atoi( Info_ValueForKey( info, "g_needpass" ) );
}
server->ping = ping;
}
}
static void CL_SetServerInfoByAddress( netadr_t from, const char *info, int ping ) {
int i;
for ( i = 0; i < MAX_OTHER_SERVERS; i++ ) {
if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) {
CL_SetServerInfo( &cls.localServers[i], info, ping );
}
}
for ( i = 0; i < MAX_GLOBAL_SERVERS; i++ ) {
if ( NET_CompareAdr( from, cls.globalServers[i].adr ) ) {
CL_SetServerInfo( &cls.globalServers[i], info, ping );
}
}
for ( i = 0; i < MAX_OTHER_SERVERS; i++ ) {
if ( NET_CompareAdr( from, cls.favoriteServers[i].adr ) ) {
CL_SetServerInfo( &cls.favoriteServers[i], info, ping );
}
}
}
/*
===================
CL_ServerInfoPacket
===================
*/
void CL_ServerInfoPacket( netadr_t from, msg_t *msg ) {
int i, type;
char info[MAX_INFO_STRING];
char *infoString;
int prot;
char *gamename;
qboolean gameMismatch;
infoString = MSG_ReadString( msg );
// if this isn't the correct gamename, ignore it
gamename = Info_ValueForKey( infoString, "gamename" );
#ifdef LEGACY_PROTOCOL
// gamename is optional for legacy protocol
if (com_legacyprotocol->integer && !*gamename)
gameMismatch = qfalse;
else
#endif
gameMismatch = !*gamename || strcmp(gamename, com_gamename->string) != 0;
if (gameMismatch)
{
Com_DPrintf( "Game mismatch in info packet: %s\n", infoString );
return;
}
// if this isn't the correct protocol version, ignore it
prot = atoi( Info_ValueForKey( infoString, "protocol" ) );
if(prot != com_protocol->integer
#ifdef LEGACY_PROTOCOL
&& prot != com_legacyprotocol->integer
#endif
)
{
Com_DPrintf( "Different protocol info packet: %s\n", infoString );
return;
}
// iterate servers waiting for ping response
for ( i = 0; i < MAX_PINGREQUESTS; i++ )
{
if ( cl_pinglist[i].adr.port && !cl_pinglist[i].time && NET_CompareAdr( from, cl_pinglist[i].adr ) ) {
// calc ping time
cl_pinglist[i].time = Sys_Milliseconds() - cl_pinglist[i].start;
Com_DPrintf( "ping time %dms from %s\n", cl_pinglist[i].time, NET_AdrToString( from ) );
// save of info
Q_strncpyz( cl_pinglist[i].info, infoString, sizeof( cl_pinglist[i].info ) );
// tack on the net type
// NOTE: make sure these types are in sync with the netnames strings in the UI
switch ( from.type )
{
case NA_BROADCAST:
case NA_IP:
type = 1;
break;
case NA_IP6:
type = 2;
break;
default:
type = 0;
break;
}
Info_SetValueForKey( cl_pinglist[i].info, "nettype", va( "%d", type ) );
CL_SetServerInfoByAddress( from, infoString, cl_pinglist[i].time );
return;
}
}
// if not just sent a local broadcast or pinging local servers
if ( cls.pingUpdateSource != AS_LOCAL ) {
return;
}
for ( i = 0 ; i < MAX_OTHER_SERVERS ; i++ ) {
// empty slot
if ( cls.localServers[i].adr.port == 0 ) {
break;
}
// avoid duplicate
if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) {
return;
}
}
if ( i == MAX_OTHER_SERVERS ) {
Com_DPrintf( "MAX_OTHER_SERVERS hit, dropping infoResponse\n" );
return;
}
// add this to the list
cls.numlocalservers = i + 1;
CL_InitServerInfo( &cls.localServers[i], &from );
Q_strncpyz( info, MSG_ReadString( msg ), MAX_INFO_STRING );
if ( strlen( info ) ) {
if ( info[strlen( info ) - 1] != '\n' ) {
Q_strcat( info, sizeof(info), "\n" );
}
Com_Printf( "%s: %s", NET_AdrToStringwPort( from ), info );
}
}
/*
===================
CL_UpdateInfoPacket
===================
*/
void CL_UpdateInfoPacket( netadr_t from ) {
if ( cls.autoupdateServer.type == NA_BAD ) {
Com_DPrintf( "CL_UpdateInfoPacket: Auto-Updater has bad address\n" );
return;
}
Com_DPrintf( "Auto-Updater resolved to %i.%i.%i.%i:%i\n",
cls.autoupdateServer.ip[0], cls.autoupdateServer.ip[1],
cls.autoupdateServer.ip[2], cls.autoupdateServer.ip[3],
BigShort( cls.autoupdateServer.port ) );
if ( !NET_CompareAdr( from, cls.autoupdateServer ) ) {
Com_DPrintf( "CL_UpdateInfoPacket: Received packet from %i.%i.%i.%i:%i\n",
from.ip[0], from.ip[1], from.ip[2], from.ip[3],
BigShort( from.port ) );
return;
}
Cvar_Set( "cl_updateavailable", Cmd_Argv( 1 ) );
if ( !Q_stricmp( cl_updateavailable->string, "1" ) ) {
Cvar_Set( "cl_updatefiles", Cmd_Argv( 2 ) );
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_WM_AUTOUPDATE );
}
}
// DHM - Nerve
/*
===================
CL_GetServerStatus
===================
*/
serverStatus_t *CL_GetServerStatus( netadr_t from ) {
int i, oldest, oldestTime;
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
return &cl_serverStatusList[i];
}
}
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( cl_serverStatusList[i].retrieved ) {
return &cl_serverStatusList[i];
}
}
oldest = -1;
oldestTime = 0;
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( oldest == -1 || cl_serverStatusList[i].startTime < oldestTime ) {
oldest = i;
oldestTime = cl_serverStatusList[i].startTime;
}
}
return &cl_serverStatusList[oldest];
}
/*
===================
CL_ServerStatus
===================
*/
int CL_ServerStatus( char *serverAddress, char *serverStatusString, int maxLen ) {
int i;
netadr_t to;
serverStatus_t *serverStatus;
// if no server address then reset all server status requests
if ( !serverAddress ) {
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
cl_serverStatusList[i].address.port = 0;
cl_serverStatusList[i].retrieved = qtrue;
}
return qfalse;
}
// get the address
if ( !NET_StringToAdr( serverAddress, &to, NA_UNSPEC) ) {
return qfalse;
}
serverStatus = CL_GetServerStatus( to );
// if no server status string then reset the server status request for this address
if ( !serverStatusString ) {
serverStatus->retrieved = qtrue;
return qfalse;
}
// if this server status request has the same address
if ( NET_CompareAdr( to, serverStatus->address ) ) {
// if we received a response for this server status request
if ( !serverStatus->pending ) {
Q_strncpyz( serverStatusString, serverStatus->string, maxLen );
serverStatus->retrieved = qtrue;
serverStatus->startTime = 0;
return qtrue;
}
// resend the request regularly
else if ( serverStatus->startTime < Com_Milliseconds() - cl_serverStatusResendTime->integer ) {
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->time = 0;
serverStatus->startTime = Com_Milliseconds();
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
}
// if retrieved
else if ( serverStatus->retrieved ) {
serverStatus->address = to;
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->startTime = Com_Milliseconds();
serverStatus->time = 0;
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
return qfalse;
}
/*
===================
CL_ServerStatusResponse
===================
*/
void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) {
char *s;
char info[MAX_INFO_STRING];
int i, l, score, ping;
int len;
serverStatus_t *serverStatus;
serverStatus = NULL;
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
serverStatus = &cl_serverStatusList[i];
break;
}
}
// if we didn't request this server status
if ( !serverStatus ) {
return;
}
s = MSG_ReadStringLine( msg );
len = 0;
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "%s", s );
if ( serverStatus->print ) {
Com_Printf( "Server settings:\n" );
// print cvars
while ( *s ) {
for ( i = 0; i < 2 && *s; i++ ) {
if ( *s == '\\' ) {
s++;
}
l = 0;
while ( *s ) {
info[l++] = *s;
if ( l >= MAX_INFO_STRING - 1 ) {
break;
}
s++;
if ( *s == '\\' ) {
break;
}
}
info[l] = '\0';
if ( i ) {
Com_Printf( "%s\n", info );
} else {
Com_Printf( "%-24s", info );
}
}
}
}
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\" );
if ( serverStatus->print ) {
Com_Printf( "\nPlayers:\n" );
Com_Printf( "num: score: ping: name:\n" );
}
for ( i = 0, s = MSG_ReadStringLine( msg ); *s; s = MSG_ReadStringLine( msg ), i++ ) {
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\%s", s );
if ( serverStatus->print ) {
score = ping = 0;
sscanf( s, "%d %d", &score, &ping );
s = strchr( s, ' ' );
if ( s ) {
s = strchr( s + 1, ' ' );
}
if ( s ) {
s++;
} else {
s = "unknown";
}
Com_Printf( "%-2d %-3d %-3d %s\n", i, score, ping, s );
}
}
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\" );
serverStatus->time = Com_Milliseconds();
serverStatus->address = from;
serverStatus->pending = qfalse;
if (serverStatus->print) {
serverStatus->retrieved = qtrue;
}
}
/*
==================
CL_LocalServers_f
==================
*/
void CL_LocalServers_f( void ) {
char *message;
int i, j;
netadr_t to;
Com_Printf( "Scanning for servers on the local network...\n" );
// reset the list, waiting for response
cls.numlocalservers = 0;
cls.pingUpdateSource = AS_LOCAL;
for ( i = 0; i < MAX_OTHER_SERVERS; i++ ) {
qboolean b = cls.localServers[i].visible;
Com_Memset( &cls.localServers[i], 0, sizeof( cls.localServers[i] ) );
cls.localServers[i].visible = b;
}
Com_Memset( &to, 0, sizeof( to ) );
// The 'xxx' in the message is a challenge that will be echoed back
// by the server. We don't care about that here, but master servers
// can use that to prevent spoofed server responses from invalid ip
message = "\377\377\377\377getinfo xxx";
// send each message twice in case one is dropped
for ( i = 0 ; i < 2 ; i++ ) {
// send a broadcast packet on each server port
// we support multiple server ports so a single machine
// can nicely run multiple servers
for ( j = 0 ; j < NUM_SERVER_PORTS ; j++ ) {
to.port = BigShort( (short)( PORT_SERVER + j ) );
to.type = NA_BROADCAST;
NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
to.type = NA_MULTICAST6;
NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
}
}
}
/*
==================
CL_GlobalServers_f
==================
*/
void CL_GlobalServers_f( void ) {
netadr_t to;
int count, i, masterNum;
char command[1024], *masteraddress;
if ((count = Cmd_Argc()) < 3 || (masterNum = atoi(Cmd_Argv(1))) < 0 || masterNum > MAX_MASTER_SERVERS - 1)
{
Com_Printf("usage: globalservers <master# 0-%d> <protocol> [keywords]\n", MAX_MASTER_SERVERS - 1);
return;
}
sprintf(command, "sv_master%d", masterNum + 1);
masteraddress = Cvar_VariableString(command);
if(!*masteraddress)
{
Com_Printf( "CL_GlobalServers_f: Error: No master server address given.\n");
return;
}
// reset the list, waiting for response
// -1 is used to distinguish a "no response"
i = NET_StringToAdr(masteraddress, &to, NA_UNSPEC);
if(!i)
{
Com_Printf( "CL_GlobalServers_f: Error: could not resolve address of master %s\n", masteraddress);
return;
}
else if(i == 2)
to.port = BigShort(PORT_MASTER);
Com_Printf("Requesting servers from master %s...\n", masteraddress);
cls.numglobalservers = -1;
cls.pingUpdateSource = AS_GLOBAL;
// Use the extended query for IPv6 masters
if (to.type == NA_IP6 || to.type == NA_MULTICAST6)
{
int v4enabled = Cvar_VariableIntegerValue("net_enabled") & NET_ENABLEV4;
if(v4enabled)
{
Com_sprintf(command, sizeof(command), "getserversExt %s %s",
com_gamename->string, Cmd_Argv(2));
}
else
{
Com_sprintf(command, sizeof(command), "getserversExt %s %s ipv6",
com_gamename->string, Cmd_Argv(2));
}
}
else if ( !Q_stricmp( com_gamename->string, LEGACY_MASTER_GAMENAME ) )
Com_sprintf(command, sizeof(command), "getservers %s",
Cmd_Argv(2));
else
Com_sprintf(command, sizeof(command), "getservers %s %s",
com_gamename->string, Cmd_Argv(2));
for (i=3; i < count; i++)
{
Q_strcat(command, sizeof(command), " ");
Q_strcat(command, sizeof(command), Cmd_Argv(i));
}
NET_OutOfBandPrint( NS_SERVER, to, "%s", command );
}
/*
==================
CL_GetPing
==================
*/
void CL_GetPing( int n, char *buf, int buflen, int *pingtime ) {
const char *str;
int time;
int maxPing;
if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port)
{
// empty or invalid slot
buf[0] = '\0';
*pingtime = 0;
return;
}
str = NET_AdrToStringwPort( cl_pinglist[n].adr );
Q_strncpyz( buf, str, buflen );
time = cl_pinglist[n].time;
if ( !time ) {
// check for timeout
time = Sys_Milliseconds() - cl_pinglist[n].start;
maxPing = Cvar_VariableIntegerValue( "cl_maxPing" );
if ( maxPing < 100 ) {
maxPing = 100;
}
if ( time < maxPing ) {
// not timed out yet
time = 0;
}
}
CL_SetServerInfoByAddress( cl_pinglist[n].adr, cl_pinglist[n].info, cl_pinglist[n].time );
*pingtime = time;
}
/*
==================
CL_GetPingInfo
==================
*/
void CL_GetPingInfo( int n, char *buf, int buflen ) {
if ( n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port ) {
// empty or invalid slot
if ( buflen ) {
buf[0] = '\0';
}
return;
}
Q_strncpyz( buf, cl_pinglist[n].info, buflen );
}
/*
==================
CL_ClearPing
==================
*/
void CL_ClearPing( int n ) {
if ( n < 0 || n >= MAX_PINGREQUESTS ) {
return;
}
cl_pinglist[n].adr.port = 0;
}
/*
==================
CL_GetPingQueueCount
==================
*/
int CL_GetPingQueueCount( void ) {
int i;
int count;
ping_t* pingptr;
count = 0;
pingptr = cl_pinglist;
for ( i = 0; i < MAX_PINGREQUESTS; i++, pingptr++ ) {
if ( pingptr->adr.port ) {
count++;
}
}
return ( count );
}
/*
==================
CL_GetFreePing
==================
*/
ping_t* CL_GetFreePing( void ) {
ping_t* pingptr;
ping_t* best;
int oldest;
int i;
int time;
pingptr = cl_pinglist;
for ( i = 0; i < MAX_PINGREQUESTS; i++, pingptr++ )
{
// find free ping slot
if ( pingptr->adr.port ) {
if ( !pingptr->time ) {
if (Sys_Milliseconds() - pingptr->start < 500)
{
// still waiting for response
continue;
}
} else if ( pingptr->time < 500 ) {
// results have not been queried
continue;
}
}
// clear it
pingptr->adr.port = 0;
return ( pingptr );
}
// use oldest entry
pingptr = cl_pinglist;
best = cl_pinglist;
oldest = INT_MIN;
for ( i = 0; i < MAX_PINGREQUESTS; i++, pingptr++ )
{
// scan for oldest
time = Sys_Milliseconds() - pingptr->start;
if ( time > oldest ) {
oldest = time;
best = pingptr;
}
}
return ( best );
}
/*
==================
CL_Ping_f
==================
*/
void CL_Ping_f( void ) {
netadr_t to;
ping_t* pingptr;
char* server;
int argc;
netadrtype_t family = NA_UNSPEC;
argc = Cmd_Argc();
if ( argc != 2 && argc != 3 ) {
Com_Printf( "usage: ping [-4|-6] server\n");
return;
}
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
Com_Memset( &to, 0, sizeof( netadr_t ) );
if ( !NET_StringToAdr( server, &to, family ) ) {
return;
}
pingptr = CL_GetFreePing();
memcpy( &pingptr->adr, &to, sizeof( netadr_t ) );
pingptr->start = Sys_Milliseconds();
pingptr->time = 0;
CL_SetServerInfoByAddress( pingptr->adr, NULL, 0 );
NET_OutOfBandPrint( NS_CLIENT, to, "getinfo xxx" );
}
/*
==================
CL_UpdateVisiblePings_f
==================
*/
qboolean CL_UpdateVisiblePings_f( int source ) {
int slots, i;
char buff[MAX_STRING_CHARS];
int pingTime;
int max;
qboolean status = qfalse;
if ( source < 0 || source > AS_FAVORITES ) {
return qfalse;
}
cls.pingUpdateSource = source;
slots = CL_GetPingQueueCount();
if ( slots < MAX_PINGREQUESTS ) {
serverInfo_t *server = NULL;
switch ( source ) {
case AS_LOCAL:
server = &cls.localServers[0];
max = cls.numlocalservers;
break;
case AS_GLOBAL:
server = &cls.globalServers[0];
max = cls.numglobalservers;
break;
case AS_FAVORITES:
server = &cls.favoriteServers[0];
max = cls.numfavoriteservers;
break;
default:
return qfalse;
}
for ( i = 0; i < max; i++ ) {
if ( server[i].visible ) {
if ( server[i].ping == -1 ) {
int j;
if ( slots >= MAX_PINGREQUESTS ) {
break;
}
for ( j = 0; j < MAX_PINGREQUESTS; j++ ) {
if ( !cl_pinglist[j].adr.port ) {
continue;
}
if ( NET_CompareAdr( cl_pinglist[j].adr, server[i].adr ) ) {
// already on the list
break;
}
}
if ( j >= MAX_PINGREQUESTS ) {
status = qtrue;
for ( j = 0; j < MAX_PINGREQUESTS; j++ ) {
if ( !cl_pinglist[j].adr.port ) {
break;
}
}
memcpy( &cl_pinglist[j].adr, &server[i].adr, sizeof( netadr_t ) );
cl_pinglist[j].start = Sys_Milliseconds();
cl_pinglist[j].time = 0;
NET_OutOfBandPrint( NS_CLIENT, cl_pinglist[j].adr, "getinfo xxx" );
slots++;
}
}
// if the server has a ping higher than cl_maxPing or
// the ping packet got lost
else if ( server[i].ping == 0 ) {
// if we are updating global servers
if ( source == AS_GLOBAL ) {
//
if ( cls.numGlobalServerAddresses > 0 ) {
// overwrite this server with one from the additional global servers
cls.numGlobalServerAddresses--;
CL_InitServerInfo( &server[i], &cls.globalServerAddresses[cls.numGlobalServerAddresses] );
// NOTE: the server[i].visible flag stays untouched
}
}
}
}
}
}
if ( slots ) {
status = qtrue;
}
for ( i = 0; i < MAX_PINGREQUESTS; i++ ) {
if ( !cl_pinglist[i].adr.port ) {
continue;
}
CL_GetPing( i, buff, MAX_STRING_CHARS, &pingTime );
if ( pingTime != 0 ) {
CL_ClearPing( i );
status = qtrue;
}
}
return status;
}
/*
==================
CL_UpdateServerInfo
==================
*/
void CL_UpdateServerInfo( int n ) {
if ( !cl_pinglist[n].adr.port ) {
return;
}
CL_SetServerInfoByAddress( cl_pinglist[n].adr, cl_pinglist[n].info, cl_pinglist[n].time );
}
/*
==================
CL_ServerStatus_f
==================
*/
void CL_ServerStatus_f( void ) {
netadr_t to, *toptr = NULL;
char *server;
serverStatus_t *serverStatus;
int argc;
netadrtype_t family = NA_UNSPEC;
argc = Cmd_Argc();
if ( argc != 2 && argc != 3 )
{
if (clc.state != CA_ACTIVE || clc.demoplaying)
{
Com_Printf( "Not connected to a server.\n" );
Com_Printf( "usage: serverstatus [-4|-6] server\n");
return;
}
toptr = &clc.serverAddress;
}
if(!toptr)
{
Com_Memset( &to, 0, sizeof(netadr_t) );
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
toptr = &to;
if ( !NET_StringToAdr( server, toptr, family ) )
return;
}
NET_OutOfBandPrint( NS_CLIENT, *toptr, "getstatus" );
serverStatus = CL_GetServerStatus( *toptr );
serverStatus->address = *toptr;
serverStatus->print = qtrue;
serverStatus->pending = qtrue;
}
/*
==================
CL_ShowIP_f
==================
*/
void CL_ShowIP_f( void ) {
Sys_ShowIP();
}
/*
=================
CL_CDKeyValidate
=================
*/
qboolean CL_CDKeyValidate( const char *key, const char *checksum ) {
#ifdef STANDALONE
return qtrue;
#else
char ch;
byte sum;
char chs[3];
int i, len;
len = strlen( key );
if ( len != CDKEY_LEN ) {
return qfalse;
}
if ( checksum && strlen( checksum ) != CDCHKSUM_LEN ) {
return qfalse;
}
sum = 0;
// for loop gets rid of conditional assignment warning
for ( i = 0; i < len; i++ ) {
ch = *key++;
if ( ch >= 'a' && ch <= 'z' ) {
ch -= 32;
}
switch ( ch ) {
case '2':
case '3':
case '7':
case 'A':
case 'B':
case 'C':
case 'D':
case 'G':
case 'H':
case 'J':
case 'L':
case 'P':
case 'R':
case 'S':
case 'T':
case 'W':
sum = ( sum << 1 ) ^ ch;
continue;
default:
return qfalse;
}
}
sprintf( chs, "%02x", sum );
if ( checksum && !Q_stricmp( chs, checksum ) ) {
return qtrue;
}
if ( !checksum ) {
return qtrue;
}
return qfalse;
#endif
}
// NERVE - SMF
/*
=======================
CL_AddToLimboChat
=======================
*/
void CL_AddToLimboChat( const char *str ) {
int len = 0;
char *p;
int i;
cl.limboChatPos = LIMBOCHAT_HEIGHT - 1;
// copy old strings
for ( i = cl.limboChatPos; i > 0; i-- ) {
strcpy( cl.limboChatMsgs[i], cl.limboChatMsgs[i - 1] );
}
// copy new string
p = cl.limboChatMsgs[0];
*p = 0;
while ( *str ) {
if ( len > LIMBOCHAT_WIDTH - 1 ) {
break;
}
if ( Q_IsColorString( str ) ) {
*p++ = *str++;
*p++ = *str++;
continue;
}
*p++ = *str++;
len++;
}
*p = 0;
}
/*
=======================
CL_GetLimboString
=======================
*/
qboolean CL_GetLimboString( int index, char *buf ) {
if ( index >= LIMBOCHAT_HEIGHT ) {
return qfalse;
}
strncpy( buf, cl.limboChatMsgs[index], 140 );
return qtrue;
}
// -NERVE - SMF
// NERVE - SMF - Localization code
#define FILE_HASH_SIZE 1024
#define MAX_VA_STRING 32000
#define MAX_TRANS_STRING 4096
typedef struct trans_s {
char original[MAX_TRANS_STRING];
char translated[MAX_LANGUAGES][MAX_TRANS_STRING];
struct trans_s *next;
float x_offset;
float y_offset;
qboolean fromFile;
} trans_t;
static trans_t* transTable[FILE_HASH_SIZE];
/*
=======================
AllocTrans
=======================
*/
static trans_t* AllocTrans( char *original, char *translated[MAX_LANGUAGES] ) {
trans_t *t;
int i;
t = malloc( sizeof( trans_t ) );
memset( t, 0, sizeof( trans_t ) );
if ( original ) {
strncpy( t->original, original, MAX_TRANS_STRING );
}
if ( translated ) {
for ( i = 0; i < MAX_LANGUAGES; i++ )
strncpy( t->translated[i], translated[i], MAX_TRANS_STRING );
}
return t;
}
/*
=======================
generateHashValue
=======================
*/
static long generateHashValue( const char *fname ) {
int i;
long hash;
char letter;
hash = 0;
i = 0;
while ( fname[i] != '\0' ) {
letter = tolower( fname[i] );
hash += (long)( letter ) * ( i + 119 );
i++;
}
hash &= ( FILE_HASH_SIZE - 1 );
return hash;
}
/*
=======================
LookupTrans
=======================
*/
static trans_t* LookupTrans( char *original, char *translated[MAX_LANGUAGES], qboolean isLoading ) {
trans_t *t, *newt, *prev = NULL;
long hash;
hash = generateHashValue( original );
for ( t = transTable[hash]; t; prev = t, t = t->next ) {
if ( !Q_stricmp( original, t->original ) ) {
if ( isLoading ) {
Com_DPrintf( S_COLOR_YELLOW "WARNING: Duplicate string found: \"%s\"\n", original );
}
return t;
}
}
newt = AllocTrans( original, translated );
if ( prev ) {
prev->next = newt;
} else {
transTable[hash] = newt;
}
if ( cl_debugTranslation->integer >= 1 && !isLoading ) {
Com_Printf( "Missing translation: \'%s\'\n", original );
}
// see if we want to save out the translation table everytime a string is added
// if ( cl_debugTranslation->integer == 2 && !isLoading ) {
// CL_SaveTransTable();
// }
return newt;
}
/*
=======================
CL_SaveTransTable
=======================
*/
void CL_SaveTransTable( const char *fileName, qboolean newOnly ) {
int bucketlen, bucketnum, maxbucketlen, avebucketlen;
int untransnum, transnum;
const char *buf;
fileHandle_t f;
trans_t *t;
int i, j, len;
if ( cl.corruptedTranslationFile ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Cannot save corrupted translation file. Please reload first." );
return;
}
FS_FOpenFileByMode( fileName, &f, FS_WRITE );
bucketnum = 0;
maxbucketlen = 0;
avebucketlen = 0;
transnum = 0;
untransnum = 0;
// write out version, if one
if ( strlen( cl.translationVersion ) ) {
buf = va( "#version\t\t\"%s\"\n", cl.translationVersion );
} else {
buf = va( "#version\t\t\"1.0 01/01/01\"\n" );
}
len = strlen( buf );
FS_Write( buf, len, f );
// write out translated strings
for ( j = 0; j < 2; j++ ) {
for ( i = 0; i < FILE_HASH_SIZE; i++ ) {
t = transTable[i];
if ( !t || ( newOnly && t->fromFile ) ) {
continue;
}
bucketlen = 0;
for ( ; t; t = t->next ) {
bucketlen++;
if ( strlen( t->translated[0] ) ) {
if ( j ) {
continue;
}
transnum++;
} else {
if ( !j ) {
continue;
}
untransnum++;
}
buf = va( "{\n\tenglish\t\t\"%s\"\n", t->original );
len = strlen( buf );
FS_Write( buf, len, f );
buf = va( "\tfrench\t\t\"%s\"\n", t->translated[LANGUAGE_FRENCH] );
len = strlen( buf );
FS_Write( buf, len, f );
buf = va( "\tgerman\t\t\"%s\"\n", t->translated[LANGUAGE_GERMAN] );
len = strlen( buf );
FS_Write( buf, len, f );
buf = va( "\titalian\t\t\"%s\"\n", t->translated[LANGUAGE_ITALIAN] );
len = strlen( buf );
FS_Write( buf, len, f );
buf = va( "\tspanish\t\t\"%s\"\n", t->translated[LANGUAGE_SPANISH] );
len = strlen( buf );
FS_Write( buf, len, f );
buf = va( "}\n" );
len = strlen( buf );
FS_Write( buf, len, f );
}
if ( bucketlen > maxbucketlen ) {
maxbucketlen = bucketlen;
}
if ( bucketlen ) {
bucketnum++;
avebucketlen += bucketlen;
}
}
}
Com_Printf( "Saved translation table.\nTotal = %i, Translated = %i, Untranslated = %i, aveblen = %2.2f, maxblen = %i\n",
transnum + untransnum, transnum, untransnum, (float)avebucketlen / bucketnum, maxbucketlen );
FS_FCloseFile( f );
}
/*
=======================
CL_CheckTranslationString
NERVE - SMF - compare formatting characters
=======================
*/
qboolean CL_CheckTranslationString( char *original, char *translated ) {
char format_org[128], format_trans[128];
int len, i;
memset( format_org, 0, 128 );
memset( format_trans, 0, 128 );
// generate formatting string for original
len = strlen( original );
for ( i = 0; i < len; i++ ) {
if ( original[i] != '%' ) {
continue;
}
strcat( format_org, va( "%c%c ", '%', original[i + 1] ) );
}
// generate formatting string for translated
len = strlen( translated );
if ( !len ) {
return qtrue;
}
for ( i = 0; i < len; i++ ) {
if ( translated[i] != '%' ) {
continue;
}
strcat( format_trans, va( "%c%c ", '%', translated[i + 1] ) );
}
// compare
len = strlen( format_org );
if ( len != strlen( format_trans ) ) {
return qfalse;
}
for ( i = 0; i < len; i++ ) {
if ( format_org[i] != format_trans[i] ) {
return qfalse;
}
}
return qtrue;
}
/*
=======================
CL_LoadTransTable
=======================
*/
void CL_LoadTransTable( const char *fileName ) {
char translated[MAX_LANGUAGES][MAX_VA_STRING];
char original[MAX_VA_STRING];
qboolean aborted;
char *text;
fileHandle_t f;
char *text_p;
char *token;
int len, i;
trans_t *t;
int count;
count = 0;
aborted = qfalse;
cl.corruptedTranslationFile = qfalse;
len = FS_FOpenFileByMode( fileName, &f, FS_READ );
if ( len <= 0 ) {
return;
}
text = malloc( len + 1 );
if ( !text ) {
return;
}
FS_Read( text, len, f );
text[len] = 0;
FS_FCloseFile( f );
// parse the text
text_p = text;
do {
token = COM_Parse( &text_p );
if ( Q_stricmp( "{", token ) ) {
// parse version number
if ( !Q_stricmp( "#version", token ) ) {
token = COM_Parse( &text_p );
strcpy( cl.translationVersion, token );
continue;
}
break;
}
// english
token = COM_Parse( &text_p );
if ( Q_stricmp( "english", token ) ) {
aborted = qtrue;
break;
}
token = COM_Parse( &text_p );
strcpy( original, token );
if ( cl_debugTranslation->integer == 3 ) {
Com_Printf( "%i Loading: \"%s\"\n", count, original );
}
// french
token = COM_Parse( &text_p );
if ( Q_stricmp( "french", token ) ) {
aborted = qtrue;
break;
}
token = COM_Parse( &text_p );
strcpy( translated[LANGUAGE_FRENCH], token );
if ( !CL_CheckTranslationString( original, translated[LANGUAGE_FRENCH] ) ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Translation formatting doesn't match up with English version!\n" );
aborted = qtrue;
break;
}
// german
token = COM_Parse( &text_p );
if ( Q_stricmp( "german", token ) ) {
aborted = qtrue;
break;
}
token = COM_Parse( &text_p );
strcpy( translated[LANGUAGE_GERMAN], token );
if ( !CL_CheckTranslationString( original, translated[LANGUAGE_GERMAN] ) ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Translation formatting doesn't match up with English version!\n" );
aborted = qtrue;
break;
}
// italian
token = COM_Parse( &text_p );
if ( Q_stricmp( "italian", token ) ) {
aborted = qtrue;
break;
}
token = COM_Parse( &text_p );
strcpy( translated[LANGUAGE_ITALIAN], token );
if ( !CL_CheckTranslationString( original, translated[LANGUAGE_ITALIAN] ) ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Translation formatting doesn't match up with English version!\n" );
aborted = qtrue;
break;
}
// spanish
token = COM_Parse( &text_p );
if ( Q_stricmp( "spanish", token ) ) {
aborted = qtrue;
break;
}
token = COM_Parse( &text_p );
strcpy( translated[LANGUAGE_SPANISH], token );
if ( !CL_CheckTranslationString( original, translated[LANGUAGE_SPANISH] ) ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Translation formatting doesn't match up with English version!\n" );
aborted = qtrue;
break;
}
// do lookup
t = LookupTrans( original, NULL, qtrue );
if ( t ) {
t->fromFile = qtrue;
for ( i = 0; i < MAX_LANGUAGES; i++ )
strncpy( t->translated[i], translated[i], MAX_TRANS_STRING );
}
token = COM_Parse( &text_p );
// set offset if we have one
if ( !Q_stricmp( "offset", token ) ) {
if ( t )
{
token = COM_Parse( &text_p );
t->x_offset = atof( token );
token = COM_Parse( &text_p );
t->y_offset = atof( token );
token = COM_Parse( &text_p );
}
}
if ( Q_stricmp( "}", token ) ) {
aborted = qtrue;
break;
}
count++;
} while ( token );
if ( aborted ) {
int i, line = 1;
for ( i = 0; i < len && ( text + i ) < text_p; i++ ) {
if ( text[i] == '\n' ) {
line++;
}
}
Com_Printf( S_COLOR_YELLOW "WARNING: Problem loading %s on line %i\n", fileName, line );
cl.corruptedTranslationFile = qtrue;
} else {
Com_Printf( "Loaded %i translation strings from %s\n", count, fileName );
}
// cleanup
free( text );
}
/*
=======================
CL_ReloadTranslation
=======================
*/
void CL_ReloadTranslation( void ) {
char **fileList;
int numFiles, i;
char fileName[MAX_QPATH];
for ( i = 0; i < FILE_HASH_SIZE; i++ ) {
if ( transTable[i] ) {
free( transTable[i] );
}
}
memset( transTable, 0, sizeof( trans_t* ) * FILE_HASH_SIZE );
CL_LoadTransTable( "scripts/translation.cfg" );
fileList = FS_ListFiles( "translations", ".cfg", &numFiles );
for ( i = 0; i < numFiles; i++ ) {
Com_sprintf( fileName, sizeof (fileName), "translations/%s", fileList[i] );
CL_LoadTransTable( fileName );
}
}
/*
=======================
CL_InitTranslation
=======================
*/
void CL_InitTranslation( void ) {
char **fileList;
int numFiles, i;
char fileName[MAX_QPATH];
memset( transTable, 0, sizeof( trans_t* ) * FILE_HASH_SIZE );
CL_LoadTransTable( "scripts/translation.cfg" );
fileList = FS_ListFiles( "translations", ".cfg", &numFiles );
for ( i = 0; i < numFiles; i++ ) {
Com_sprintf( fileName, sizeof (fileName), "translations/%s", fileList[i] );
CL_LoadTransTable( fileName );
}
}
/*
=======================
CL_TranslateString
=======================
*/
void CL_TranslateString( const char *string, char *dest_buffer ) {
int i, count, currentLanguage;
trans_t *t;
qboolean newline = qfalse;
char *buf;
buf = dest_buffer;
currentLanguage = cl_language->integer - 1;
// early bail if we only want english or bad language type
if ( !string ) {
strcpy( buf, "(null)" );
return;
} else if ( currentLanguage == -1 || currentLanguage >= MAX_LANGUAGES || !strlen( string ) ) {
strcpy( buf, string );
return;
}
// ignore newlines
if ( string[strlen( string ) - 1] == '\n' ) {
newline = qtrue;
}
for ( i = 0, count = 0; string[i] != '\0'; i++ ) {
if ( string[i] != '\n' ) {
buf[count++] = string[i];
}
}
buf[count] = '\0';
t = LookupTrans( buf, NULL, qfalse );
if ( t && strlen( t->translated[currentLanguage] ) ) {
int offset = 0;
if ( cl_debugTranslation->integer >= 1 ) {
buf[0] = '^';
buf[1] = '1';
buf[2] = '[';
offset = 3;
}
strcpy( buf + offset, t->translated[currentLanguage] );
if ( cl_debugTranslation->integer >= 1 ) {
int len2 = strlen( buf );
buf[len2] = ']';
buf[len2 + 1] = '^';
buf[len2 + 2] = '7';
buf[len2 + 3] = '\0';
}
if ( newline ) {
int len2 = strlen( buf );
buf[len2] = '\n';
buf[len2 + 1] = '\0';
}
} else {
int offset = 0;
if ( cl_debugTranslation->integer >= 1 ) {
buf[0] = '^';
buf[1] = '1';
buf[2] = '[';
offset = 3;
}
strcpy( buf + offset, string );
if ( cl_debugTranslation->integer >= 1 ) {
int len2 = strlen( buf );
qboolean addnewline = qfalse;
if ( buf[len2 - 1] == '\n' ) {
len2--;
addnewline = qtrue;
}
buf[len2] = ']';
buf[len2 + 1] = '^';
buf[len2 + 2] = '7';
buf[len2 + 3] = '\0';
if ( addnewline ) {
buf[len2 + 3] = '\n';
buf[len2 + 4] = '\0';
}
}
}
}
/*
=======================
CL_TranslateStringBuf
TTimo - handy, stores in a static buf, converts \n to chr(13)
=======================
*/
const char* CL_TranslateStringBuf( const char *string ) {
char *p;
int i,l;
static char buf[MAX_VA_STRING];
CL_TranslateString( string, buf );
while ( ( p = strstr( buf, "\\n" ) ) )
{
*p = '\n';
p++;
// Com_Memcpy(p, p+1, strlen(p) ); b0rks on win32
l = strlen( p );
for ( i = 0; i < l; i++ )
{
*p = *( p + 1 );
p++;
}
}
return buf;
}
/*
=======================
CL_OpenURLForCvar
=======================
*/
void CL_OpenURL( const char *url ) {
if ( !url || !strlen( url ) ) {
Com_Printf( "%s", CL_TranslateStringBuf( "invalid/empty URL\n" ) );
return;
}
Sys_OpenURL( url, qtrue );
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3233_0 |
crossvul-cpp_data_bad_4227_0 |
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-features.h>
#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/agent/net-snmp-agent-includes.h>
#include <net-snmp/agent/watcher.h>
#include <net-snmp/agent/agent_callbacks.h>
#include "agent/extend.h"
#include "utilities/execute.h"
#include "struct.h"
#ifndef USING_UCD_SNMP_EXTENSIBLE_MODULE
#include "util_funcs/header_simple_table.h"
#include "mibdefs.h"
#define SHELLCOMMAND 3
#endif
netsnmp_feature_require(extract_table_row_data);
netsnmp_feature_require(table_data_delete_table);
#ifndef NETSNMP_NO_WRITE_SUPPORT
netsnmp_feature_require(insert_table_row);
#endif /* NETSNMP_NO_WRITE_SUPPORT */
oid ns_extend_oid[] = { 1, 3, 6, 1, 4, 1, 8072, 1, 3, 2 };
typedef struct extend_registration_block_s {
netsnmp_table_data *dinfo;
oid *root_oid;
size_t oid_len;
long num_entries;
netsnmp_extend *ehead;
netsnmp_handler_registration *reg[4];
struct extend_registration_block_s *next;
} extend_registration_block;
extend_registration_block *ereg_head = NULL;
#ifndef USING_UCD_SNMP_EXTENSIBLE_MODULE
typedef struct netsnmp_old_extend_s {
unsigned int idx;
netsnmp_extend *exec_entry;
netsnmp_extend *efix_entry;
} netsnmp_old_extend;
unsigned int num_compatability_entries = 0;
unsigned int max_compatability_entries = 50;
netsnmp_old_extend *compatability_entries;
char *cmdlinebuf;
size_t cmdlinesize;
WriteMethod fixExec2Error;
FindVarMethod var_extensible_old;
oid old_extensible_variables_oid[] = { NETSNMP_UCDAVIS_MIB, NETSNMP_SHELLMIBNUM, 1 };
#ifndef NETSNMP_NO_WRITE_SUPPORT
struct variable2 old_extensible_variables[] = {
{MIBINDEX, ASN_INTEGER, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {MIBINDEX}},
{ERRORNAME, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORNAME}},
{SHELLCOMMAND, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {SHELLCOMMAND}},
{ERRORFLAG, ASN_INTEGER, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORFLAG}},
{ERRORMSG, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORMSG}},
{ERRORFIX, ASN_INTEGER, NETSNMP_OLDAPI_RWRITE,
var_extensible_old, 1, {ERRORFIX}},
{ERRORFIXCMD, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORFIXCMD}}
};
#else /* !NETSNMP_NO_WRITE_SUPPORT */
struct variable2 old_extensible_variables[] = {
{MIBINDEX, ASN_INTEGER, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {MIBINDEX}},
{ERRORNAME, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORNAME}},
{SHELLCOMMAND, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {SHELLCOMMAND}},
{ERRORFLAG, ASN_INTEGER, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORFLAG}},
{ERRORMSG, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORMSG}},
{ERRORFIX, ASN_INTEGER, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORFIX}},
{ERRORFIXCMD, ASN_OCTET_STR, NETSNMP_OLDAPI_RONLY,
var_extensible_old, 1, {ERRORFIXCMD}}
};
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
#endif
/*************************
*
* Main initialisation routine
*
*************************/
extend_registration_block *
_find_extension_block( oid *name, size_t name_len )
{
extend_registration_block *eptr;
size_t len;
for ( eptr=ereg_head; eptr; eptr=eptr->next ) {
len = SNMP_MIN(name_len, eptr->oid_len);
if (!snmp_oid_compare( name, len, eptr->root_oid, eptr->oid_len))
return eptr;
}
return NULL;
}
extend_registration_block *
_register_extend( oid *base, size_t len )
{
extend_registration_block *eptr;
oid oid_buf[MAX_OID_LEN];
netsnmp_table_data *dinfo;
netsnmp_table_registration_info *tinfo;
netsnmp_watcher_info *winfo;
netsnmp_handler_registration *reg = NULL;
int rc;
for ( eptr=ereg_head; eptr; eptr=eptr->next ) {
if (!snmp_oid_compare( base, len, eptr->root_oid, eptr->oid_len))
return eptr;
}
if (!eptr) {
eptr = SNMP_MALLOC_TYPEDEF( extend_registration_block );
if (!eptr)
return NULL;
eptr->root_oid = snmp_duplicate_objid( base, len );
eptr->oid_len = len;
eptr->num_entries = 0;
eptr->ehead = NULL;
eptr->dinfo = netsnmp_create_table_data( "nsExtendTable" );
eptr->next = ereg_head;
ereg_head = eptr;
}
dinfo = eptr->dinfo;
memcpy( oid_buf, base, len*sizeof(oid) );
/*
* Register the configuration table
*/
tinfo = SNMP_MALLOC_TYPEDEF( netsnmp_table_registration_info );
netsnmp_table_helper_add_indexes( tinfo, ASN_OCTET_STR, 0 );
tinfo->min_column = COLUMN_EXTCFG_FIRST_COLUMN;
tinfo->max_column = COLUMN_EXTCFG_LAST_COLUMN;
oid_buf[len] = 2;
#ifndef NETSNMP_NO_WRITE_SUPPORT
reg = netsnmp_create_handler_registration(
"nsExtendConfigTable", handle_nsExtendConfigTable,
oid_buf, len+1, HANDLER_CAN_RWRITE);
#else /* !NETSNMP_NO_WRITE_SUPPORT */
reg = netsnmp_create_handler_registration(
"nsExtendConfigTable", handle_nsExtendConfigTable,
oid_buf, len+1, HANDLER_CAN_RONLY);
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
rc = netsnmp_register_table_data( reg, dinfo, tinfo );
if (rc != SNMPERR_SUCCESS) {
goto bail;
}
netsnmp_handler_owns_table_info(reg->handler->next);
eptr->reg[0] = reg;
/*
* Register the main output table
* using the same table_data handle.
* This is sufficient to link the two tables,
* and implement the AUGMENTS behaviour
*/
tinfo = SNMP_MALLOC_TYPEDEF( netsnmp_table_registration_info );
netsnmp_table_helper_add_indexes( tinfo, ASN_OCTET_STR, 0 );
tinfo->min_column = COLUMN_EXTOUT1_FIRST_COLUMN;
tinfo->max_column = COLUMN_EXTOUT1_LAST_COLUMN;
oid_buf[len] = 3;
reg = netsnmp_create_handler_registration(
"nsExtendOut1Table", handle_nsExtendOutput1Table,
oid_buf, len+1, HANDLER_CAN_RONLY);
rc = netsnmp_register_table_data( reg, dinfo, tinfo );
if (rc != SNMPERR_SUCCESS)
goto bail;
netsnmp_handler_owns_table_info(reg->handler->next);
eptr->reg[1] = reg;
/*
* Register the multi-line output table
* using a simple table helper.
* This handles extracting the indexes from
* the request OID, but leaves most of
* the work to our handler routine.
* Still, it was nice while it lasted...
*/
tinfo = SNMP_MALLOC_TYPEDEF( netsnmp_table_registration_info );
netsnmp_table_helper_add_indexes( tinfo, ASN_OCTET_STR, ASN_INTEGER, 0 );
tinfo->min_column = COLUMN_EXTOUT2_FIRST_COLUMN;
tinfo->max_column = COLUMN_EXTOUT2_LAST_COLUMN;
oid_buf[len] = 4;
reg = netsnmp_create_handler_registration(
"nsExtendOut2Table", handle_nsExtendOutput2Table,
oid_buf, len+1, HANDLER_CAN_RONLY);
rc = netsnmp_register_table( reg, tinfo );
if (rc != SNMPERR_SUCCESS)
goto bail;
netsnmp_handler_owns_table_info(reg->handler->next);
eptr->reg[2] = reg;
/*
* Register a watched scalar to keep track of the number of entries
*/
oid_buf[len] = 1;
reg = netsnmp_create_handler_registration(
"nsExtendNumEntries", NULL,
oid_buf, len+1, HANDLER_CAN_RONLY);
winfo = netsnmp_create_watcher_info(
&(eptr->num_entries), sizeof(eptr->num_entries),
ASN_INTEGER, WATCHER_FIXED_SIZE);
rc = netsnmp_register_watched_scalar2( reg, winfo );
if (rc != SNMPERR_SUCCESS)
goto bail;
eptr->reg[3] = reg;
return eptr;
bail:
if (eptr->reg[3])
netsnmp_unregister_handler(eptr->reg[3]);
if (eptr->reg[2])
netsnmp_unregister_handler(eptr->reg[2]);
if (eptr->reg[1])
netsnmp_unregister_handler(eptr->reg[1]);
if (eptr->reg[0])
netsnmp_unregister_handler(eptr->reg[0]);
return NULL;
}
static void
_unregister_extend(extend_registration_block *eptr)
{
extend_registration_block *prev;
netsnmp_assert(eptr);
for (prev = ereg_head; prev && prev->next != eptr; prev = prev->next)
;
if (prev) {
netsnmp_assert(eptr == prev->next);
prev->next = eptr->next;
} else {
netsnmp_assert(eptr == ereg_head);
ereg_head = eptr->next;
}
netsnmp_table_data_delete_table(eptr->dinfo);
free(eptr->root_oid);
free(eptr);
}
int
extend_clear_callback(int majorID, int minorID,
void *serverarg, void *clientarg)
{
extend_registration_block *eptr, *enext = NULL;
for ( eptr=ereg_head; eptr; eptr=enext ) {
enext=eptr->next;
netsnmp_unregister_handler( eptr->reg[0] );
netsnmp_unregister_handler( eptr->reg[1] );
netsnmp_unregister_handler( eptr->reg[2] );
netsnmp_unregister_handler( eptr->reg[3] );
SNMP_FREE(eptr);
}
ereg_head = NULL;
return 0;
}
void init_extend( void )
{
snmpd_register_config_handler("extend", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("extend-sh", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("extendfix", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("exec2", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("sh2", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("execFix2", extend_parse_config, NULL, NULL);
(void)_register_extend( ns_extend_oid, OID_LENGTH(ns_extend_oid));
#ifndef USING_UCD_SNMP_EXTENSIBLE_MODULE
snmpd_register_config_handler("exec", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("sh", extend_parse_config, NULL, NULL);
snmpd_register_config_handler("execFix", extend_parse_config, NULL, NULL);
compatability_entries = (netsnmp_old_extend *)
calloc( max_compatability_entries, sizeof(netsnmp_old_extend));
REGISTER_MIB("ucd-extensible", old_extensible_variables,
variable2, old_extensible_variables_oid);
#endif
snmp_register_callback(SNMP_CALLBACK_APPLICATION,
SNMPD_CALLBACK_PRE_UPDATE_CONFIG,
extend_clear_callback, NULL);
}
void
shutdown_extend(void)
{
#ifndef USING_UCD_SNMP_EXTENSIBLE_MODULE
free(compatability_entries);
compatability_entries = NULL;
#endif
while (ereg_head)
_unregister_extend(ereg_head);
}
/*************************
*
* Cached-data hooks
* see 'cache_handler' helper
*
*************************/
int
extend_load_cache(netsnmp_cache *cache, void *magic)
{
#ifndef USING_UTILITIES_EXECUTE_MODULE
NETSNMP_LOGONCE((LOG_WARNING,"support for run_exec_command not available\n"));
return -1;
#else
int out_len = 1024*100;
char out_buf[ 1024*100 ];
int cmd_len = 255*2 + 2; /* 2 * DisplayStrings */
char cmd_buf[ 255*2 + 2 ];
int ret;
char *cp;
char *line_buf[ 1024 ];
netsnmp_extend *extension = (netsnmp_extend *)magic;
if (!magic)
return -1;
DEBUGMSGTL(( "nsExtendTable:cache", "load %s", extension->token ));
if ( extension->args )
snprintf( cmd_buf, cmd_len, "%s %s", extension->command, extension->args );
else
snprintf( cmd_buf, cmd_len, "%s", extension->command );
if ( extension->flags & NS_EXTEND_FLAGS_SHELL )
ret = run_shell_command( cmd_buf, extension->input, out_buf, &out_len);
else
ret = run_exec_command( cmd_buf, extension->input, out_buf, &out_len);
DEBUGMSG(( "nsExtendTable:cache", ": %s : %d\n", cmd_buf, ret));
if (ret >= 0) {
if (out_buf[ out_len-1 ] == '\n')
out_buf[ --out_len ] = '\0'; /* Stomp on trailing newline */
extension->output = strdup( out_buf );
extension->out_len = out_len;
/*
* Now we need to pick the output apart into separate lines.
* Start by counting how many lines we've got, and keeping
* track of where each line starts in a static buffer
*/
extension->numlines = 1;
line_buf[ 0 ] = extension->output;
for (cp=extension->output; *cp; cp++) {
if (*cp == '\n') {
line_buf[ extension->numlines++ ] = cp+1;
}
}
if ( extension->numlines > 1 ) {
extension->lines = (char**)calloc( sizeof(char *), extension->numlines );
memcpy( extension->lines, line_buf,
sizeof(char *) * extension->numlines );
} else {
extension->lines = &extension->output;
}
}
extension->result = ret;
return ret;
#endif /* !defined(USING_UTILITIES_EXECUTE_MODULE) */
}
void
extend_free_cache(netsnmp_cache *cache, void *magic)
{
netsnmp_extend *extension = (netsnmp_extend *)magic;
if (!magic)
return;
DEBUGMSGTL(( "nsExtendTable:cache", "free %s\n", extension->token ));
if (extension->output) {
SNMP_FREE(extension->output);
extension->output = NULL;
}
if ( extension->numlines > 1 ) {
SNMP_FREE(extension->lines);
}
extension->lines = NULL;
extension->out_len = 0;
extension->numlines = 0;
}
/*************************
*
* Utility routines for setting up a new entry
* (either via SET requests, or the config file)
*
*************************/
void
_free_extension( netsnmp_extend *extension, extend_registration_block *ereg )
{
netsnmp_extend *eptr = NULL;
netsnmp_extend *eprev = NULL;
if (!extension)
return;
if (ereg) {
/* Unlink from 'ehead' list */
for (eptr=ereg->ehead; eptr; eptr=eptr->next) {
if (eptr == extension)
break;
eprev = eptr;
}
if (!eptr) {
snmp_log(LOG_ERR,
"extend: fell off end of list before finding extension\n");
return;
}
if (eprev)
eprev->next = eptr->next;
else
ereg->ehead = eptr->next;
netsnmp_table_data_remove_and_delete_row( ereg->dinfo, extension->row);
}
SNMP_FREE( extension->token );
SNMP_FREE( extension->cache );
SNMP_FREE( extension->command );
SNMP_FREE( extension->args );
SNMP_FREE( extension->input );
SNMP_FREE( extension );
return;
}
netsnmp_extend *
_new_extension( char *exec_name, int exec_flags, extend_registration_block *ereg )
{
netsnmp_extend *extension;
netsnmp_table_row *row;
netsnmp_extend *eptr1, *eptr2;
netsnmp_table_data *dinfo = ereg->dinfo;
if (!exec_name)
return NULL;
extension = SNMP_MALLOC_TYPEDEF( netsnmp_extend );
if (!extension)
return NULL;
extension->token = strdup( exec_name );
extension->flags = exec_flags;
extension->cache = netsnmp_cache_create( 0, extend_load_cache,
extend_free_cache, NULL, 0 );
if (extension->cache)
extension->cache->magic = extension;
row = netsnmp_create_table_data_row();
if (!row || !extension->cache) {
_free_extension( extension, ereg );
SNMP_FREE( row );
return NULL;
}
row->data = (void *)extension;
extension->row = row;
netsnmp_table_row_add_index( row, ASN_OCTET_STR,
exec_name, strlen(exec_name));
if ( netsnmp_table_data_add_row( dinfo, row) != SNMPERR_SUCCESS ) {
/* _free_extension( extension, ereg ); */
SNMP_FREE( extension ); /* Probably not sufficient */
SNMP_FREE( row );
return NULL;
}
ereg->num_entries++;
/*
* Now add this structure to a private linked list.
* We don't need this for the main tables - the
* 'table_data' helper will take care of those.
* But it's probably easier to handle the multi-line
* output table ourselves, for which we need access
* to the underlying data.
* So we'll keep a list internally as well.
*/
for ( eptr1 = ereg->ehead, eptr2 = NULL;
eptr1;
eptr2 = eptr1, eptr1 = eptr1->next ) {
if (strlen( eptr1->token ) > strlen( exec_name ))
break;
if (strlen( eptr1->token ) == strlen( exec_name ) &&
strcmp( eptr1->token, exec_name ) > 0 )
break;
}
if ( eptr2 )
eptr2->next = extension;
else
ereg->ehead = extension;
extension->next = eptr1;
return extension;
}
void
extend_parse_config(const char *token, char *cptr)
{
netsnmp_extend *extension;
char exec_name[STRMAX];
char exec_name2[STRMAX]; /* For use with UCD execFix directive */
char exec_command[STRMAX];
oid oid_buf[MAX_OID_LEN];
size_t oid_len;
extend_registration_block *eptr;
int flags;
int cache_timeout = 0;
int exec_type = NS_EXTEND_ETYPE_EXEC;
cptr = copy_nword(cptr, exec_name, sizeof(exec_name));
if (strcmp(exec_name, "-cacheTime") == 0) {
char cache_timeout_str[32];
cptr = copy_nword(cptr, cache_timeout_str, sizeof(cache_timeout_str));
/* If atoi can't do the conversion, it returns 0 */
cache_timeout = atoi(cache_timeout_str);
cptr = copy_nword(cptr, exec_name, sizeof(exec_name));
}
if (strcmp(exec_name, "-execType") == 0) {
char exec_type_str[16];
cptr = copy_nword(cptr, exec_type_str, sizeof(exec_type_str));
if (strcmp(exec_type_str, "sh") == 0)
exec_type = NS_EXTEND_ETYPE_SHELL;
else
exec_type = NS_EXTEND_ETYPE_EXEC;
cptr = copy_nword(cptr, exec_name, sizeof(exec_name));
}
if ( *exec_name == '.' ) {
oid_len = MAX_OID_LEN - 2;
if (0 == read_objid( exec_name, oid_buf, &oid_len )) {
config_perror("ERROR: Unrecognised OID" );
return;
}
cptr = copy_nword(cptr, exec_name, sizeof(exec_name));
if (!strcmp( token, "sh" ) ||
!strcmp( token, "exec" )) {
config_perror("ERROR: This output format has been deprecated - Please use the 'extend' directive instead" );
return;
}
} else {
memcpy( oid_buf, ns_extend_oid, sizeof(ns_extend_oid));
oid_len = OID_LENGTH(ns_extend_oid);
}
cptr = copy_nword(cptr, exec_command, sizeof(exec_command));
/* XXX - check 'exec_command' exists & is executable */
flags = (NS_EXTEND_FLAGS_ACTIVE | NS_EXTEND_FLAGS_CONFIG);
if (!strcmp( token, "sh" ) ||
!strcmp( token, "extend-sh" ) ||
!strcmp( token, "sh2") ||
exec_type == NS_EXTEND_ETYPE_SHELL)
flags |= NS_EXTEND_FLAGS_SHELL;
if (!strcmp( token, "execFix" ) ||
!strcmp( token, "extendfix" ) ||
!strcmp( token, "execFix2" )) {
strcpy( exec_name2, exec_name );
strcat( exec_name, "Fix" );
flags |= NS_EXTEND_FLAGS_WRITEABLE;
/* XXX - Check for shell... */
}
eptr = _register_extend( oid_buf, oid_len );
if (!eptr) {
snmp_log(LOG_ERR, "Failed to register extend entry '%s' - possibly duplicate name.\n", exec_name );
return;
}
extension = _new_extension( exec_name, flags, eptr );
if (extension) {
extension->command = strdup( exec_command );
if (cptr)
extension->args = strdup( cptr );
if (cache_timeout != 0)
extension->cache->timeout = cache_timeout;
} else {
snmp_log(LOG_ERR, "Failed to register extend entry '%s' - possibly duplicate name.\n", exec_name );
return;
}
#ifndef USING_UCD_SNMP_EXTENSIBLE_MODULE
/*
* Compatability with the UCD extTable
*/
if (!strcmp( token, "execFix" )) {
int i;
for ( i=0; i < num_compatability_entries; i++ ) {
if (!strcmp( exec_name2,
compatability_entries[i].exec_entry->token))
break;
}
if ( i == num_compatability_entries )
config_perror("No matching exec entry" );
else
compatability_entries[ i ].efix_entry = extension;
} else if (!strcmp( token, "sh" ) ||
!strcmp( token, "exec" )) {
if ( num_compatability_entries == max_compatability_entries ) {
/* XXX - should really use dynamic allocation */
netsnmp_old_extend *new_compatability_entries;
new_compatability_entries = realloc(compatability_entries,
max_compatability_entries*2*sizeof(netsnmp_old_extend));
if (!new_compatability_entries)
config_perror("No further UCD-compatible entries" );
else {
memset(new_compatability_entries+num_compatability_entries, 0,
sizeof(netsnmp_old_extend)*max_compatability_entries);
max_compatability_entries *= 2;
compatability_entries = new_compatability_entries;
}
}
if (num_compatability_entries != max_compatability_entries)
compatability_entries[
num_compatability_entries++ ].exec_entry = extension;
}
#endif
}
/*************************
*
* Main table handlers
* Most of the work is handled
* by the 'table_data' helper.
*
*************************/
int
handle_nsExtendConfigTable(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
{
netsnmp_request_info *request;
netsnmp_table_request_info *table_info;
netsnmp_extend *extension;
extend_registration_block *eptr;
int i;
int need_to_validate = 0;
for ( request=requests; request; request=request->next ) {
if (request->processed)
continue;
table_info = netsnmp_extract_table_info( request );
extension = (netsnmp_extend*)netsnmp_extract_table_row_data( request );
DEBUGMSGTL(( "nsExtendTable:config", "varbind: "));
DEBUGMSGOID(("nsExtendTable:config", request->requestvb->name,
request->requestvb->name_length));
DEBUGMSG(( "nsExtendTable:config", " (%s)\n",
se_find_label_in_slist("agent_mode", reqinfo->mode)));
switch (reqinfo->mode) {
case MODE_GET:
switch (table_info->colnum) {
case COLUMN_EXTCFG_COMMAND:
snmp_set_var_typed_value(
request->requestvb, ASN_OCTET_STR,
extension->command,
(extension->command)?strlen(extension->command):0);
break;
case COLUMN_EXTCFG_ARGS:
snmp_set_var_typed_value(
request->requestvb, ASN_OCTET_STR,
extension->args,
(extension->args)?strlen(extension->args):0);
break;
case COLUMN_EXTCFG_INPUT:
snmp_set_var_typed_value(
request->requestvb, ASN_OCTET_STR,
extension->input,
(extension->input)?strlen(extension->input):0);
break;
case COLUMN_EXTCFG_CACHETIME:
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&extension->cache->timeout, sizeof(int));
break;
case COLUMN_EXTCFG_EXECTYPE:
i = ((extension->flags & NS_EXTEND_FLAGS_SHELL) ?
NS_EXTEND_ETYPE_SHELL :
NS_EXTEND_ETYPE_EXEC);
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&i, sizeof(i));
break;
case COLUMN_EXTCFG_RUNTYPE:
i = ((extension->flags & NS_EXTEND_FLAGS_WRITEABLE) ?
NS_EXTEND_RTYPE_RWRITE :
NS_EXTEND_RTYPE_RONLY);
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&i, sizeof(i));
break;
case COLUMN_EXTCFG_STORAGE:
i = ((extension->flags & NS_EXTEND_FLAGS_CONFIG) ?
ST_PERMANENT : ST_VOLATILE);
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&i, sizeof(i));
break;
case COLUMN_EXTCFG_STATUS:
i = ((extension->flags & NS_EXTEND_FLAGS_ACTIVE) ?
RS_ACTIVE :
RS_NOTINSERVICE);
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&i, sizeof(i));
break;
default:
netsnmp_set_request_error(reqinfo, request, SNMP_NOSUCHOBJECT);
continue;
}
break;
/**********
*
* Start of SET handling
*
* All config objects are potentially writable except
* nsExtendStorage which is fixed as either 'permanent'
* (if read from a config file) or 'volatile' (if set via SNMP)
* The string-based settings of a 'permanent' entry cannot
* be changed - neither can the execution or run type.
* Such entries can be (temporarily) marked as inactive,
* and the cache timeout adjusted, but these changes are
* not persistent.
*
**********/
#ifndef NETSNMP_NO_WRITE_SUPPORT
case MODE_SET_RESERVE1:
/*
* Validate the new assignments
*/
switch (table_info->colnum) {
case COLUMN_EXTCFG_COMMAND:
if (request->requestvb->type != ASN_OCTET_STR) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGTYPE);
return SNMP_ERR_WRONGTYPE;
}
/*
* Must have a full path to the command
* XXX - Assumes Unix-style paths
*/
if (request->requestvb->val_len == 0 ||
request->requestvb->val.string[0] != '/') {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGVALUE);
return SNMP_ERR_WRONGVALUE;
}
/*
* XXX - need to check this file exists
* (and is executable)
*/
if (extension && extension->flags & NS_EXTEND_FLAGS_CONFIG) {
/*
* config entries are "permanent" so can't be changed
*/
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_NOTWRITABLE);
return SNMP_ERR_NOTWRITABLE;
}
break;
case COLUMN_EXTCFG_ARGS:
case COLUMN_EXTCFG_INPUT:
if (request->requestvb->type != ASN_OCTET_STR) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGTYPE);
return SNMP_ERR_WRONGTYPE;
}
if (extension && extension->flags & NS_EXTEND_FLAGS_CONFIG) {
/*
* config entries are "permanent" so can't be changed
*/
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_NOTWRITABLE);
return SNMP_ERR_NOTWRITABLE;
}
break;
case COLUMN_EXTCFG_CACHETIME:
if (request->requestvb->type != ASN_INTEGER) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGTYPE);
return SNMP_ERR_WRONGTYPE;
}
i = *request->requestvb->val.integer;
/*
* -1 is a special value indicating "don't cache"
* [[ XXX - should this be 0 ?? ]]
* Otherwise, cache times must be non-negative
*/
if (i < -1 ) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGVALUE);
return SNMP_ERR_WRONGVALUE;
}
break;
case COLUMN_EXTCFG_EXECTYPE:
if (request->requestvb->type != ASN_INTEGER) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGTYPE);
return SNMP_ERR_WRONGTYPE;
}
i = *request->requestvb->val.integer;
if (i<1 || i>2) { /* 'exec(1)' or 'shell(2)' only */
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGVALUE);
return SNMP_ERR_WRONGVALUE;
}
if (extension && extension->flags & NS_EXTEND_FLAGS_CONFIG) {
/*
* config entries are "permanent" so can't be changed
*/
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_NOTWRITABLE);
return SNMP_ERR_NOTWRITABLE;
}
break;
case COLUMN_EXTCFG_RUNTYPE:
if (request->requestvb->type != ASN_INTEGER) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGTYPE);
return SNMP_ERR_WRONGTYPE;
}
/*
* 'run-on-read(1)', 'run-on-set(2)'
* or 'run-command(3)' only
*/
i = *request->requestvb->val.integer;
if (i<1 || i>3) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGVALUE);
return SNMP_ERR_WRONGVALUE;
}
/*
* 'run-command(3)' can only be used with
* a pre-existing 'run-on-set(2)' entry.
*/
if (i==3 && !(extension && (extension->flags & NS_EXTEND_FLAGS_WRITEABLE))) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_INCONSISTENTVALUE);
return SNMP_ERR_INCONSISTENTVALUE;
}
/*
* 'run-command(3)' is the only valid assignment
* for permanent (i.e. config) entries
*/
if ((extension && extension->flags & NS_EXTEND_FLAGS_CONFIG)
&& i!=3 ) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_INCONSISTENTVALUE);
return SNMP_ERR_INCONSISTENTVALUE;
}
break;
case COLUMN_EXTCFG_STATUS:
if (request->requestvb->type != ASN_INTEGER) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGTYPE);
return SNMP_ERR_WRONGTYPE;
}
i = *request->requestvb->val.integer;
switch (i) {
case RS_ACTIVE:
case RS_NOTINSERVICE:
if (!extension) {
/* Must be used with existing rows */
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_INCONSISTENTVALUE);
return SNMP_ERR_INCONSISTENTVALUE;
}
break; /* OK */
case RS_CREATEANDGO:
case RS_CREATEANDWAIT:
if (extension) {
/* Can only be used to create new rows */
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_INCONSISTENTVALUE);
return SNMP_ERR_INCONSISTENTVALUE;
}
break;
case RS_DESTROY:
break;
default:
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_WRONGVALUE);
return SNMP_ERR_WRONGVALUE;
}
break;
default:
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_NOTWRITABLE);
return SNMP_ERR_NOTWRITABLE;
}
break;
case MODE_SET_RESERVE2:
switch (table_info->colnum) {
case COLUMN_EXTCFG_STATUS:
i = *request->requestvb->val.integer;
switch (i) {
case RS_CREATEANDGO:
case RS_CREATEANDWAIT:
eptr = _find_extension_block( request->requestvb->name,
request->requestvb->name_length );
extension = _new_extension( (char *) table_info->indexes->val.string,
0, eptr );
if (!extension) { /* failed */
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_RESOURCEUNAVAILABLE);
return SNMP_ERR_RESOURCEUNAVAILABLE;
}
netsnmp_insert_table_row( request, extension->row );
}
}
break;
case MODE_SET_FREE:
switch (table_info->colnum) {
case COLUMN_EXTCFG_STATUS:
i = *request->requestvb->val.integer;
switch (i) {
case RS_CREATEANDGO:
case RS_CREATEANDWAIT:
eptr = _find_extension_block( request->requestvb->name,
request->requestvb->name_length );
_free_extension( extension, eptr );
}
}
break;
case MODE_SET_ACTION:
switch (table_info->colnum) {
case COLUMN_EXTCFG_COMMAND:
extension->old_command = extension->command;
extension->command = netsnmp_strdup_and_null(
request->requestvb->val.string,
request->requestvb->val_len);
break;
case COLUMN_EXTCFG_ARGS:
extension->old_args = extension->args;
extension->args = netsnmp_strdup_and_null(
request->requestvb->val.string,
request->requestvb->val_len);
break;
case COLUMN_EXTCFG_INPUT:
extension->old_input = extension->input;
extension->input = netsnmp_strdup_and_null(
request->requestvb->val.string,
request->requestvb->val_len);
break;
case COLUMN_EXTCFG_STATUS:
i = *request->requestvb->val.integer;
switch (i) {
case RS_ACTIVE:
case RS_CREATEANDGO:
need_to_validate = 1;
}
break;
}
break;
case MODE_SET_UNDO:
switch (table_info->colnum) {
case COLUMN_EXTCFG_COMMAND:
if ( extension && extension->old_command ) {
SNMP_FREE(extension->command);
extension->command = extension->old_command;
extension->old_command = NULL;
}
break;
case COLUMN_EXTCFG_ARGS:
if ( extension && extension->old_args ) {
SNMP_FREE(extension->args);
extension->args = extension->old_args;
extension->old_args = NULL;
}
break;
case COLUMN_EXTCFG_INPUT:
if ( extension && extension->old_input ) {
SNMP_FREE(extension->input);
extension->input = extension->old_input;
extension->old_input = NULL;
}
break;
case COLUMN_EXTCFG_STATUS:
i = *request->requestvb->val.integer;
switch (i) {
case RS_CREATEANDGO:
case RS_CREATEANDWAIT:
eptr = _find_extension_block( request->requestvb->name,
request->requestvb->name_length );
_free_extension( extension, eptr );
}
break;
}
break;
case MODE_SET_COMMIT:
switch (table_info->colnum) {
case COLUMN_EXTCFG_CACHETIME:
i = *request->requestvb->val.integer;
extension->cache->timeout = i;
break;
case COLUMN_EXTCFG_RUNTYPE:
i = *request->requestvb->val.integer;
switch (i) {
case 1:
extension->flags &= ~NS_EXTEND_FLAGS_WRITEABLE;
break;
case 2:
extension->flags |= NS_EXTEND_FLAGS_WRITEABLE;
break;
case 3:
(void)netsnmp_cache_check_and_reload( extension->cache );
break;
}
break;
case COLUMN_EXTCFG_EXECTYPE:
i = *request->requestvb->val.integer;
if ( i == NS_EXTEND_ETYPE_SHELL )
extension->flags |= NS_EXTEND_FLAGS_SHELL;
else
extension->flags &= ~NS_EXTEND_FLAGS_SHELL;
break;
case COLUMN_EXTCFG_STATUS:
i = *request->requestvb->val.integer;
switch (i) {
case RS_ACTIVE:
case RS_CREATEANDGO:
extension->flags |= NS_EXTEND_FLAGS_ACTIVE;
break;
case RS_NOTINSERVICE:
case RS_CREATEANDWAIT:
extension->flags &= ~NS_EXTEND_FLAGS_ACTIVE;
break;
case RS_DESTROY:
eptr = _find_extension_block( request->requestvb->name,
request->requestvb->name_length );
_free_extension( extension, eptr );
break;
}
}
break;
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
default:
netsnmp_set_request_error(reqinfo, request, SNMP_ERR_GENERR);
return SNMP_ERR_GENERR;
}
}
#ifndef NETSNMP_NO_WRITE_SUPPORT
/*
* If we're marking a given row as active,
* then we need to check that it's ready.
*/
if (need_to_validate) {
for ( request=requests; request; request=request->next ) {
if (request->processed)
continue;
table_info = netsnmp_extract_table_info( request );
extension = (netsnmp_extend*)netsnmp_extract_table_row_data( request );
switch (table_info->colnum) {
case COLUMN_EXTCFG_STATUS:
i = *request->requestvb->val.integer;
if (( i == RS_ACTIVE || i == RS_CREATEANDGO ) &&
!(extension && extension->command &&
extension->command[0] == '/' /* &&
is_executable(extension->command) */)) {
netsnmp_set_request_error(reqinfo, request,
SNMP_ERR_INCONSISTENTVALUE);
return SNMP_ERR_INCONSISTENTVALUE;
}
}
}
}
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
return SNMP_ERR_NOERROR;
}
int
handle_nsExtendOutput1Table(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
{
netsnmp_request_info *request;
netsnmp_table_request_info *table_info;
netsnmp_extend *extension;
int len;
for ( request=requests; request; request=request->next ) {
if (request->processed)
continue;
table_info = netsnmp_extract_table_info( request );
extension = (netsnmp_extend*)netsnmp_extract_table_row_data( request );
DEBUGMSGTL(( "nsExtendTable:output1", "varbind: "));
DEBUGMSGOID(("nsExtendTable:output1", request->requestvb->name,
request->requestvb->name_length));
DEBUGMSG(( "nsExtendTable:output1", "\n"));
switch (reqinfo->mode) {
case MODE_GET:
if (!extension || !(extension->flags & NS_EXTEND_FLAGS_ACTIVE)) {
/*
* If this row is inactive, then skip it.
*/
netsnmp_set_request_error(reqinfo, request,
SNMP_NOSUCHINSTANCE);
continue;
}
if (!(extension->flags & NS_EXTEND_FLAGS_WRITEABLE) &&
(netsnmp_cache_check_and_reload( extension->cache ) < 0 )) {
/*
* If reloading the output cache of a 'run-on-read'
* entry fails, then skip it.
*/
netsnmp_set_request_error(reqinfo, request,
SNMP_NOSUCHINSTANCE);
continue;
}
if ((extension->flags & NS_EXTEND_FLAGS_WRITEABLE) &&
(netsnmp_cache_check_expired( extension->cache ) == 1 )) {
/*
* If the output cache of a 'run-on-write'
* entry has expired, then skip it.
*/
netsnmp_set_request_error(reqinfo, request,
SNMP_NOSUCHINSTANCE);
continue;
}
switch (table_info->colnum) {
case COLUMN_EXTOUT1_OUTLEN:
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&extension->out_len, sizeof(int));
break;
case COLUMN_EXTOUT1_OUTPUT1:
/*
* If we've got more than one line,
* find the length of the first one.
* Otherwise find the length of the whole string.
*/
if (extension->numlines > 1) {
len = (extension->lines[1])-(extension->output) -1;
} else if (extension->output) {
len = strlen(extension->output);
} else {
len = 0;
}
snmp_set_var_typed_value(
request->requestvb, ASN_OCTET_STR,
extension->output, len);
break;
case COLUMN_EXTOUT1_OUTPUT2:
snmp_set_var_typed_value(
request->requestvb, ASN_OCTET_STR,
extension->output,
(extension->output)?extension->out_len:0);
break;
case COLUMN_EXTOUT1_NUMLINES:
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&extension->numlines, sizeof(int));
break;
case COLUMN_EXTOUT1_RESULT:
snmp_set_var_typed_value(
request->requestvb, ASN_INTEGER,
(u_char*)&extension->result, sizeof(int));
break;
default:
netsnmp_set_request_error(reqinfo, request, SNMP_NOSUCHOBJECT);
continue;
}
break;
default:
netsnmp_set_request_error(reqinfo, request, SNMP_ERR_GENERR);
return SNMP_ERR_GENERR;
}
}
return SNMP_ERR_NOERROR;
}
/*************************
*
* Multi-line output table handler
* Most of the work is handled here.
*
*************************/
/*
* Locate the appropriate entry for a given request
*/
netsnmp_extend *
_extend_find_entry( netsnmp_request_info *request,
netsnmp_table_request_info *table_info,
int mode )
{
netsnmp_extend *eptr;
extend_registration_block *ereg;
unsigned int line_idx;
oid oid_buf[MAX_OID_LEN];
int oid_len;
int i;
char *token;
size_t token_len;
if (!request || !table_info || !table_info->indexes
|| !table_info->indexes->next_variable) {
DEBUGMSGTL(( "nsExtendTable:output2", "invalid invocation\n"));
return NULL;
}
ereg = _find_extension_block( request->requestvb->name,
request->requestvb->name_length );
/***
* GET handling - find the exact entry being requested
***/
if ( mode == MODE_GET ) {
DEBUGMSGTL(( "nsExtendTable:output2", "GET: %s / %ld\n ",
table_info->indexes->val.string,
*table_info->indexes->next_variable->val.integer));
for ( eptr = ereg->ehead; eptr; eptr = eptr->next ) {
if ( !strcmp( eptr->token, (char *) table_info->indexes->val.string ))
break;
}
if ( eptr ) {
/*
* Ensure the output is available...
*/
if (!(eptr->flags & NS_EXTEND_FLAGS_ACTIVE) ||
(netsnmp_cache_check_and_reload( eptr->cache ) < 0 ))
return NULL;
/*
* ...and check the line requested is valid
*/
line_idx = *table_info->indexes->next_variable->val.integer;
if (line_idx < 1 || line_idx > eptr->numlines)
return NULL;
}
}
/***
* GETNEXT handling - find the first suitable entry
***/
else {
if (!table_info->indexes->val_len ) {
DEBUGMSGTL(( "nsExtendTable:output2", "GETNEXT: first entry\n"));
/*
* Beginning of the table - find the first active
* (and successful) entry, and use the first line of it
*/
for (eptr = ereg->ehead; eptr; eptr = eptr->next ) {
if ((eptr->flags & NS_EXTEND_FLAGS_ACTIVE) &&
(netsnmp_cache_check_and_reload( eptr->cache ) >= 0 )) {
line_idx = 1;
break;
}
}
} else {
token = (char *) table_info->indexes->val.string;
token_len = table_info->indexes->val_len;
line_idx = *table_info->indexes->next_variable->val.integer;
DEBUGMSGTL(( "nsExtendTable:output2", "GETNEXT: %s / %d\n ",
token, line_idx ));
/*
* Otherwise, find the first entry not earlier
* than the requested token...
*/
for (eptr = ereg->ehead; eptr; eptr = eptr->next ) {
if ( strlen(eptr->token) > token_len )
break;
if ( strlen(eptr->token) == token_len &&
strcmp(eptr->token, token) >= 0 )
break;
}
if (!eptr)
return NULL; /* (assuming there is one) */
/*
* ... and make sure it's active & the output is available
* (or use the first following entry that is)
*/
for ( ; eptr; eptr = eptr->next ) {
if ((eptr->flags & NS_EXTEND_FLAGS_ACTIVE) &&
(netsnmp_cache_check_and_reload( eptr->cache ) >= 0 )) {
break;
}
line_idx = 1;
}
if (!eptr)
return NULL; /* (assuming there is one) */
/*
* If we're working with the same entry that was requested,
* see whether we've reached the end of the output...
*/
if (!strcmp( eptr->token, token )) {
if ( eptr->numlines <= line_idx ) {
/*
* ... and if so, move on to the first line
* of the next (active and successful) entry.
*/
line_idx = 1;
for (eptr = eptr->next ; eptr; eptr = eptr->next ) {
if ((eptr->flags & NS_EXTEND_FLAGS_ACTIVE) &&
(netsnmp_cache_check_and_reload( eptr->cache ) >= 0 )) {
break;
}
}
} else {
/*
* Otherwise just use the next line of this entry.
*/
line_idx++;
}
}
else {
/*
* If this is not the same entry that was requested,
* then we should return the first line.
*/
line_idx = 1;
}
}
if (eptr) {
DEBUGMSGTL(( "nsExtendTable:output2", "GETNEXT -> %s / %d\n ",
eptr->token, line_idx));
/*
* Since we're processing a GETNEXT request,
* now we've found the appropriate entry (and line),
* we need to update the varbind OID ...
*/
memset(oid_buf, 0, sizeof(oid_buf));
oid_len = ereg->oid_len;
memcpy( oid_buf, ereg->root_oid, oid_len*sizeof(oid));
oid_buf[ oid_len++ ] = 4; /* nsExtendOutput2Table */
oid_buf[ oid_len++ ] = 1; /* nsExtendOutput2Entry */
oid_buf[ oid_len++ ] = COLUMN_EXTOUT2_OUTLINE;
/* string token index */
oid_buf[ oid_len++ ] = strlen(eptr->token);
for ( i=0; i < (int)strlen(eptr->token); i++ )
oid_buf[ oid_len+i ] = eptr->token[i];
oid_len += strlen( eptr->token );
/* plus line number */
oid_buf[ oid_len++ ] = line_idx;
snmp_set_var_objid( request->requestvb, oid_buf, oid_len );
/*
* ... and index values to match.
*/
snmp_set_var_value( table_info->indexes,
eptr->token, strlen(eptr->token));
snmp_set_var_value( table_info->indexes->next_variable,
(const u_char*)&line_idx, sizeof(line_idx));
}
}
return eptr; /* Finally, signal success */
}
/*
* Multi-line output handler
* Locate the appropriate entry (using _extend_find_entry)
* and return the appropriate output line
*/
int
handle_nsExtendOutput2Table(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
{
netsnmp_request_info *request;
netsnmp_table_request_info *table_info;
netsnmp_extend *extension;
char *cp;
unsigned int line_idx;
int len;
for ( request=requests; request; request=request->next ) {
if (request->processed)
continue;
table_info = netsnmp_extract_table_info( request );
extension = _extend_find_entry( request, table_info, reqinfo->mode );
DEBUGMSGTL(( "nsExtendTable:output2", "varbind: "));
DEBUGMSGOID(("nsExtendTable:output2", request->requestvb->name,
request->requestvb->name_length));
DEBUGMSG(( "nsExtendTable:output2", " (%s)\n",
(extension) ? extension->token : "[none]"));
if (!extension) {
if (reqinfo->mode == MODE_GET)
netsnmp_set_request_error(reqinfo, request, SNMP_NOSUCHINSTANCE);
else
netsnmp_set_request_error(reqinfo, request, SNMP_ENDOFMIBVIEW);
continue;
}
switch (reqinfo->mode) {
case MODE_GET:
case MODE_GETNEXT:
switch (table_info->colnum) {
case COLUMN_EXTOUT2_OUTLINE:
/*
* Determine which line we've been asked for....
*/
line_idx = *table_info->indexes->next_variable->val.integer;
if (line_idx < 1 || line_idx > extension->numlines) {
netsnmp_set_request_error(reqinfo, request, SNMP_NOSUCHINSTANCE);
continue;
}
cp = extension->lines[line_idx-1];
/*
* ... and how long it is.
*/
if ( extension->numlines > line_idx )
len = (extension->lines[line_idx])-cp -1;
else if (cp)
len = strlen(cp);
else
len = 0;
snmp_set_var_typed_value( request->requestvb,
ASN_OCTET_STR, cp, len );
break;
default:
netsnmp_set_request_error(reqinfo, request, SNMP_NOSUCHOBJECT);
continue;
}
break;
default:
netsnmp_set_request_error(reqinfo, request, SNMP_ERR_GENERR);
return SNMP_ERR_GENERR;
}
}
return SNMP_ERR_NOERROR;
}
#ifndef USING_UCD_SNMP_EXTENSIBLE_MODULE
/*************************
*
* Compatability with the UCD extTable
*
*************************/
char * _get_cmdline(netsnmp_extend *extend)
{
size_t size;
char *newbuf;
const char *args = extend->args;
if (args == NULL)
/* Use empty string for processes without arguments. */
args = "";
size = strlen(extend->command) + strlen(args) + 2;
if (size > cmdlinesize) {
newbuf = realloc(cmdlinebuf, size);
if (!newbuf) {
free(cmdlinebuf);
cmdlinebuf = NULL;
cmdlinesize = 0;
return NULL;
}
cmdlinebuf = newbuf;
cmdlinesize = size;
}
sprintf(cmdlinebuf, "%s %s", extend->command, args);
return cmdlinebuf;
}
u_char *
var_extensible_old(struct variable * vp,
oid * name,
size_t * length,
int exact,
size_t * var_len, WriteMethod ** write_method)
{
netsnmp_old_extend *exten = NULL;
static long long_ret;
unsigned int idx;
char *cmdline;
if (header_simple_table
(vp, name, length, exact, var_len, write_method, num_compatability_entries))
return (NULL);
idx = name[*length-1] -1;
if (idx > max_compatability_entries)
return NULL;
exten = &compatability_entries[idx];
switch (vp->magic) {
case MIBINDEX:
long_ret = name[*length - 1];
return (u_char *) &long_ret;
case ERRORNAME: /* name defined in config file */
*var_len = strlen(exten->exec_entry->token);
return ((u_char *) (exten->exec_entry->token));
case SHELLCOMMAND:
cmdline = _get_cmdline(exten->exec_entry);
if (cmdline)
*var_len = strlen(cmdline);
return (u_char *) cmdline;
case ERRORFLAG: /* return code from the process */
netsnmp_cache_check_and_reload( exten->exec_entry->cache );
long_ret = exten->exec_entry->result;
return (u_char *) &long_ret;
case ERRORMSG: /* first line of text returned from the process */
netsnmp_cache_check_and_reload( exten->exec_entry->cache );
if (exten->exec_entry->numlines > 1) {
*var_len = (exten->exec_entry->lines[1])-
(exten->exec_entry->output) -1;
} else if (exten->exec_entry->output) {
*var_len = strlen(exten->exec_entry->output);
} else {
*var_len = 0;
}
return (u_char *) exten->exec_entry->output;
case ERRORFIX:
*write_method = fixExec2Error;
long_return = 0;
return (u_char *) &long_return;
case ERRORFIXCMD:
if (exten->efix_entry) {
cmdline = _get_cmdline(exten->efix_entry);
if (cmdline)
*var_len = strlen(cmdline);
return (u_char *) cmdline;
} else {
*var_len = 0;
return (u_char *) &long_return; /* Just needs to be non-null! */
}
}
return NULL;
}
int
fixExec2Error(int action,
u_char * var_val,
u_char var_val_type,
size_t var_val_len,
u_char * statP, oid * name, size_t name_len)
{
netsnmp_old_extend *exten = NULL;
unsigned int idx;
idx = name[name_len-1] -1;
exten = &compatability_entries[ idx ];
#ifndef NETSNMP_NO_WRITE_SUPPORT
switch (action) {
case MODE_SET_RESERVE1:
if (var_val_type != ASN_INTEGER) {
snmp_log(LOG_ERR, "Wrong type != int\n");
return SNMP_ERR_WRONGTYPE;
}
idx = *((long *) var_val);
if (idx != 1) {
snmp_log(LOG_ERR, "Wrong value != 1\n");
return SNMP_ERR_WRONGVALUE;
}
if (!exten || !exten->efix_entry) {
snmp_log(LOG_ERR, "No command to run\n");
return SNMP_ERR_GENERR;
}
return SNMP_ERR_NOERROR;
case MODE_SET_COMMIT:
netsnmp_cache_check_and_reload( exten->efix_entry->cache );
}
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
return SNMP_ERR_NOERROR;
}
#endif /* USING_UCD_SNMP_EXTENSIBLE_MODULE */
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_4227_0 |
crossvul-cpp_data_good_3233_5 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include <signal.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/types.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#ifndef DEDICATED
#ifdef USE_LOCAL_HEADERS
# include "SDL.h"
# include "SDL_cpuinfo.h"
#else
# include <SDL.h>
# include <SDL_cpuinfo.h>
#endif
#endif
#include "sys_local.h"
#include "sys_loadlib.h"
#include "../qcommon/q_shared.h"
#include "../qcommon/qcommon.h"
static char binaryPath[ MAX_OSPATH ] = { 0 };
static char installPath[ MAX_OSPATH ] = { 0 };
/*
=================
Sys_SetBinaryPath
=================
*/
void Sys_SetBinaryPath(const char *path)
{
Q_strncpyz(binaryPath, path, sizeof(binaryPath));
}
/*
=================
Sys_BinaryPath
=================
*/
char *Sys_BinaryPath(void)
{
return binaryPath;
}
/*
=================
Sys_SetDefaultInstallPath
=================
*/
void Sys_SetDefaultInstallPath(const char *path)
{
Q_strncpyz(installPath, path, sizeof(installPath));
}
/*
=================
Sys_DefaultInstallPath
=================
*/
char *Sys_DefaultInstallPath(void)
{
if (*installPath)
return installPath;
else
return Sys_Cwd();
}
/*
=================
Sys_DefaultAppPath
=================
*/
char *Sys_DefaultAppPath(void)
{
return Sys_BinaryPath();
}
/*
=================
Sys_In_Restart_f
Restart the input subsystem
=================
*/
void Sys_In_Restart_f( void )
{
IN_Restart( );
}
/*
=================
Sys_ConsoleInput
Handle new console input
=================
*/
char *Sys_ConsoleInput(void)
{
return CON_Input( );
}
/*
==================
Sys_GetClipboardData
==================
*/
char *Sys_GetClipboardData(void)
{
#ifdef DEDICATED
return NULL;
#else
char *data = NULL;
char *cliptext;
if ( ( cliptext = SDL_GetClipboardText() ) != NULL ) {
if ( cliptext[0] != '\0' ) {
size_t bufsize = strlen( cliptext ) + 1;
data = Z_Malloc( bufsize );
Q_strncpyz( data, cliptext, bufsize );
// find first listed char and set to '\0'
strtok( data, "\n\r\b" );
}
SDL_free( cliptext );
}
return data;
#endif
}
#ifdef DEDICATED
# define PID_FILENAME "iowolfsp_server.pid"
#else
# define PID_FILENAME "iowolfsp.pid"
#endif
/*
=================
Sys_PIDFileName
=================
*/
static char *Sys_PIDFileName( const char *gamedir )
{
const char *homePath = Cvar_VariableString( "fs_homepath" );
if( *homePath != '\0' )
return va( "%s/%s/%s", homePath, gamedir, PID_FILENAME );
return NULL;
}
/*
=================
Sys_RemovePIDFile
=================
*/
void Sys_RemovePIDFile( const char *gamedir )
{
char *pidFile = Sys_PIDFileName( gamedir );
if( pidFile != NULL )
remove( pidFile );
}
/*
=================
Sys_WritePIDFile
Return qtrue if there is an existing stale PID file
=================
*/
static qboolean Sys_WritePIDFile( const char *gamedir )
{
char *pidFile = Sys_PIDFileName( gamedir );
FILE *f;
qboolean stale = qfalse;
if( pidFile == NULL )
return qfalse;
// First, check if the pid file is already there
if( ( f = fopen( pidFile, "r" ) ) != NULL )
{
char pidBuffer[ 64 ] = { 0 };
int pid;
pid = fread( pidBuffer, sizeof( char ), sizeof( pidBuffer ) - 1, f );
fclose( f );
if(pid > 0)
{
pid = atoi( pidBuffer );
if( !Sys_PIDIsRunning( pid ) )
stale = qtrue;
}
else
stale = qtrue;
}
if( FS_CreatePath( pidFile ) ) {
return 0;
}
if( ( f = fopen( pidFile, "w" ) ) != NULL )
{
fprintf( f, "%d", Sys_PID( ) );
fclose( f );
}
else
Com_Printf( S_COLOR_YELLOW "Couldn't write %s.\n", pidFile );
return stale;
}
/*
=================
Sys_InitPIDFile
=================
*/
void Sys_InitPIDFile( const char *gamedir ) {
if( Sys_WritePIDFile( gamedir ) ) {
#ifndef DEDICATED
char message[1024];
char modName[MAX_OSPATH];
FS_GetModDescription( gamedir, modName, sizeof ( modName ) );
Q_CleanStr( modName );
Com_sprintf( message, sizeof (message), "The last time %s ran, "
"it didn't exit properly. This may be due to inappropriate video "
"settings. Would you like to start with \"safe\" video settings?", modName );
if( Sys_Dialog( DT_YES_NO, message, "Abnormal Exit" ) == DR_YES ) {
Cvar_Set( "com_abnormalExit", "1" );
}
#endif
}
}
/*
=================
Sys_Exit
Single exit point (regular exit or in case of error)
=================
*/
static __attribute__ ((noreturn)) void Sys_Exit( int exitCode )
{
CON_Shutdown( );
#ifndef DEDICATED
SDL_Quit( );
#endif
if( exitCode < 2 && com_fullyInitialized )
{
// Normal exit
Sys_RemovePIDFile( FS_GetCurrentGameDir() );
}
NET_Shutdown( );
Sys_PlatformExit( );
exit( exitCode );
}
/*
=================
Sys_Quit
=================
*/
void Sys_Quit( void )
{
Sys_Exit( 0 );
}
/*
=================
Sys_GetProcessorFeatures
=================
*/
cpuFeatures_t Sys_GetProcessorFeatures( void )
{
cpuFeatures_t features = 0;
#ifndef DEDICATED
if( SDL_HasRDTSC( ) ) features |= CF_RDTSC;
if( SDL_Has3DNow( ) ) features |= CF_3DNOW;
if( SDL_HasMMX( ) ) features |= CF_MMX;
if( SDL_HasSSE( ) ) features |= CF_SSE;
if( SDL_HasSSE2( ) ) features |= CF_SSE2;
if( SDL_HasAltiVec( ) ) features |= CF_ALTIVEC;
#endif
return features;
}
/*
=================
Sys_Init
=================
*/
void Sys_Init(void)
{
Cmd_AddCommand( "in_restart", Sys_In_Restart_f );
Cvar_Set( "arch", OS_STRING " " ARCH_STRING );
Cvar_Set( "username", Sys_GetCurrentUser( ) );
}
/*
=================
Sys_AnsiColorPrint
Transform Q3 colour codes to ANSI escape sequences
=================
*/
void Sys_AnsiColorPrint( const char *msg )
{
static char buffer[ MAXPRINTMSG ];
int length = 0;
static int q3ToAnsi[ 8 ] =
{
30, // COLOR_BLACK
31, // COLOR_RED
32, // COLOR_GREEN
33, // COLOR_YELLOW
34, // COLOR_BLUE
36, // COLOR_CYAN
35, // COLOR_MAGENTA
0 // COLOR_WHITE
};
while( *msg )
{
if( Q_IsColorString( msg ) || *msg == '\n' )
{
// First empty the buffer
if( length > 0 )
{
buffer[ length ] = '\0';
fputs( buffer, stderr );
length = 0;
}
if( *msg == '\n' )
{
// Issue a reset and then the newline
fputs( "\033[0m\n", stderr );
msg++;
}
else
{
// Print the color code
Com_sprintf( buffer, sizeof( buffer ), "\033[%dm",
q3ToAnsi[ ColorIndex( *( msg + 1 ) ) ] );
fputs( buffer, stderr );
msg += 2;
}
}
else
{
if( length >= MAXPRINTMSG - 1 )
break;
buffer[ length ] = *msg;
length++;
msg++;
}
}
// Empty anything still left in the buffer
if( length > 0 )
{
buffer[ length ] = '\0';
fputs( buffer, stderr );
}
}
/*
=================
Sys_Print
=================
*/
void Sys_Print( const char *msg )
{
CON_LogWrite( msg );
CON_Print( msg );
}
/*
=================
Sys_Error
=================
*/
void Sys_Error( const char *error, ... )
{
va_list argptr;
char string[1024];
va_start (argptr,error);
Q_vsnprintf (string, sizeof(string), error, argptr);
va_end (argptr);
Sys_ErrorDialog( string );
Sys_Exit( 3 );
}
#if 0
/*
=================
Sys_Warn
=================
*/
static __attribute__ ((format (printf, 1, 2))) void Sys_Warn( char *warning, ... )
{
va_list argptr;
char string[1024];
va_start (argptr,warning);
Q_vsnprintf (string, sizeof(string), warning, argptr);
va_end (argptr);
CON_Print( va( "Warning: %s", string ) );
}
#endif
/*
============
Sys_FileTime
returns -1 if not present
============
*/
int Sys_FileTime( char *path )
{
struct stat buf;
if (stat (path,&buf) == -1)
return -1;
return buf.st_mtime;
}
/*
=================
Sys_UnloadDll
=================
*/
void Sys_UnloadDll( void *dllHandle )
{
if( !dllHandle )
{
Com_Printf("Sys_UnloadDll(NULL)\n");
return;
}
Sys_UnloadLibrary(dllHandle);
}
/*
=================
Sys_LoadDll
First try to load library name from system library path,
from executable path, then fs_basepath.
=================
*/
void *Sys_LoadDll(const char *name, qboolean useSystemLib)
{
void *dllhandle;
// Don't load any DLLs that end with the pk3 extension
if (COM_CompareExtension(name, ".pk3"))
{
Com_Printf("Rejecting DLL named \"%s\"", name);
return NULL;
}
if(useSystemLib)
Com_Printf("Trying to load \"%s\"...\n", name);
if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name)))
{
const char *topDir;
char libPath[MAX_OSPATH];
topDir = Sys_BinaryPath();
if(!*topDir)
topDir = ".";
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name);
if(!(dllhandle = Sys_LoadLibrary(libPath)))
{
const char *basePath = Cvar_VariableString("fs_basepath");
if(!basePath || !*basePath)
basePath = ".";
if(FS_FilenameCompare(topDir, basePath))
{
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name);
dllhandle = Sys_LoadLibrary(libPath);
}
if(!dllhandle)
Com_Printf("Loading \"%s\" failed\n", name);
}
}
return dllhandle;
}
/*
=================
Sys_LoadGameDll
Used to load a development dll instead of a virtual machine
=================
*/
void *Sys_LoadGameDll(const char *name,
intptr_t (QDECL **entryPoint)(intptr_t, ...),
intptr_t (*systemcalls)(intptr_t, ...))
{
void *libHandle;
void (*dllEntry)(intptr_t (*syscallptr)(intptr_t, ...));
assert(name);
Com_DPrintf( "Loading DLL file: %s\n", name);
libHandle = Sys_LoadLibrary(name);
if(!libHandle)
{
Com_Printf("Sys_LoadGameDll(%s) failed:\n\"%s\"\n", name, Sys_LibraryError());
return NULL;
}
dllEntry = Sys_LoadFunction( libHandle, "dllEntry" );
*entryPoint = Sys_LoadFunction( libHandle, "vmMain" );
if ( !*entryPoint || !dllEntry )
{
Com_Printf ( "Sys_LoadGameDll(%s) failed to find vmMain function:\n\"%s\" !\n", name, Sys_LibraryError( ) );
Sys_UnloadLibrary(libHandle);
return NULL;
}
Com_DPrintf ( "Sys_LoadGameDll(%s) found vmMain function at %p\n", name, *entryPoint );
dllEntry( systemcalls );
return libHandle;
}
/*
=================
Sys_ParseArgs
=================
*/
void Sys_ParseArgs( int argc, char **argv )
{
if( argc == 2 )
{
if( !strcmp( argv[1], "--version" ) ||
!strcmp( argv[1], "-v" ) )
{
const char* date = PRODUCT_DATE;
#ifdef DEDICATED
fprintf( stdout, Q3_VERSION " dedicated server (%s)\n", date );
#else
fprintf( stdout, Q3_VERSION " client (%s)\n", date );
#endif
Sys_Exit( 0 );
}
}
}
#ifndef DEFAULT_BASEDIR
# ifdef __APPLE__
# define DEFAULT_BASEDIR Sys_StripAppBundle(Sys_BinaryPath())
# else
# define DEFAULT_BASEDIR Sys_BinaryPath()
# endif
#endif
/*
=================
Sys_SigHandler
=================
*/
void Sys_SigHandler( int signal )
{
static qboolean signalcaught = qfalse;
if( signalcaught )
{
fprintf( stderr, "DOUBLE SIGNAL FAULT: Received signal %d, exiting...\n",
signal );
}
else
{
signalcaught = qtrue;
VM_Forced_Unload_Start();
#ifndef DEDICATED
CL_Shutdown(va("Received signal %d", signal), qtrue, qtrue);
#endif
SV_Shutdown(va("Received signal %d", signal) );
VM_Forced_Unload_Done();
}
if( signal == SIGTERM || signal == SIGINT )
Sys_Exit( 1 );
else
Sys_Exit( 2 );
}
/*
=================
main
=================
*/
int main( int argc, char **argv )
{
int i;
char commandLine[ MAX_STRING_CHARS ] = { 0 };
#ifndef DEDICATED
// SDL version check
// Compile time
# if !SDL_VERSION_ATLEAST(MINSDL_MAJOR,MINSDL_MINOR,MINSDL_PATCH)
# error A more recent version of SDL is required
# endif
// Run time
SDL_version ver;
SDL_GetVersion( &ver );
#define MINSDL_VERSION \
XSTRING(MINSDL_MAJOR) "." \
XSTRING(MINSDL_MINOR) "." \
XSTRING(MINSDL_PATCH)
if( SDL_VERSIONNUM( ver.major, ver.minor, ver.patch ) <
SDL_VERSIONNUM( MINSDL_MAJOR, MINSDL_MINOR, MINSDL_PATCH ) )
{
Sys_Dialog( DT_ERROR, va( "SDL version " MINSDL_VERSION " or greater is required, "
"but only version %d.%d.%d was found. You may be able to obtain a more recent copy "
"from http://www.libsdl.org/.", ver.major, ver.minor, ver.patch ), "SDL Library Too Old" );
Sys_Exit( 1 );
}
#endif
Sys_PlatformInit( );
// Set the initial time base
Sys_Milliseconds( );
#ifdef __APPLE__
// This is passed if we are launched by double-clicking
if ( argc >= 2 && Q_strncmp ( argv[1], "-psn", 4 ) == 0 )
argc = 1;
#endif
Sys_ParseArgs( argc, argv );
Sys_SetBinaryPath( Sys_Dirname( argv[ 0 ] ) );
Sys_SetDefaultInstallPath( DEFAULT_BASEDIR );
// Concatenate the command line for passing to Com_Init
for( i = 1; i < argc; i++ )
{
const qboolean containsSpaces = strchr(argv[i], ' ') != NULL;
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), argv[ i ] );
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), " " );
}
Com_Init( commandLine );
NET_Init( );
CON_Init( );
signal( SIGILL, Sys_SigHandler );
signal( SIGFPE, Sys_SigHandler );
signal( SIGSEGV, Sys_SigHandler );
signal( SIGTERM, Sys_SigHandler );
signal( SIGINT, Sys_SigHandler );
while( 1 )
{
IN_Frame( );
Com_Frame( );
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3233_5 |
crossvul-cpp_data_bad_3232_0 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
Copyright (C) 2005 Stuart Dalton (badcdev@gmail.com)
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "snd_local.h"
#include "snd_codec.h"
#include "client.h"
#ifdef USE_OPENAL
#include "qal.h"
// Console variables specific to OpenAL
cvar_t *s_alPrecache;
cvar_t *s_alGain;
cvar_t *s_alSources;
cvar_t *s_alDopplerFactor;
cvar_t *s_alDopplerSpeed;
cvar_t *s_alMinDistance;
cvar_t *s_alMaxDistance;
cvar_t *s_alRolloff;
cvar_t *s_alGraceDistance;
cvar_t *s_alDriver;
cvar_t *s_alDevice;
cvar_t *s_alInputDevice;
cvar_t *s_alAvailableDevices;
cvar_t *s_alAvailableInputDevices;
static qboolean enumeration_ext = qfalse;
static qboolean enumeration_all_ext = qfalse;
#ifdef USE_VOIP
static qboolean capture_ext = qfalse;
#endif
/*
=================
S_AL_Format
=================
*/
static
ALuint S_AL_Format(int width, int channels)
{
ALuint format = AL_FORMAT_MONO16;
// Work out format
if(width == 1)
{
if(channels == 1)
format = AL_FORMAT_MONO8;
else if(channels == 2)
format = AL_FORMAT_STEREO8;
}
else if(width == 2)
{
if(channels == 1)
format = AL_FORMAT_MONO16;
else if(channels == 2)
format = AL_FORMAT_STEREO16;
}
return format;
}
/*
=================
S_AL_ErrorMsg
=================
*/
static const char *S_AL_ErrorMsg(ALenum error)
{
switch(error)
{
case AL_NO_ERROR:
return "No error";
case AL_INVALID_NAME:
return "Invalid name";
case AL_INVALID_ENUM:
return "Invalid enumerator";
case AL_INVALID_VALUE:
return "Invalid value";
case AL_INVALID_OPERATION:
return "Invalid operation";
case AL_OUT_OF_MEMORY:
return "Out of memory";
default:
return "Unknown error";
}
}
/*
=================
S_AL_ClearError
=================
*/
static void S_AL_ClearError( qboolean quiet )
{
int error = qalGetError();
if( quiet )
return;
if(error != AL_NO_ERROR)
{
Com_DPrintf(S_COLOR_YELLOW "WARNING: unhandled AL error: %s\n",
S_AL_ErrorMsg(error));
}
}
//===========================================================================
typedef struct alSfx_s
{
char filename[MAX_QPATH];
ALuint buffer; // OpenAL buffer
snd_info_t info; // information for this sound like rate, sample count..
qboolean isDefault; // Couldn't be loaded - use default FX
qboolean isDefaultChecked; // Sound has been check if it isDefault
qboolean inMemory; // Sound is stored in memory
qboolean isLocked; // Sound is locked (can not be unloaded)
int lastUsedTime; // Time last used
int loopCnt; // number of loops using this sfx
int loopActiveCnt; // number of playing loops using this sfx
int masterLoopSrc; // All other sources looping this buffer are synced to this master src
} alSfx_t;
static qboolean alBuffersInitialised = qfalse;
// Sound effect storage, data structures
#define MAX_SFX 4096
static alSfx_t knownSfx[MAX_SFX];
static sfxHandle_t numSfx = 0;
static sfxHandle_t default_sfx;
/*
=================
S_AL_BufferFindFree
Find a free handle
=================
*/
static sfxHandle_t S_AL_BufferFindFree( void )
{
int i;
for(i = 0; i < MAX_SFX; i++)
{
// Got one
if(knownSfx[i].filename[0] == '\0')
{
if(i >= numSfx)
numSfx = i + 1;
return i;
}
}
// Shit...
Com_Error(ERR_FATAL, "S_AL_BufferFindFree: No free sound handles");
return -1;
}
/*
=================
S_AL_BufferFind
Find a sound effect if loaded, set up a handle otherwise
=================
*/
static sfxHandle_t S_AL_BufferFind(const char *filename)
{
// Look it up in the table
sfxHandle_t sfx = -1;
int i;
if ( !filename ) {
//Com_Error( ERR_FATAL, "Sound name is NULL" );
filename = "*default*";
}
if ( !filename[0] ) {
//Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is empty\n" );
filename = "*default*";
}
if ( strlen( filename ) >= MAX_QPATH ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is too long: %s\n", filename );
return 0;
}
for(i = 0; i < numSfx; i++)
{
if(!Q_stricmp(knownSfx[i].filename, filename))
{
sfx = i;
break;
}
}
// Not found in table?
if(sfx == -1)
{
alSfx_t *ptr;
sfx = S_AL_BufferFindFree();
// Clear and copy the filename over
ptr = &knownSfx[sfx];
memset(ptr, 0, sizeof(*ptr));
ptr->masterLoopSrc = -1;
strcpy(ptr->filename, filename);
}
// Return the handle
return sfx;
}
/*
=================
S_AL_BufferUseDefault
=================
*/
static void S_AL_BufferUseDefault(sfxHandle_t sfx)
{
if(sfx == default_sfx)
Com_Error(ERR_FATAL, "Can't load default sound effect %s", knownSfx[sfx].filename);
// Com_Printf( S_COLOR_YELLOW "WARNING: Using default sound for %s\n", knownSfx[sfx].filename);
knownSfx[sfx].isDefault = qtrue;
knownSfx[sfx].buffer = knownSfx[default_sfx].buffer;
}
/*
=================
S_AL_BufferUnload
=================
*/
static void S_AL_BufferUnload(sfxHandle_t sfx)
{
if(knownSfx[sfx].filename[0] == '\0')
return;
if(!knownSfx[sfx].inMemory)
return;
// Delete it
S_AL_ClearError( qfalse );
qalDeleteBuffers(1, &knownSfx[sfx].buffer);
if(qalGetError() != AL_NO_ERROR)
Com_Printf( S_COLOR_RED "ERROR: Can't delete sound buffer for %s\n",
knownSfx[sfx].filename);
knownSfx[sfx].inMemory = qfalse;
}
/*
=================
S_AL_BufferEvict
=================
*/
static qboolean S_AL_BufferEvict( void )
{
int i, oldestBuffer = -1;
int oldestTime = Sys_Milliseconds( );
for( i = 0; i < numSfx; i++ )
{
if( !knownSfx[ i ].filename[ 0 ] )
continue;
if( !knownSfx[ i ].inMemory )
continue;
if( knownSfx[ i ].lastUsedTime < oldestTime )
{
oldestTime = knownSfx[ i ].lastUsedTime;
oldestBuffer = i;
}
}
if( oldestBuffer >= 0 )
{
S_AL_BufferUnload( oldestBuffer );
return qtrue;
}
else
return qfalse;
}
/*
=================
S_AL_GenBuffers
=================
*/
static qboolean S_AL_GenBuffers(ALsizei numBuffers, ALuint *buffers, const char *name)
{
ALenum error;
S_AL_ClearError( qfalse );
qalGenBuffers( numBuffers, buffers );
error = qalGetError();
// If we ran out of buffers, start evicting the least recently used sounds
while( error == AL_INVALID_VALUE )
{
if( !S_AL_BufferEvict( ) )
{
Com_Printf( S_COLOR_RED "ERROR: Out of audio buffers\n");
return qfalse;
}
// Try again
S_AL_ClearError( qfalse );
qalGenBuffers( numBuffers, buffers );
error = qalGetError();
}
if( error != AL_NO_ERROR )
{
Com_Printf( S_COLOR_RED "ERROR: Can't create a sound buffer for %s - %s\n",
name, S_AL_ErrorMsg(error));
return qfalse;
}
return qtrue;
}
/*
=================
S_AL_BufferLoad
=================
*/
static void S_AL_BufferLoad(sfxHandle_t sfx, qboolean cache)
{
ALenum error;
ALuint format;
void *data;
snd_info_t info;
alSfx_t *curSfx = &knownSfx[sfx];
// Nothing?
if(curSfx->filename[0] == '\0')
return;
// Player SFX
if(curSfx->filename[0] == '*')
return;
// Already done?
if((curSfx->inMemory) || (curSfx->isDefault) || (!cache && curSfx->isDefaultChecked))
return;
// Try to load
data = S_CodecLoad(curSfx->filename, &info);
if(!data)
{
S_AL_BufferUseDefault(sfx);
return;
}
curSfx->isDefaultChecked = qtrue;
if (!cache)
{
// Don't create AL cache
Hunk_FreeTempMemory(data);
return;
}
format = S_AL_Format(info.width, info.channels);
// Create a buffer
if (!S_AL_GenBuffers(1, &curSfx->buffer, curSfx->filename))
{
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
return;
}
// Fill the buffer
if( info.size == 0 )
{
// We have no data to buffer, so buffer silence
byte dummyData[ 2 ] = { 0 };
qalBufferData(curSfx->buffer, AL_FORMAT_MONO16, (void *)dummyData, 2, 22050);
}
else
qalBufferData(curSfx->buffer, format, data, info.size, info.rate);
error = qalGetError();
// If we ran out of memory, start evicting the least recently used sounds
while(error == AL_OUT_OF_MEMORY)
{
if( !S_AL_BufferEvict( ) )
{
qalDeleteBuffers(1, &curSfx->buffer);
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
Com_Printf( S_COLOR_RED "ERROR: Out of memory loading %s\n", curSfx->filename);
return;
}
// Try load it again
qalBufferData(curSfx->buffer, format, data, info.size, info.rate);
error = qalGetError();
}
// Some other error condition
if(error != AL_NO_ERROR)
{
qalDeleteBuffers(1, &curSfx->buffer);
S_AL_BufferUseDefault(sfx);
Hunk_FreeTempMemory(data);
Com_Printf( S_COLOR_RED "ERROR: Can't fill sound buffer for %s - %s\n",
curSfx->filename, S_AL_ErrorMsg(error));
return;
}
curSfx->info = info;
// Free the memory
Hunk_FreeTempMemory(data);
// Woo!
curSfx->inMemory = qtrue;
}
/*
=================
S_AL_BufferUse
=================
*/
static
void S_AL_BufferUse(sfxHandle_t sfx)
{
if(knownSfx[sfx].filename[0] == '\0')
return;
if((!knownSfx[sfx].inMemory) && (!knownSfx[sfx].isDefault))
S_AL_BufferLoad(sfx, qtrue);
knownSfx[sfx].lastUsedTime = Sys_Milliseconds();
}
/*
=================
S_AL_BufferInit
=================
*/
static
qboolean S_AL_BufferInit( void )
{
if(alBuffersInitialised)
return qtrue;
// Clear the hash table, and SFX table
memset(knownSfx, 0, sizeof(knownSfx));
numSfx = 0;
// Load the default sound, and lock it
default_sfx = S_AL_BufferFind( "***DEFAULT***" );
S_AL_BufferUse(default_sfx);
knownSfx[default_sfx].isLocked = qtrue;
// All done
alBuffersInitialised = qtrue;
return qtrue;
}
/*
=================
S_AL_BufferShutdown
=================
*/
static
void S_AL_BufferShutdown( void )
{
int i;
if(!alBuffersInitialised)
return;
// Unlock the default sound effect
knownSfx[default_sfx].isLocked = qfalse;
// Free all used effects
for(i = 0; i < numSfx; i++)
S_AL_BufferUnload(i);
// Clear the tables
numSfx = 0;
// All undone
alBuffersInitialised = qfalse;
}
/*
=================
S_AL_RegisterSound
=================
*/
static
sfxHandle_t S_AL_RegisterSound( const char *sample, qboolean compressed )
{
sfxHandle_t sfx = S_AL_BufferFind(sample);
if((!knownSfx[sfx].inMemory) && (!knownSfx[sfx].isDefault))
S_AL_BufferLoad(sfx, s_alPrecache->integer);
knownSfx[sfx].lastUsedTime = Com_Milliseconds();
if (knownSfx[sfx].isDefault) {
return 0;
}
return sfx;
}
/*
=================
S_AL_BufferGet
Return's a sfx's buffer
=================
*/
static
ALuint S_AL_BufferGet(sfxHandle_t sfx)
{
return knownSfx[sfx].buffer;
}
//===========================================================================
typedef struct src_s
{
ALuint alSource; // OpenAL source object
sfxHandle_t sfx; // Sound effect in use
int lastUsedTime; // Last time used
alSrcPriority_t priority; // Priority
int entity; // Owning entity (-1 if none)
int channel; // Associated channel (-1 if none)
qboolean isActive; // Is this source currently in use?
qboolean isPlaying; // Is this source currently playing, or stopped?
qboolean isLocked; // This is locked (un-allocatable)
qboolean isLooping; // Is this a looping effect (attached to an entity)
qboolean isTracking; // Is this object tracking its owner
qboolean isStream; // Is this source a stream
float curGain; // gain employed if source is within maxdistance.
float scaleGain; // Last gain value for this source. 0 if muted.
float lastTimePos; // On stopped loops, the last position in the buffer
int lastSampleTime; // Time when this was stopped
vec3_t loopSpeakerPos; // Origin of the loop speaker
qboolean local; // Is this local (relative to the cam)
int flags; // flags from StartSoundEx
} src_t;
#ifdef __APPLE__
#define MAX_SRC 128
#else
#define MAX_SRC 256
#endif
static src_t srcList[MAX_SRC];
static int srcCount = 0;
static int srcActiveCnt = 0;
static qboolean alSourcesInitialised = qfalse;
static int lastListenerNumber = -1;
static vec3_t lastListenerOrigin = { 0.0f, 0.0f, 0.0f };
typedef struct sentity_s
{
vec3_t origin;
qboolean srcAllocated; // If a src_t has been allocated to this entity
int srcIndex;
qboolean loopAddedThisFrame;
alSrcPriority_t loopPriority;
sfxHandle_t loopSfx;
qboolean startLoopingSound;
} sentity_t;
static sentity_t entityList[MAX_GENTITIES];
/*
=================
S_AL_SanitiseVector
=================
*/
#define S_AL_SanitiseVector(v) _S_AL_SanitiseVector(v,__LINE__)
static void _S_AL_SanitiseVector( vec3_t v, int line )
{
if( Q_isnan( v[ 0 ] ) || Q_isnan( v[ 1 ] ) || Q_isnan( v[ 2 ] ) )
{
Com_DPrintf( S_COLOR_YELLOW "WARNING: vector with one or more NaN components "
"being passed to OpenAL at %s:%d -- zeroing\n", __FILE__, line );
VectorClear( v );
}
}
/*
=================
S_AL_Gain
Set gain to 0 if muted, otherwise set it to given value.
=================
*/
static void S_AL_Gain(ALuint source, float gainval)
{
if(s_muted->integer)
qalSourcef(source, AL_GAIN, 0.0f);
else
qalSourcef(source, AL_GAIN, gainval);
}
/*
=================
S_AL_ScaleGain
Adapt the gain if necessary to get a quicker fadeout when the source is too far away.
=================
*/
static void S_AL_ScaleGain(src_t *chksrc, vec3_t origin)
{
float distance;
if(!chksrc->local)
distance = Distance(origin, lastListenerOrigin);
// If we exceed a certain distance, scale the gain linearly until the sound
// vanishes into nothingness.
if(!chksrc->local && (distance -= s_alMaxDistance->value) > 0)
{
float scaleFactor;
if(distance >= s_alGraceDistance->value)
scaleFactor = 0.0f;
else
scaleFactor = 1.0f - distance / s_alGraceDistance->value;
scaleFactor *= chksrc->curGain;
if(chksrc->scaleGain != scaleFactor)
{
chksrc->scaleGain = scaleFactor;
S_AL_Gain(chksrc->alSource, chksrc->scaleGain);
}
}
else if(chksrc->scaleGain != chksrc->curGain)
{
chksrc->scaleGain = chksrc->curGain;
S_AL_Gain(chksrc->alSource, chksrc->scaleGain);
}
}
/*
=================
S_AL_HearingThroughEntity
Also see S_Base_HearingThroughEntity
=================
*/
static qboolean S_AL_HearingThroughEntity( int entityNum )
{
float distanceSq;
if( lastListenerNumber == entityNum )
{
// This is an outrageous hack to detect
// whether or not the player is rendering in third person or not. We can't
// ask the renderer because the renderer has no notion of entities and we
// can't ask cgame since that would involve changing the API and hence mod
// compatibility. I don't think there is any way around this, but I'll leave
// the FIXME just in case anyone has a bright idea.
distanceSq = DistanceSquared(
entityList[ entityNum ].origin,
lastListenerOrigin );
if( distanceSq > THIRD_PERSON_THRESHOLD_SQ )
return qfalse; //we're the player, but third person
else
return qtrue; //we're the player
}
else
return qfalse; //not the player
}
/*
=================
S_AL_SrcInit
=================
*/
static
qboolean S_AL_SrcInit( void )
{
int i;
int limit;
// Clear the sources data structure
memset(srcList, 0, sizeof(srcList));
srcCount = 0;
srcActiveCnt = 0;
// Cap s_alSources to MAX_SRC
limit = s_alSources->integer;
if(limit > MAX_SRC)
limit = MAX_SRC;
else if(limit < 16)
limit = 16;
S_AL_ClearError( qfalse );
// Allocate as many sources as possible
for(i = 0; i < limit; i++)
{
qalGenSources(1, &srcList[i].alSource);
if(qalGetError() != AL_NO_ERROR)
break;
srcCount++;
}
alSourcesInitialised = qtrue;
return qtrue;
}
/*
=================
S_AL_SrcShutdown
=================
*/
static
void S_AL_SrcShutdown( void )
{
int i;
src_t *curSource;
if(!alSourcesInitialised)
return;
// Destroy all the sources
for(i = 0; i < srcCount; i++)
{
curSource = &srcList[i];
if(curSource->isLocked)
{
srcList[i].isLocked = qfalse;
Com_DPrintf( S_COLOR_YELLOW "WARNING: Source %d was locked\n", i);
}
if(curSource->entity > 0)
entityList[curSource->entity].srcAllocated = qfalse;
qalSourceStop(srcList[i].alSource);
qalDeleteSources(1, &srcList[i].alSource);
}
memset(srcList, 0, sizeof(srcList));
alSourcesInitialised = qfalse;
}
/*
=================
S_AL_SrcSetup
=================
*/
static void S_AL_SrcSetup(srcHandle_t src, sfxHandle_t sfx, alSrcPriority_t priority,
int entity, int channel, int flags, qboolean local)
{
src_t *curSource;
// Set up src struct
curSource = &srcList[src];
curSource->lastUsedTime = Sys_Milliseconds();
curSource->sfx = sfx;
curSource->priority = priority;
curSource->entity = entity;
curSource->channel = channel;
curSource->isPlaying = qfalse;
curSource->isLocked = qfalse;
curSource->isLooping = qfalse;
curSource->isTracking = qfalse;
curSource->isStream = qfalse;
curSource->curGain = s_alGain->value * s_volume->value;
curSource->scaleGain = curSource->curGain;
curSource->local = local;
curSource->flags = flags;
// Set up OpenAL source
if(sfx >= 0)
{
// Mark the SFX as used, and grab the raw AL buffer
S_AL_BufferUse(sfx);
qalSourcei(curSource->alSource, AL_BUFFER, S_AL_BufferGet(sfx));
}
qalSourcef(curSource->alSource, AL_PITCH, 1.0f);
S_AL_Gain(curSource->alSource, curSource->curGain);
qalSourcefv(curSource->alSource, AL_POSITION, vec3_origin);
qalSourcefv(curSource->alSource, AL_VELOCITY, vec3_origin);
qalSourcei(curSource->alSource, AL_LOOPING, AL_FALSE);
qalSourcef(curSource->alSource, AL_REFERENCE_DISTANCE, s_alMinDistance->value);
if(local)
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_TRUE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, 0.0f);
}
else
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_FALSE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
}
}
/*
=================
S_AL_SaveLoopPos
Remove given source as loop master if it is the master and hand off master status to another source in this case.
=================
*/
static void S_AL_SaveLoopPos(src_t *dest, ALuint alSource)
{
int error;
S_AL_ClearError( qfalse );
qalGetSourcef(alSource, AL_SEC_OFFSET, &dest->lastTimePos);
if((error = qalGetError()) != AL_NO_ERROR)
{
// Old OpenAL implementations don't support AL_SEC_OFFSET
if(error != AL_INVALID_ENUM)
{
Com_Printf(S_COLOR_YELLOW "WARNING: Could not get time offset for alSource %d: %s\n",
alSource, S_AL_ErrorMsg(error));
}
dest->lastTimePos = -1;
}
else
dest->lastSampleTime = Sys_Milliseconds();
}
/*
=================
S_AL_NewLoopMaster
Remove given source as loop master if it is the master and hand off master status to another source in this case.
=================
*/
static void S_AL_NewLoopMaster(src_t *rmSource, qboolean iskilled)
{
int index;
src_t *curSource = NULL;
alSfx_t *curSfx;
curSfx = &knownSfx[rmSource->sfx];
if(rmSource->isPlaying)
curSfx->loopActiveCnt--;
if(iskilled)
curSfx->loopCnt--;
if(curSfx->loopCnt)
{
if(rmSource->priority == SRCPRI_ENTITY)
{
if(!iskilled && rmSource->isPlaying)
{
// only sync ambient loops...
// It makes more sense to have sounds for weapons/projectiles unsynced
S_AL_SaveLoopPos(rmSource, rmSource->alSource);
}
}
else if(rmSource == &srcList[curSfx->masterLoopSrc])
{
int firstInactive = -1;
// Only if rmSource was the master and if there are still playing loops for
// this sound will we need to find a new master.
if(iskilled || curSfx->loopActiveCnt)
{
for(index = 0; index < srcCount; index++)
{
curSource = &srcList[index];
if(curSource->sfx == rmSource->sfx && curSource != rmSource &&
curSource->isActive && curSource->isLooping && curSource->priority == SRCPRI_AMBIENT)
{
if(curSource->isPlaying)
{
curSfx->masterLoopSrc = index;
break;
}
else if(firstInactive < 0)
firstInactive = index;
}
}
}
if(!curSfx->loopActiveCnt)
{
if(firstInactive < 0)
{
if(iskilled)
{
curSfx->masterLoopSrc = -1;
return;
}
else
curSource = rmSource;
}
else
curSource = &srcList[firstInactive];
if(rmSource->isPlaying)
{
// this was the last not stopped source, save last sample position + time
S_AL_SaveLoopPos(curSource, rmSource->alSource);
}
else
{
// second case: all loops using this sound have stopped due to listener being of of range,
// and now the inactive master gets deleted. Just move over the soundpos settings to the
// new master.
curSource->lastTimePos = rmSource->lastTimePos;
curSource->lastSampleTime = rmSource->lastSampleTime;
}
}
}
}
else
curSfx->masterLoopSrc = -1;
}
/*
=================
S_AL_SrcKill
=================
*/
static void S_AL_SrcKill(srcHandle_t src)
{
src_t *curSource = &srcList[src];
// I'm not touching it. Unlock it first.
if(curSource->isLocked)
return;
// Remove the entity association and loop master status
if(curSource->isLooping)
{
curSource->isLooping = qfalse;
if(curSource->entity != -1)
{
sentity_t *curEnt = &entityList[curSource->entity];
curEnt->srcAllocated = qfalse;
curEnt->srcIndex = -1;
curEnt->loopAddedThisFrame = qfalse;
curEnt->startLoopingSound = qfalse;
}
S_AL_NewLoopMaster(curSource, qtrue);
}
// Stop it if it's playing
if(curSource->isPlaying)
{
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
// Detach any buffers
qalSourcei(curSource->alSource, AL_BUFFER, 0);
curSource->sfx = 0;
curSource->lastUsedTime = 0;
curSource->priority = 0;
curSource->entity = -1;
curSource->channel = -1;
if(curSource->isActive)
{
curSource->isActive = qfalse;
srcActiveCnt--;
}
curSource->isLocked = qfalse;
curSource->isTracking = qfalse;
curSource->local = qfalse;
}
/*
=================
S_AL_SrcAlloc
=================
*/
static
srcHandle_t S_AL_SrcAlloc( sfxHandle_t sfx, alSrcPriority_t priority, int entnum, int channel, int flags )
{
int i;
int empty = -1;
int weakest = -1;
int weakest_time = Sys_Milliseconds();
int weakest_pri = 999;
float weakest_gain = 1000.0;
qboolean weakest_isplaying = qtrue;
int weakest_numloops = 0;
src_t *curSource;
qboolean cutDuplicateSound = qfalse;
for(i = 0; i < srcCount; i++)
{
curSource = &srcList[i];
// If it's locked, we aren't even going to look at it
if(curSource->isLocked)
continue;
// Is it empty or not?
if(!curSource->isActive)
{
if (empty == -1)
empty = i;
break;
}
if(curSource->isPlaying)
{
if(weakest_isplaying && curSource->priority < priority &&
(curSource->priority < weakest_pri ||
(!curSource->isLooping && (curSource->scaleGain < weakest_gain || curSource->lastUsedTime < weakest_time))))
{
// If it has lower priority, is fainter or older, flag it as weak
// the last two values are only compared if it's not a looping sound, because we want to prevent two
// loops (loops are added EVERY frame) fighting for a slot
weakest_pri = curSource->priority;
weakest_time = curSource->lastUsedTime;
weakest_gain = curSource->scaleGain;
weakest = i;
}
}
else
{
weakest_isplaying = qfalse;
if(weakest < 0 ||
knownSfx[curSource->sfx].loopCnt > weakest_numloops ||
curSource->priority < weakest_pri ||
curSource->lastUsedTime < weakest_time)
{
// Sources currently not playing of course have lowest priority
// also try to always keep at least one loop master for every loop sound
weakest_pri = curSource->priority;
weakest_time = curSource->lastUsedTime;
weakest_numloops = knownSfx[curSource->sfx].loopCnt;
weakest = i;
}
}
// shut off other sounds on this channel if necessary
if((curSource->entity == entnum) && curSource->sfx > 0 && (curSource->channel == channel))
{
// currently apply only to non-looping sounds
if ( curSource->isLooping ) {
continue;
}
// cutoff all on channel
if ( flags & SND_CUTOFF_ALL ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
if ( curSource->flags & SND_NOCUT ) {
continue;
}
// cutoff sounds that expect to be overwritten
if ( curSource->flags & SND_OKTOCUT ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
// cutoff 'weak' sounds on channel
if ( flags & SND_CUTOFF ) {
if ( curSource->flags & SND_REQUESTCUT ) {
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
}
// re-use channel if applicable
if ( curSource->channel != -1 && curSource->sfx == sfx && !cutDuplicateSound ) {
cutDuplicateSound = qtrue;
S_AL_SrcKill(i);
if (empty == -1)
empty = i;
continue;
}
}
}
if(empty == -1)
empty = weakest;
if(empty >= 0)
{
S_AL_SrcKill(empty);
srcList[empty].isActive = qtrue;
srcActiveCnt++;
}
return empty;
}
/*
=================
S_AL_SrcFind
Finds an active source with matching entity and channel numbers
Returns -1 if there isn't one
=================
*/
#if 0
static
srcHandle_t S_AL_SrcFind(int entnum, int channel)
{
int i;
for(i = 0; i < srcCount; i++)
{
if(!srcList[i].isActive)
continue;
if((srcList[i].entity == entnum) && (srcList[i].channel == channel))
return i;
}
return -1;
}
#endif
/*
=================
S_AL_SrcLock
Locked sources will not be automatically reallocated or managed
=================
*/
static
void S_AL_SrcLock(srcHandle_t src)
{
srcList[src].isLocked = qtrue;
}
/*
=================
S_AL_SrcUnlock
Once unlocked, the source may be reallocated again
=================
*/
static
void S_AL_SrcUnlock(srcHandle_t src)
{
srcList[src].isLocked = qfalse;
}
/*
=================
S_AL_UpdateEntityPosition
=================
*/
static
void S_AL_UpdateEntityPosition( int entityNum, const vec3_t origin )
{
vec3_t sanOrigin;
VectorCopy( origin, sanOrigin );
S_AL_SanitiseVector( sanOrigin );
if ( entityNum < 0 || entityNum >= MAX_GENTITIES )
Com_Error( ERR_DROP, "S_UpdateEntityPosition: bad entitynum %i", entityNum );
VectorCopy( sanOrigin, entityList[entityNum].origin );
}
/*
=================
S_AL_CheckInput
Check whether input values from mods are out of range.
Necessary for i.g. Western Quake3 mod which is buggy.
=================
*/
static qboolean S_AL_CheckInput(int entityNum, sfxHandle_t sfx)
{
if (entityNum < 0 || entityNum >= MAX_GENTITIES)
Com_Error(ERR_DROP, "ERROR: S_AL_CheckInput: bad entitynum %i", entityNum);
if (sfx < 0 || sfx >= numSfx)
{
Com_Printf(S_COLOR_RED "ERROR: S_AL_CheckInput: handle %i out of range\n", sfx);
return qtrue;
}
return qfalse;
}
/*
=================
S_AL_StartLocalSound
Play a local (non-spatialized) sound effect
=================
*/
static
void S_AL_StartLocalSound(sfxHandle_t sfx, int channel)
{
srcHandle_t src;
if(S_AL_CheckInput(0, sfx))
return;
// Try to grab a source
src = S_AL_SrcAlloc(sfx, SRCPRI_LOCAL, -1, channel, 0);
if(src == -1)
return;
// Set up the effect
S_AL_SrcSetup(src, sfx, SRCPRI_LOCAL, -1, channel, 0, qtrue);
// Start it playing
srcList[src].isPlaying = qtrue;
qalSourcePlay(srcList[src].alSource);
}
/*
=================
S_AL_MainStartSound
Play a one-shot sound effect
=================
*/
static void S_AL_MainStartSound( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx, int flags )
{
vec3_t sorigin;
srcHandle_t src;
src_t *curSource;
if(origin)
{
if(S_AL_CheckInput(0, sfx))
return;
VectorCopy(origin, sorigin);
}
else
{
if(S_AL_CheckInput(entnum, sfx))
return;
if(S_AL_HearingThroughEntity(entnum))
{
S_AL_StartLocalSound(sfx, entchannel);
return;
}
VectorCopy(entityList[entnum].origin, sorigin);
}
S_AL_SanitiseVector(sorigin);
if((srcActiveCnt > 5 * srcCount / 3) &&
(DistanceSquared(sorigin, lastListenerOrigin) >=
(s_alMaxDistance->value + s_alGraceDistance->value) * (s_alMaxDistance->value + s_alGraceDistance->value)))
{
// We're getting tight on sources and source is not within hearing distance so don't add it
return;
}
// Try to grab a source
src = S_AL_SrcAlloc(sfx, SRCPRI_ONESHOT, entnum, entchannel, flags);
if(src == -1)
return;
S_AL_SrcSetup(src, sfx, SRCPRI_ONESHOT, entnum, entchannel, flags, qfalse);
curSource = &srcList[src];
if(!origin)
curSource->isTracking = qtrue;
qalSourcefv(curSource->alSource, AL_POSITION, sorigin );
S_AL_ScaleGain(curSource, sorigin);
// Start it playing
curSource->isPlaying = qtrue;
qalSourcePlay(curSource->alSource);
}
/*
=================
S_AL_StartSound
=================
*/
static void S_AL_StartSound( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx )
{
S_AL_MainStartSound( origin, entnum, entchannel, sfx, 0 );
}
/*
=================
S_AL_StartSoundEx
=================
*/
static void S_AL_StartSoundEx( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx, int flags )
{
// RF, we have lots of NULL sounds using up valuable channels, so just ignore them
if ( !sfx && entchannel != CHAN_WEAPON ) { // let null weapon sounds try to play. they kill any weapon sounds playing when a guy dies
return;
}
// RF, make the call now, or else we could override following streaming sounds in the same frame, due to the delay
S_AL_MainStartSound( origin, entnum, entchannel, sfx, flags );
}
/*
=================
S_AL_ClearLoopingSounds
=================
*/
static
void S_AL_ClearLoopingSounds( qboolean killall )
{
int i;
for(i = 0; i < srcCount; i++)
{
if((srcList[i].isLooping) && (srcList[i].entity != -1))
entityList[srcList[i].entity].loopAddedThisFrame = qfalse;
}
}
/*
=================
S_AL_SrcLoop
=================
*/
static void S_AL_SrcLoop( alSrcPriority_t priority, sfxHandle_t sfx,
const vec3_t origin, const vec3_t velocity, int entityNum, int volume )
{
int src;
sentity_t *sent = &entityList[ entityNum ];
src_t *curSource;
vec3_t sorigin, svelocity;
if( entityNum < 0 || entityNum >= MAX_GENTITIES )
return;
if(S_AL_CheckInput(entityNum, sfx))
return;
// Do we need to allocate a new source for this entity
if( !sent->srcAllocated )
{
// Try to get a channel
src = S_AL_SrcAlloc( sfx, priority, entityNum, -1, 0 );
if( src == -1 )
{
Com_DPrintf( S_COLOR_YELLOW "WARNING: Failed to allocate source "
"for loop sfx %d on entity %d\n", sfx, entityNum );
return;
}
curSource = &srcList[src];
sent->startLoopingSound = qtrue;
curSource->lastTimePos = -1.0;
curSource->lastSampleTime = Sys_Milliseconds();
}
else
{
src = sent->srcIndex;
curSource = &srcList[src];
}
sent->srcAllocated = qtrue;
sent->srcIndex = src;
sent->loopPriority = priority;
sent->loopSfx = sfx;
// If this is not set then the looping sound is stopped.
sent->loopAddedThisFrame = qtrue;
// UGH
// These lines should be called via S_AL_SrcSetup, but we
// can't call that yet as it buffers sfxes that may change
// with subsequent calls to S_AL_SrcLoop
curSource->entity = entityNum;
curSource->isLooping = qtrue;
if( S_AL_HearingThroughEntity( entityNum ) )
{
curSource->local = qtrue;
VectorClear(sorigin);
if ( volume > 255 ) {
volume = 255;
} else if ( volume < 0 ) {
volume = 0;
}
qalSourcefv(curSource->alSource, AL_POSITION, sorigin);
qalSourcefv(curSource->alSource, AL_VELOCITY, vec3_origin);
S_AL_Gain(curSource->alSource, volume / 255.0f);
}
else
{
curSource->local = qfalse;
if(origin)
VectorCopy(origin, sorigin);
else
VectorCopy(sent->origin, sorigin);
S_AL_SanitiseVector(sorigin);
VectorCopy(sorigin, curSource->loopSpeakerPos);
if(velocity)
{
VectorCopy(velocity, svelocity);
S_AL_SanitiseVector(svelocity);
}
else
VectorClear(svelocity);
qalSourcefv(curSource->alSource, AL_POSITION, (ALfloat *) sorigin);
qalSourcefv(curSource->alSource, AL_VELOCITY, (ALfloat *) svelocity);
}
}
/*
=================
S_AL_AddLoopingSound
=================
*/
static void S_AL_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, const int range, sfxHandle_t sfx, int volume)
{
S_AL_SrcLoop(SRCPRI_ENTITY, sfx, origin, velocity, entityNum, volume);
}
/*
=================
S_AL_AddRealLoopingSound
=================
*/
static void S_AL_AddRealLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, const int range, sfxHandle_t sfx)
{
S_AL_SrcLoop(SRCPRI_AMBIENT, sfx, origin, velocity, entityNum, 255);
}
/*
=================
S_AL_StopLoopingSound
=================
*/
static
void S_AL_StopLoopingSound(int entityNum )
{
if(entityList[entityNum].srcAllocated)
S_AL_SrcKill(entityList[entityNum].srcIndex);
}
/*
=================
S_AL_SrcUpdate
Update state (move things around, manage sources, and so on)
=================
*/
static
void S_AL_SrcUpdate( void )
{
int i;
int entityNum;
ALint state;
src_t *curSource;
for(i = 0; i < srcCount; i++)
{
entityNum = srcList[i].entity;
curSource = &srcList[i];
if(curSource->isLocked)
continue;
if(!curSource->isActive)
continue;
// Update source parameters
if((s_alGain->modified) || (s_volume->modified))
curSource->curGain = s_alGain->value * s_volume->value;
if((s_alRolloff->modified) && (!curSource->local))
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
if(s_alMinDistance->modified)
qalSourcef(curSource->alSource, AL_REFERENCE_DISTANCE, s_alMinDistance->value);
if(curSource->isLooping)
{
sentity_t *sent = &entityList[ entityNum ];
// If a looping effect hasn't been touched this frame, pause or kill it
if(sent->loopAddedThisFrame)
{
alSfx_t *curSfx;
// The sound has changed without an intervening removal
if(curSource->isActive && !sent->startLoopingSound &&
curSource->sfx != sent->loopSfx)
{
S_AL_NewLoopMaster(curSource, qtrue);
curSource->isPlaying = qfalse;
qalSourceStop(curSource->alSource);
qalSourcei(curSource->alSource, AL_BUFFER, 0);
sent->startLoopingSound = qtrue;
}
// The sound hasn't been started yet
if(sent->startLoopingSound)
{
S_AL_SrcSetup(i, sent->loopSfx, sent->loopPriority,
entityNum, -1, 0, curSource->local);
curSource->isLooping = qtrue;
knownSfx[curSource->sfx].loopCnt++;
sent->startLoopingSound = qfalse;
}
curSfx = &knownSfx[curSource->sfx];
S_AL_ScaleGain(curSource, curSource->loopSpeakerPos);
if(!curSource->scaleGain)
{
if(curSource->isPlaying)
{
// Sound is mute, stop playback until we are in range again
S_AL_NewLoopMaster(curSource, qfalse);
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
else if(!curSfx->loopActiveCnt && curSfx->masterLoopSrc < 0)
curSfx->masterLoopSrc = i;
continue;
}
if(!curSource->isPlaying)
{
qalSourcei(curSource->alSource, AL_LOOPING, AL_TRUE);
curSource->isPlaying = qtrue;
qalSourcePlay(curSource->alSource);
if(curSource->priority == SRCPRI_AMBIENT)
{
// If there are other ambient looping sources with the same sound,
// make sure the sound of these sources are in sync.
if(curSfx->loopActiveCnt)
{
int offset, error;
// we already have a master loop playing, get buffer position.
S_AL_ClearError( qfalse );
qalGetSourcei(srcList[curSfx->masterLoopSrc].alSource, AL_SAMPLE_OFFSET, &offset);
if((error = qalGetError()) != AL_NO_ERROR)
{
if(error != AL_INVALID_ENUM)
{
Com_Printf(S_COLOR_YELLOW "WARNING: Cannot get sample offset from source %d: "
"%s\n", i, S_AL_ErrorMsg(error));
}
}
else
qalSourcei(curSource->alSource, AL_SAMPLE_OFFSET, offset);
}
else if(curSfx->loopCnt && curSfx->masterLoopSrc >= 0)
{
float secofs;
src_t *master = &srcList[curSfx->masterLoopSrc];
// This loop sound used to be played, but all sources are stopped. Use last sample position/time
// to calculate offset so the player thinks the sources continued playing while they were inaudible.
if(master->lastTimePos >= 0)
{
secofs = master->lastTimePos + (Sys_Milliseconds() - master->lastSampleTime) / 1000.0f;
secofs = fmodf(secofs, (float) curSfx->info.samples / curSfx->info.rate);
qalSourcef(curSource->alSource, AL_SEC_OFFSET, secofs);
}
// I be the master now
curSfx->masterLoopSrc = i;
}
else
curSfx->masterLoopSrc = i;
}
else if(curSource->lastTimePos >= 0)
{
float secofs;
// For unsynced loops (SRCPRI_ENTITY) just carry on playing as if the sound was never stopped
secofs = curSource->lastTimePos + (Sys_Milliseconds() - curSource->lastSampleTime) / 1000.0f;
secofs = fmodf(secofs, (float) curSfx->info.samples / curSfx->info.rate);
qalSourcef(curSource->alSource, AL_SEC_OFFSET, secofs);
}
curSfx->loopActiveCnt++;
}
// Update locality
if(curSource->local)
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_TRUE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, 0.0f);
}
else
{
qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_FALSE);
qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
}
}
else if(curSource->priority == SRCPRI_AMBIENT)
{
if(curSource->isPlaying)
{
S_AL_NewLoopMaster(curSource, qfalse);
qalSourceStop(curSource->alSource);
curSource->isPlaying = qfalse;
}
}
else
S_AL_SrcKill(i);
continue;
}
if(!curSource->isStream)
{
// Check if it's done, and flag it
qalGetSourcei(curSource->alSource, AL_SOURCE_STATE, &state);
if(state == AL_STOPPED)
{
curSource->isPlaying = qfalse;
S_AL_SrcKill(i);
continue;
}
}
// Query relativity of source, don't move if it's true
qalGetSourcei(curSource->alSource, AL_SOURCE_RELATIVE, &state);
// See if it needs to be moved
if(curSource->isTracking && !state)
{
qalSourcefv(curSource->alSource, AL_POSITION, entityList[entityNum].origin);
S_AL_ScaleGain(curSource, entityList[entityNum].origin);
}
}
}
/*
=================
S_AL_SrcShutup
=================
*/
static
void S_AL_SrcShutup( void )
{
int i;
for(i = 0; i < srcCount; i++)
S_AL_SrcKill(i);
}
/*
=================
S_AL_SrcGet
=================
*/
static
ALuint S_AL_SrcGet(srcHandle_t src)
{
return srcList[src].alSource;
}
//===========================================================================
// Q3A cinematics use up to 12 buffers at once
#define MAX_STREAM_BUFFERS 20
static srcHandle_t streamSourceHandles[MAX_RAW_STREAMS];
static qboolean streamPlaying[MAX_RAW_STREAMS];
static ALuint streamSources[MAX_RAW_STREAMS];
static ALuint streamBuffers[MAX_RAW_STREAMS][MAX_STREAM_BUFFERS];
static int streamNumBuffers[MAX_RAW_STREAMS];
static int streamBufIndex[MAX_RAW_STREAMS];
/*
=================
S_AL_AllocateStreamChannel
=================
*/
static void S_AL_AllocateStreamChannel(int stream, int entityNum)
{
srcHandle_t cursrc;
ALuint alsrc;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(entityNum >= 0)
{
// This is a stream that tracks an entity
// Allocate a streamSource at normal priority
cursrc = S_AL_SrcAlloc(-1, SRCPRI_ENTITY, entityNum, 0, 0);
if(cursrc < 0)
return;
S_AL_SrcSetup(cursrc, -1, SRCPRI_ENTITY, entityNum, 0, 0, qfalse);
alsrc = S_AL_SrcGet(cursrc);
srcList[cursrc].isTracking = qtrue;
srcList[cursrc].isStream = qtrue;
}
else
{
// Unspatialized stream source
// Allocate a streamSource at high priority
cursrc = S_AL_SrcAlloc(-1, SRCPRI_STREAM, -2, 0, 0);
if(cursrc < 0)
return;
alsrc = S_AL_SrcGet(cursrc);
// Lock the streamSource so nobody else can use it, and get the raw streamSource
S_AL_SrcLock(cursrc);
// make sure that after unmuting the S_AL_Gain in S_Update() does not turn
// volume up prematurely for this source
srcList[cursrc].scaleGain = 0.0f;
// Set some streamSource parameters
qalSourcei (alsrc, AL_BUFFER, 0 );
qalSourcei (alsrc, AL_LOOPING, AL_FALSE );
qalSource3f(alsrc, AL_POSITION, 0.0, 0.0, 0.0);
qalSource3f(alsrc, AL_VELOCITY, 0.0, 0.0, 0.0);
qalSource3f(alsrc, AL_DIRECTION, 0.0, 0.0, 0.0);
qalSourcef (alsrc, AL_ROLLOFF_FACTOR, 0.0 );
qalSourcei (alsrc, AL_SOURCE_RELATIVE, AL_TRUE );
}
streamSourceHandles[stream] = cursrc;
streamSources[stream] = alsrc;
streamNumBuffers[stream] = 0;
streamBufIndex[stream] = 0;
}
/*
=================
S_AL_FreeStreamChannel
=================
*/
static void S_AL_FreeStreamChannel( int stream )
{
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
// Detach any buffers
qalSourcei(streamSources[stream], AL_BUFFER, 0);
// Delete the buffers
if (streamNumBuffers[stream] > 0) {
qalDeleteBuffers(streamNumBuffers[stream], streamBuffers[stream]);
streamNumBuffers[stream] = 0;
}
// Release the output streamSource
S_AL_SrcUnlock(streamSourceHandles[stream]);
S_AL_SrcKill(streamSourceHandles[stream]);
streamSources[stream] = 0;
streamSourceHandles[stream] = -1;
}
/*
=================
S_AL_RawSamples
=================
*/
static
void S_AL_RawSamples(int stream, int samples, int rate, int width, int channels, const byte *data, float volume, int entityNum)
{
int numBuffers;
ALuint buffer;
ALuint format;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
format = S_AL_Format( width, channels );
// Create the streamSource if necessary
if(streamSourceHandles[stream] == -1)
{
S_AL_AllocateStreamChannel(stream, entityNum);
// Failed?
if(streamSourceHandles[stream] == -1)
{
Com_Printf( S_COLOR_RED "ERROR: Can't allocate streaming streamSource\n");
return;
}
}
qalGetSourcei(streamSources[stream], AL_BUFFERS_QUEUED, &numBuffers);
if (numBuffers == MAX_STREAM_BUFFERS)
{
Com_DPrintf(S_COLOR_RED"WARNING: Steam dropping raw samples, reached MAX_STREAM_BUFFERS\n");
return;
}
// Allocate a new AL buffer if needed
if (numBuffers == streamNumBuffers[stream])
{
ALuint oldBuffers[MAX_STREAM_BUFFERS];
int i;
if (!S_AL_GenBuffers(1, &buffer, "stream"))
return;
Com_Memcpy(oldBuffers, &streamBuffers[stream], sizeof (oldBuffers));
// Reorder buffer array in order of oldest to newest
for ( i = 0; i < streamNumBuffers[stream]; ++i )
streamBuffers[stream][i] = oldBuffers[(streamBufIndex[stream] + i) % streamNumBuffers[stream]];
// Add the new buffer to end
streamBuffers[stream][streamNumBuffers[stream]] = buffer;
streamBufIndex[stream] = streamNumBuffers[stream];
streamNumBuffers[stream]++;
}
// Select next buffer in loop
buffer = streamBuffers[stream][ streamBufIndex[stream] ];
streamBufIndex[stream] = (streamBufIndex[stream] + 1) % streamNumBuffers[stream];
// Fill buffer
qalBufferData(buffer, format, (ALvoid *)data, (samples * width * channels), rate);
// Shove the data onto the streamSource
qalSourceQueueBuffers(streamSources[stream], 1, &buffer);
if(entityNum < 0)
{
// Volume
S_AL_Gain (streamSources[stream], volume * s_volume->value * s_alGain->value);
}
// Start stream
if(!streamPlaying[stream])
{
qalSourcePlay( streamSources[stream] );
streamPlaying[stream] = qtrue;
}
}
/*
=================
S_AL_StreamUpdate
=================
*/
static
void S_AL_StreamUpdate( int stream )
{
int numBuffers;
ALint state;
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(streamSourceHandles[stream] == -1)
return;
// Un-queue any buffers
qalGetSourcei( streamSources[stream], AL_BUFFERS_PROCESSED, &numBuffers );
while( numBuffers-- )
{
ALuint buffer;
qalSourceUnqueueBuffers(streamSources[stream], 1, &buffer);
}
// Start the streamSource playing if necessary
qalGetSourcei( streamSources[stream], AL_BUFFERS_QUEUED, &numBuffers );
qalGetSourcei(streamSources[stream], AL_SOURCE_STATE, &state);
if(state == AL_STOPPED)
{
streamPlaying[stream] = qfalse;
// If there are no buffers queued up, release the streamSource
if( !numBuffers )
S_AL_FreeStreamChannel( stream );
}
if( !streamPlaying[stream] && numBuffers )
{
qalSourcePlay( streamSources[stream] );
streamPlaying[stream] = qtrue;
}
}
/*
=================
S_AL_StreamDie
=================
*/
static
void S_AL_StreamDie( int stream )
{
if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
return;
if(streamSourceHandles[stream] == -1)
return;
streamPlaying[stream] = qfalse;
qalSourceStop(streamSources[stream]);
S_AL_FreeStreamChannel(stream);
}
//===========================================================================
#define NUM_MUSIC_BUFFERS 4
#define MUSIC_BUFFER_SIZE 4096
static qboolean musicPlaying = qfalse;
static srcHandle_t musicSourceHandle = -1;
static ALuint musicSource;
static ALuint musicBuffers[NUM_MUSIC_BUFFERS];
static snd_stream_t *mus_stream;
static snd_stream_t *intro_stream;
static char s_backgroundLoop[MAX_QPATH];
static byte decode_buffer[MUSIC_BUFFER_SIZE];
/*
=================
S_AL_MusicSourceGet
=================
*/
static void S_AL_MusicSourceGet( void )
{
// Allocate a musicSource at high priority
musicSourceHandle = S_AL_SrcAlloc(-1, SRCPRI_STREAM, -2, 0, 0);
if(musicSourceHandle == -1)
return;
// Lock the musicSource so nobody else can use it, and get the raw musicSource
S_AL_SrcLock(musicSourceHandle);
musicSource = S_AL_SrcGet(musicSourceHandle);
// make sure that after unmuting the S_AL_Gain in S_Update() does not turn
// volume up prematurely for this source
srcList[musicSourceHandle].scaleGain = 0.0f;
// Set some musicSource parameters
qalSource3f(musicSource, AL_POSITION, 0.0, 0.0, 0.0);
qalSource3f(musicSource, AL_VELOCITY, 0.0, 0.0, 0.0);
qalSource3f(musicSource, AL_DIRECTION, 0.0, 0.0, 0.0);
qalSourcef (musicSource, AL_ROLLOFF_FACTOR, 0.0 );
qalSourcei (musicSource, AL_SOURCE_RELATIVE, AL_TRUE );
}
/*
=================
S_AL_MusicSourceFree
=================
*/
static void S_AL_MusicSourceFree( void )
{
// Release the output musicSource
S_AL_SrcUnlock(musicSourceHandle);
S_AL_SrcKill(musicSourceHandle);
musicSource = 0;
musicSourceHandle = -1;
}
/*
=================
S_AL_CloseMusicFiles
=================
*/
static void S_AL_CloseMusicFiles(void)
{
if(intro_stream)
{
S_CodecCloseStream(intro_stream);
intro_stream = NULL;
}
if(mus_stream)
{
S_CodecCloseStream(mus_stream);
mus_stream = NULL;
}
}
/*
=================
S_AL_StopBackgroundTrack
=================
*/
static
void S_AL_StopBackgroundTrack( void )
{
if(!musicPlaying)
return;
// Stop playing
qalSourceStop(musicSource);
// Detach any buffers
qalSourcei(musicSource, AL_BUFFER, 0);
// Delete the buffers
qalDeleteBuffers(NUM_MUSIC_BUFFERS, musicBuffers);
// Free the musicSource
S_AL_MusicSourceFree();
// Unload the stream
S_AL_CloseMusicFiles();
musicPlaying = qfalse;
}
/*
=================
S_AL_MusicProcess
=================
*/
static
void S_AL_MusicProcess(ALuint b)
{
ALenum error;
int l;
ALuint format;
snd_stream_t *curstream;
S_AL_ClearError( qfalse );
if(intro_stream)
curstream = intro_stream;
else
curstream = mus_stream;
if(!curstream)
return;
l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
// Run out data to read, start at the beginning again
if(l == 0)
{
S_CodecCloseStream(curstream);
// the intro stream just finished playing so we don't need to reopen
// the music stream.
if(intro_stream)
intro_stream = NULL;
else
mus_stream = S_CodecOpenStream(s_backgroundLoop);
curstream = mus_stream;
if(!curstream)
{
S_AL_StopBackgroundTrack();
return;
}
l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
}
format = S_AL_Format(curstream->info.width, curstream->info.channels);
if( l == 0 )
{
// We have no data to buffer, so buffer silence
byte dummyData[ 2 ] = { 0 };
qalBufferData( b, AL_FORMAT_MONO16, (void *)dummyData, 2, 22050 );
}
else
qalBufferData(b, format, decode_buffer, l, curstream->info.rate);
if( ( error = qalGetError( ) ) != AL_NO_ERROR )
{
S_AL_StopBackgroundTrack( );
Com_Printf( S_COLOR_RED "ERROR: while buffering data for music stream - %s\n",
S_AL_ErrorMsg( error ) );
return;
}
}
/*
=================
S_AL_StartBackgroundTrack
=================
*/
static
void S_AL_StartBackgroundTrack( const char *intro, const char *loop )
{
int i;
qboolean issame;
Com_DPrintf( "S_AL_StartBackgroundTrack( %s, %s )\n", intro, loop );
// Stop any existing music that might be playing
S_AL_StopBackgroundTrack();
if((!intro || !*intro) && (!loop || !*loop))
return;
// Allocate a musicSource
S_AL_MusicSourceGet();
if(musicSourceHandle == -1)
return;
if (!loop || !*loop)
{
loop = intro;
issame = qtrue;
}
else if(intro && *intro && !strcmp(intro, loop))
issame = qtrue;
else
issame = qfalse;
// Copy the loop over
Q_strncpyz( s_backgroundLoop, loop, sizeof( s_backgroundLoop ) );
if(!issame)
{
// Open the intro and don't mind whether it succeeds.
// The important part is the loop.
intro_stream = S_CodecOpenStream(intro);
}
else
intro_stream = NULL;
mus_stream = S_CodecOpenStream(s_backgroundLoop);
if(!mus_stream)
{
S_AL_CloseMusicFiles();
S_AL_MusicSourceFree();
return;
}
// Generate the musicBuffers
if (!S_AL_GenBuffers(NUM_MUSIC_BUFFERS, musicBuffers, "music"))
return;
// Queue the musicBuffers up
for(i = 0; i < NUM_MUSIC_BUFFERS; i++)
{
S_AL_MusicProcess(musicBuffers[i]);
}
qalSourceQueueBuffers(musicSource, NUM_MUSIC_BUFFERS, musicBuffers);
// Set the initial gain property
S_AL_Gain(musicSource, s_alGain->value * s_musicVolume->value);
// Start playing
qalSourcePlay(musicSource);
musicPlaying = qtrue;
}
/*
=================
S_AL_MusicUpdate
=================
*/
static
void S_AL_MusicUpdate( void )
{
int numBuffers;
ALint state;
if(!musicPlaying)
return;
qalGetSourcei( musicSource, AL_BUFFERS_PROCESSED, &numBuffers );
while( numBuffers-- )
{
ALuint b;
qalSourceUnqueueBuffers(musicSource, 1, &b);
S_AL_MusicProcess(b);
qalSourceQueueBuffers(musicSource, 1, &b);
}
// Hitches can cause OpenAL to be starved of buffers when streaming.
// If this happens, it will stop playback. This restarts the source if
// it is no longer playing, and if there are buffers available
qalGetSourcei( musicSource, AL_SOURCE_STATE, &state );
qalGetSourcei( musicSource, AL_BUFFERS_QUEUED, &numBuffers );
if( state == AL_STOPPED && numBuffers )
{
Com_DPrintf( S_COLOR_YELLOW "Restarted OpenAL music\n" );
qalSourcePlay(musicSource);
}
// Set the gain property
S_AL_Gain(musicSource, s_alGain->value * s_musicVolume->value);
}
/*
======================
S_StartStreamingSound
======================
*/
void S_AL_StartStreamingSound( const char *intro, const char *loop, int entnum, int channel, int attenuation ) {
// FIXME: Stub
}
/*
======================
S_GetVoiceAmplitude
======================
*/
int S_AL_GetVoiceAmplitude( int entityNum ) {
// FIXME: Stub
return 0;
}
//===========================================================================
// Local state variables
static ALCdevice *alDevice;
static ALCcontext *alContext;
#ifdef USE_VOIP
static ALCdevice *alCaptureDevice;
static cvar_t *s_alCapture;
#endif
#ifdef _WIN32
#define ALDRIVER_DEFAULT "OpenAL32.dll"
#elif defined(__APPLE__)
#define ALDRIVER_DEFAULT "libopenal.dylib"
#elif defined(__OpenBSD__)
#define ALDRIVER_DEFAULT "libopenal.so"
#else
#define ALDRIVER_DEFAULT "libopenal.so.1"
#endif
/*
=================
S_AL_ClearSoundBuffer
=================
*/
static
void S_AL_ClearSoundBuffer( void )
{
S_AL_SrcShutdown( );
S_AL_SrcInit( );
}
/*
=================
S_AL_StopAllSounds
=================
*/
static
void S_AL_StopAllSounds( void )
{
int i;
S_AL_SrcShutup();
S_AL_StopBackgroundTrack();
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamDie(i);
S_AL_ClearSoundBuffer();
}
/*
=================
S_AL_Respatialize
=================
*/
static
void S_AL_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], int inwater )
{
float orientation[6];
vec3_t sorigin;
VectorCopy( origin, sorigin );
S_AL_SanitiseVector( sorigin );
S_AL_SanitiseVector( axis[ 0 ] );
S_AL_SanitiseVector( axis[ 1 ] );
S_AL_SanitiseVector( axis[ 2 ] );
orientation[0] = axis[0][0]; orientation[1] = axis[0][1]; orientation[2] = axis[0][2];
orientation[3] = axis[2][0]; orientation[4] = axis[2][1]; orientation[5] = axis[2][2];
lastListenerNumber = entityNum;
VectorCopy( sorigin, lastListenerOrigin );
// Set OpenAL listener paramaters
qalListenerfv(AL_POSITION, (ALfloat *)sorigin);
qalListenerfv(AL_VELOCITY, vec3_origin);
qalListenerfv(AL_ORIENTATION, orientation);
}
/*
=================
S_AL_Update
=================
*/
static
void S_AL_Update( void )
{
int i;
if(s_muted->modified)
{
// muted state changed. Let S_AL_Gain turn up all sources again.
for(i = 0; i < srcCount; i++)
{
if(srcList[i].isActive)
S_AL_Gain(srcList[i].alSource, srcList[i].scaleGain);
}
s_muted->modified = qfalse;
}
// Update SFX channels
S_AL_SrcUpdate();
// Update streams
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamUpdate(i);
S_AL_MusicUpdate();
// Doppler
if(s_doppler->modified)
{
s_alDopplerFactor->modified = qtrue;
s_doppler->modified = qfalse;
}
// Doppler parameters
if(s_alDopplerFactor->modified)
{
if(s_doppler->integer)
qalDopplerFactor(s_alDopplerFactor->value);
else
qalDopplerFactor(0.0f);
s_alDopplerFactor->modified = qfalse;
}
if(s_alDopplerSpeed->modified)
{
qalSpeedOfSound(s_alDopplerSpeed->value);
s_alDopplerSpeed->modified = qfalse;
}
// Clear the modified flags on the other cvars
s_alGain->modified = qfalse;
s_volume->modified = qfalse;
s_musicVolume->modified = qfalse;
s_alMinDistance->modified = qfalse;
s_alRolloff->modified = qfalse;
}
/*
=================
S_AL_DisableSounds
=================
*/
static
void S_AL_DisableSounds( void )
{
S_AL_StopAllSounds();
}
/*
=================
S_AL_BeginRegistration
=================
*/
static
void S_AL_BeginRegistration( void )
{
if(!numSfx)
S_AL_BufferInit();
}
/*
=================
S_AL_SoundList
=================
*/
static
void S_AL_SoundList( void )
{
}
#ifdef USE_VOIP
static
void S_AL_StartCapture( void )
{
if (alCaptureDevice != NULL)
qalcCaptureStart(alCaptureDevice);
}
static
int S_AL_AvailableCaptureSamples( void )
{
int retval = 0;
if (alCaptureDevice != NULL)
{
ALint samples = 0;
qalcGetIntegerv(alCaptureDevice, ALC_CAPTURE_SAMPLES, sizeof (samples), &samples);
retval = (int) samples;
}
return retval;
}
static
void S_AL_Capture( int samples, byte *data )
{
if (alCaptureDevice != NULL)
qalcCaptureSamples(alCaptureDevice, data, samples);
}
void S_AL_StopCapture( void )
{
if (alCaptureDevice != NULL)
qalcCaptureStop(alCaptureDevice);
}
void S_AL_MasterGain( float gain )
{
qalListenerf(AL_GAIN, gain);
}
#endif
/*
=================
S_AL_SoundInfo
=================
*/
static void S_AL_SoundInfo(void)
{
Com_Printf( "OpenAL info:\n" );
Com_Printf( " Vendor: %s\n", qalGetString( AL_VENDOR ) );
Com_Printf( " Version: %s\n", qalGetString( AL_VERSION ) );
Com_Printf( " Renderer: %s\n", qalGetString( AL_RENDERER ) );
Com_Printf( " AL Extensions: %s\n", qalGetString( AL_EXTENSIONS ) );
Com_Printf( " ALC Extensions: %s\n", qalcGetString( alDevice, ALC_EXTENSIONS ) );
if(enumeration_all_ext)
Com_Printf(" Device: %s\n", qalcGetString(alDevice, ALC_ALL_DEVICES_SPECIFIER));
else if(enumeration_ext)
Com_Printf(" Device: %s\n", qalcGetString(alDevice, ALC_DEVICE_SPECIFIER));
if(enumeration_all_ext || enumeration_ext)
Com_Printf(" Available Devices:\n%s", s_alAvailableDevices->string);
#ifdef USE_VOIP
if(capture_ext)
{
#ifdef __APPLE__
Com_Printf(" Input Device: %s\n", qalcGetString(alCaptureDevice, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER));
#else
Com_Printf(" Input Device: %s\n", qalcGetString(alCaptureDevice, ALC_CAPTURE_DEVICE_SPECIFIER));
#endif
Com_Printf(" Available Input Devices:\n%s", s_alAvailableInputDevices->string);
}
#endif
}
/*
=================
S_AL_Shutdown
=================
*/
static
void S_AL_Shutdown( void )
{
// Shut down everything
int i;
for (i = 0; i < MAX_RAW_STREAMS; i++)
S_AL_StreamDie(i);
S_AL_StopBackgroundTrack( );
S_AL_SrcShutdown( );
S_AL_BufferShutdown( );
qalcDestroyContext(alContext);
qalcCloseDevice(alDevice);
#ifdef USE_VOIP
if (alCaptureDevice != NULL) {
qalcCaptureStop(alCaptureDevice);
qalcCaptureCloseDevice(alCaptureDevice);
alCaptureDevice = NULL;
Com_Printf( "OpenAL capture device closed.\n" );
}
#endif
for (i = 0; i < MAX_RAW_STREAMS; i++) {
streamSourceHandles[i] = -1;
streamPlaying[i] = qfalse;
streamSources[i] = 0;
}
QAL_Shutdown();
}
#endif
/*
=================
S_AL_Init
=================
*/
qboolean S_AL_Init( soundInterface_t *si )
{
#ifdef USE_OPENAL
const char* device = NULL;
const char* inputdevice = NULL;
int i;
if( !si ) {
return qfalse;
}
for (i = 0; i < MAX_RAW_STREAMS; i++) {
streamSourceHandles[i] = -1;
streamPlaying[i] = qfalse;
streamSources[i] = 0;
streamNumBuffers[i] = 0;
streamBufIndex[i] = 0;
}
// New console variables
s_alPrecache = Cvar_Get( "s_alPrecache", "1", CVAR_ARCHIVE );
s_alGain = Cvar_Get( "s_alGain", "1.0", CVAR_ARCHIVE );
s_alSources = Cvar_Get( "s_alSources", "128", CVAR_ARCHIVE );
s_alDopplerFactor = Cvar_Get( "s_alDopplerFactor", "1.0", CVAR_ARCHIVE );
s_alDopplerSpeed = Cvar_Get( "s_alDopplerSpeed", "9000", CVAR_ARCHIVE );
s_alMinDistance = Cvar_Get( "s_alMinDistance", "120", CVAR_CHEAT );
s_alMaxDistance = Cvar_Get("s_alMaxDistance", "1024", CVAR_CHEAT);
s_alRolloff = Cvar_Get( "s_alRolloff", "2", CVAR_CHEAT);
s_alGraceDistance = Cvar_Get("s_alGraceDistance", "512", CVAR_CHEAT);
s_alDriver = Cvar_Get( "s_alDriver", ALDRIVER_DEFAULT, CVAR_ARCHIVE | CVAR_LATCH );
s_alInputDevice = Cvar_Get( "s_alInputDevice", "", CVAR_ARCHIVE | CVAR_LATCH );
s_alDevice = Cvar_Get("s_alDevice", "", CVAR_ARCHIVE | CVAR_LATCH);
// Load QAL
if( !QAL_Init( s_alDriver->string ) )
{
#if defined( _WIN32 )
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) && !QAL_Init( "OpenAL64.dll" ) ) {
#elif defined ( __APPLE__ )
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) && !QAL_Init( "/System/Library/Frameworks/OpenAL.framework/OpenAL" ) ) {
#else
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) || !QAL_Init( ALDRIVER_DEFAULT ) ) {
#endif
return qfalse;
}
}
device = s_alDevice->string;
if(device && !*device)
device = NULL;
inputdevice = s_alInputDevice->string;
if(inputdevice && !*inputdevice)
inputdevice = NULL;
// Device enumeration support
enumeration_all_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT");
enumeration_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT");
if(enumeration_ext || enumeration_all_ext)
{
char devicenames[16384] = "";
const char *devicelist;
#ifdef _WIN32
const char *defaultdevice;
#endif
int curlen;
// get all available devices + the default device name.
if(enumeration_all_ext)
{
devicelist = qalcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_ALL_DEVICES_SPECIFIER);
#endif
}
else
{
// We don't have ALC_ENUMERATE_ALL_EXT but normal enumeration.
devicelist = qalcGetString(NULL, ALC_DEVICE_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
#endif
enumeration_ext = qtrue;
}
#ifdef _WIN32
// check whether the default device is generic hardware. If it is, change to
// Generic Software as that one works more reliably with various sound systems.
// If it's not, use OpenAL's default selection as we don't want to ignore
// native hardware acceleration.
if(!device && defaultdevice && !strcmp(defaultdevice, "Generic Hardware"))
device = "Generic Software";
#endif
// dump a list of available devices to a cvar for the user to see.
if(devicelist)
{
while((curlen = strlen(devicelist)))
{
Q_strcat(devicenames, sizeof(devicenames), devicelist);
Q_strcat(devicenames, sizeof(devicenames), "\n");
devicelist += curlen + 1;
}
}
s_alAvailableDevices = Cvar_Get("s_alAvailableDevices", devicenames, CVAR_ROM | CVAR_NORESTART);
}
alDevice = qalcOpenDevice(device);
if( !alDevice && device )
{
Com_Printf( "Failed to open OpenAL device '%s', trying default.\n", device );
alDevice = qalcOpenDevice(NULL);
}
if( !alDevice )
{
QAL_Shutdown( );
Com_Printf( "Failed to open OpenAL device.\n" );
return qfalse;
}
// Create OpenAL context
alContext = qalcCreateContext( alDevice, NULL );
if( !alContext )
{
QAL_Shutdown( );
qalcCloseDevice( alDevice );
Com_Printf( "Failed to create OpenAL context.\n" );
return qfalse;
}
qalcMakeContextCurrent( alContext );
// Initialize sources, buffers, music
S_AL_BufferInit( );
S_AL_SrcInit( );
// Print this for informational purposes
Com_Printf( "Allocated %d sources.\n", srcCount);
// Set up OpenAL parameters (doppler, etc)
qalDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
qalDopplerFactor( s_alDopplerFactor->value );
qalSpeedOfSound( s_alDopplerSpeed->value );
#ifdef USE_VOIP
// !!! FIXME: some of these alcCaptureOpenDevice() values should be cvars.
// !!! FIXME: add support for capture device enumeration.
// !!! FIXME: add some better error reporting.
s_alCapture = Cvar_Get( "s_alCapture", "1", CVAR_ARCHIVE | CVAR_LATCH );
if (!s_alCapture->integer)
{
Com_Printf("OpenAL capture support disabled by user ('+set s_alCapture 1' to enable)\n");
}
#if USE_MUMBLE
else if (cl_useMumble->integer)
{
Com_Printf("OpenAL capture support disabled for Mumble support\n");
}
#endif
else
{
#ifdef __APPLE__
// !!! FIXME: Apple has a 1.1-compliant OpenAL, which includes
// !!! FIXME: capture support, but they don't list it in the
// !!! FIXME: extension string. We need to check the version string,
// !!! FIXME: then the extension string, but that's too much trouble,
// !!! FIXME: so we'll just check the function pointer for now.
if (qalcCaptureOpenDevice == NULL)
#else
if (!qalcIsExtensionPresent(NULL, "ALC_EXT_capture"))
#endif
{
Com_Printf("No ALC_EXT_capture support, can't record audio.\n");
}
else
{
char inputdevicenames[16384] = "";
const char *inputdevicelist;
const char *defaultinputdevice;
int curlen;
capture_ext = qtrue;
// get all available input devices + the default input device name.
inputdevicelist = qalcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER);
defaultinputdevice = qalcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
// dump a list of available devices to a cvar for the user to see.
if (inputdevicelist)
{
while((curlen = strlen(inputdevicelist)))
{
Q_strcat(inputdevicenames, sizeof(inputdevicenames), inputdevicelist);
Q_strcat(inputdevicenames, sizeof(inputdevicenames), "\n");
inputdevicelist += curlen + 1;
}
}
s_alAvailableInputDevices = Cvar_Get("s_alAvailableInputDevices", inputdevicenames, CVAR_ROM | CVAR_NORESTART);
Com_Printf("OpenAL default capture device is '%s'\n", defaultinputdevice ? defaultinputdevice : "none");
alCaptureDevice = qalcCaptureOpenDevice(inputdevice, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
if( !alCaptureDevice && inputdevice )
{
Com_Printf( "Failed to open OpenAL Input device '%s', trying default.\n", inputdevice );
alCaptureDevice = qalcCaptureOpenDevice(NULL, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
}
Com_Printf( "OpenAL capture device %s.\n",
(alCaptureDevice == NULL) ? "failed to open" : "opened");
}
}
#endif
si->Shutdown = S_AL_Shutdown;
si->StartSound = S_AL_StartSound;
si->StartSoundEx = S_AL_StartSoundEx;
si->StartLocalSound = S_AL_StartLocalSound;
si->StartBackgroundTrack = S_AL_StartBackgroundTrack;
si->StopBackgroundTrack = S_AL_StopBackgroundTrack;
si->StartStreamingSound = S_AL_StartStreamingSound;
si->GetVoiceAmplitude = S_AL_GetVoiceAmplitude;
si->RawSamples = S_AL_RawSamples;
si->StopAllSounds = S_AL_StopAllSounds;
si->ClearLoopingSounds = S_AL_ClearLoopingSounds;
si->AddLoopingSound = S_AL_AddLoopingSound;
si->AddRealLoopingSound = S_AL_AddRealLoopingSound;
si->StopLoopingSound = S_AL_StopLoopingSound;
si->Respatialize = S_AL_Respatialize;
si->UpdateEntityPosition = S_AL_UpdateEntityPosition;
si->Update = S_AL_Update;
si->DisableSounds = S_AL_DisableSounds;
si->BeginRegistration = S_AL_BeginRegistration;
si->RegisterSound = S_AL_RegisterSound;
si->ClearSoundBuffer = S_AL_ClearSoundBuffer;
si->SoundInfo = S_AL_SoundInfo;
si->SoundList = S_AL_SoundList;
#ifdef USE_VOIP
si->StartCapture = S_AL_StartCapture;
si->AvailableCaptureSamples = S_AL_AvailableCaptureSamples;
si->Capture = S_AL_Capture;
si->StopCapture = S_AL_StopCapture;
si->MasterGain = S_AL_MasterGain;
#endif
return qtrue;
#else
return qfalse;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3232_0 |
crossvul-cpp_data_bad_3152_2 | /*
* Copyright (C) 2014-2016 Firejail Authors
*
* This file is part of firejail 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#define _XOPEN_SOURCE 500
#include "firejail.h"
#include <ftw.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <syslog.h>
#include <errno.h>
#include <dirent.h>
#include <grp.h>
#include <sys/ioctl.h>
#include <termios.h>
#define MAX_GROUPS 1024
// drop privileges
// - for root group or if nogroups is set, supplementary groups are not configured
void drop_privs(int nogroups) {
EUID_ROOT();
gid_t gid = getgid();
// configure supplementary groups
if (gid == 0 || nogroups) {
if (setgroups(0, NULL) < 0)
errExit("setgroups");
if (arg_debug)
printf("Username %s, no supplementary groups\n", cfg.username);
}
else {
assert(cfg.username);
gid_t groups[MAX_GROUPS];
int ngroups = MAX_GROUPS;
int rv = getgrouplist(cfg.username, gid, groups, &ngroups);
if (arg_debug && rv) {
printf("Username %s, groups ", cfg.username);
int i;
for (i = 0; i < ngroups; i++)
printf("%u, ", groups[i]);
printf("\n");
}
if (rv == -1) {
fprintf(stderr, "Warning: cannot extract supplementary group list, dropping them\n");
if (setgroups(0, NULL) < 0)
errExit("setgroups");
}
else {
rv = setgroups(ngroups, groups);
if (rv) {
fprintf(stderr, "Warning: cannot set supplementary group list, dropping them\n");
if (setgroups(0, NULL) < 0)
errExit("setgroups");
}
}
}
// set uid/gid
if (setgid(getgid()) < 0)
errExit("setgid/getgid");
if (setuid(getuid()) < 0)
errExit("setuid/getuid");
}
int mkpath_as_root(const char* path) {
assert(path && *path);
// work on a copy of the path
char *file_path = strdup(path);
if (!file_path)
errExit("strdup");
char* p;
int done = 0;
for (p=strchr(file_path+1, '/'); p; p=strchr(p+1, '/')) {
*p='\0';
if (mkdir(file_path, 0755)==-1) {
if (errno != EEXIST) {
*p='/';
free(file_path);
return -1;
}
}
else {
if (chmod(file_path, 0755) == -1)
errExit("chmod");
if (chown(file_path, 0, 0) == -1)
errExit("chown");
done = 1;
}
*p='/';
}
if (done)
fs_logger2("mkpath", path);
free(file_path);
return 0;
}
void logsignal(int s) {
if (!arg_debug)
return;
openlog("firejail", LOG_NDELAY | LOG_PID, LOG_USER);
syslog(LOG_INFO, "Signal %d caught", s);
closelog();
}
void logmsg(const char *msg) {
if (!arg_debug)
return;
openlog("firejail", LOG_NDELAY | LOG_PID, LOG_USER);
syslog(LOG_INFO, "%s\n", msg);
closelog();
}
void logargs(int argc, char **argv) {
if (!arg_debug)
return;
int i;
int len = 0;
// calculate message length
for (i = 0; i < argc; i++)
len += strlen(argv[i]) + 1; // + ' '
// build message
char msg[len + 1];
char *ptr = msg;
for (i = 0; i < argc; i++) {
sprintf(ptr, "%s ", argv[i]);
ptr += strlen(ptr);
}
// log message
logmsg(msg);
}
void logerr(const char *msg) {
if (!arg_debug)
return;
openlog("firejail", LOG_NDELAY | LOG_PID, LOG_USER);
syslog(LOG_ERR, "%s\n", msg);
closelog();
}
// return -1 if error, 0 if no error
int copy_file(const char *srcname, const char *destname, uid_t uid, gid_t gid, mode_t mode) {
assert(srcname);
assert(destname);
// open source
int src = open(srcname, O_RDONLY);
if (src < 0) {
fprintf(stderr, "Warning: cannot open %s, file not copied\n", srcname);
return -1;
}
// open destination
int dst = open(destname, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (dst < 0) {
fprintf(stderr, "Warning: cannot open %s, file not copied\n", destname);
close(src);
return -1;
}
// copy
ssize_t len;
static const int BUFLEN = 1024;
unsigned char buf[BUFLEN];
while ((len = read(src, buf, BUFLEN)) > 0) {
int done = 0;
while (done != len) {
int rv = write(dst, buf + done, len - done);
if (rv == -1) {
close(src);
close(dst);
return -1;
}
done += rv;
}
}
if (fchown(dst, uid, gid) == -1)
errExit("fchown");
if (fchmod(dst, mode) == -1)
errExit("fchmod");
close(src);
close(dst);
return 0;
}
// return 1 if the file is a directory
int is_dir(const char *fname) {
assert(fname);
if (*fname == '\0')
return 0;
// if fname doesn't end in '/', add one
int rv;
struct stat s;
if (fname[strlen(fname) - 1] == '/')
rv = stat(fname, &s);
else {
char *tmp;
if (asprintf(&tmp, "%s/", fname) == -1) {
fprintf(stderr, "Error: cannot allocate memory, %s:%d\n", __FILE__, __LINE__);
errExit("asprintf");
}
rv = stat(tmp, &s);
free(tmp);
}
if (rv == -1)
return 0;
if (S_ISDIR(s.st_mode))
return 1;
return 0;
}
// return 1 if the file is a link
int is_link(const char *fname) {
assert(fname);
if (*fname == '\0')
return 0;
struct stat s;
if (lstat(fname, &s) == 0) {
if (S_ISLNK(s.st_mode))
return 1;
}
return 0;
}
// remove multiple spaces and return allocated memory
char *line_remove_spaces(const char *buf) {
EUID_ASSERT();
assert(buf);
if (strlen(buf) == 0)
return NULL;
// allocate memory for the new string
char *rv = malloc(strlen(buf) + 1);
if (rv == NULL)
errExit("malloc");
// remove space at start of line
const char *ptr1 = buf;
while (*ptr1 == ' ' || *ptr1 == '\t')
ptr1++;
// copy data and remove additional spaces
char *ptr2 = rv;
int state = 0;
while (*ptr1 != '\0') {
if (*ptr1 == '\n' || *ptr1 == '\r')
break;
if (state == 0) {
if (*ptr1 != ' ' && *ptr1 != '\t')
*ptr2++ = *ptr1++;
else {
*ptr2++ = ' ';
ptr1++;
state = 1;
}
}
else { // state == 1
while (*ptr1 == ' ' || *ptr1 == '\t')
ptr1++;
state = 0;
}
}
// strip last blank character if any
if (ptr2 > rv && *(ptr2 - 1) == ' ')
--ptr2;
*ptr2 = '\0';
// if (arg_debug)
// printf("Processing line #%s#\n", rv);
return rv;
}
char *split_comma(char *str) {
EUID_ASSERT();
if (str == NULL || *str == '\0')
return NULL;
char *ptr = strchr(str, ',');
if (!ptr)
return NULL;
*ptr = '\0';
ptr++;
if (*ptr == '\0')
return NULL;
return ptr;
}
int not_unsigned(const char *str) {
EUID_ASSERT();
int rv = 0;
const char *ptr = str;
while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0') {
if (!isdigit(*ptr)) {
rv = 1;
break;
}
ptr++;
}
return rv;
}
#define BUFLEN 4096
// find the first child for this parent; return 1 if error
int find_child(pid_t parent, pid_t *child) {
EUID_ASSERT();
*child = 0; // use it to flag a found child
DIR *dir;
EUID_ROOT(); // grsecurity fix
if (!(dir = opendir("/proc"))) {
// sleep 2 seconds and try again
sleep(2);
if (!(dir = opendir("/proc"))) {
fprintf(stderr, "Error: cannot open /proc directory\n");
exit(1);
}
}
struct dirent *entry;
char *end;
while (*child == 0 && (entry = readdir(dir))) {
pid_t pid = strtol(entry->d_name, &end, 10);
if (end == entry->d_name || *end)
continue;
if (pid == parent)
continue;
// open stat file
char *file;
if (asprintf(&file, "/proc/%u/status", pid) == -1) {
perror("asprintf");
exit(1);
}
FILE *fp = fopen(file, "r");
if (!fp) {
free(file);
continue;
}
// look for firejail executable name
char buf[BUFLEN];
while (fgets(buf, BUFLEN - 1, fp)) {
if (strncmp(buf, "PPid:", 5) == 0) {
char *ptr = buf + 5;
while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t')) {
ptr++;
}
if (*ptr == '\0') {
fprintf(stderr, "Error: cannot read /proc file\n");
exit(1);
}
if (parent == atoi(ptr))
*child = pid;
break; // stop reading the file
}
}
fclose(fp);
free(file);
}
closedir(dir);
EUID_USER();
return (*child)? 0:1; // 0 = found, 1 = not found
}
void extract_command_name(int index, char **argv) {
EUID_ASSERT();
assert(argv);
assert(argv[index]);
// configure command index
cfg.original_program_index = index;
char *str = strdup(argv[index]);
if (!str)
errExit("strdup");
// if we have a symbolic link, use the real path to extract the name
// if (is_link(argv[index])) {
// char*newname = realpath(argv[index], NULL);
// if (newname) {
// free(str);
// str = newname;
// }
// }
// configure command name
cfg.command_name = str;
if (!cfg.command_name)
errExit("strdup");
// restrict the command name to the first word
char *ptr = cfg.command_name;
while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0')
ptr++;
*ptr = '\0';
// remove the path: /usr/bin/firefox becomes firefox
ptr = strrchr(cfg.command_name, '/');
if (ptr) {
ptr++;
if (*ptr == '\0') {
fprintf(stderr, "Error: invalid command name\n");
exit(1);
}
char *tmp = strdup(ptr);
if (!tmp)
errExit("strdup");
// limit the command to the first '.'
char *ptr2 = tmp;
while (*ptr2 != '.' && *ptr2 != '\0')
ptr2++;
*ptr2 = '\0';
free(cfg.command_name);
cfg.command_name = tmp;
}
}
void update_map(char *mapping, char *map_file) {
int fd;
size_t j;
size_t map_len; /* Length of 'mapping' */
/* Replace commas in mapping string with newlines */
map_len = strlen(mapping);
for (j = 0; j < map_len; j++)
if (mapping[j] == ',')
mapping[j] = '\n';
fd = open(map_file, O_RDWR);
if (fd == -1) {
fprintf(stderr, "Error: cannot open %s: %s\n", map_file, strerror(errno));
exit(EXIT_FAILURE);
}
if (write(fd, mapping, map_len) != (ssize_t)map_len) {
fprintf(stderr, "Error: cannot write to %s: %s\n", map_file, strerror(errno));
exit(EXIT_FAILURE);
}
close(fd);
}
void wait_for_other(int fd) {
//****************************
// wait for the parent to be initialized
//****************************
char childstr[BUFLEN + 1];
int newfd = dup(fd);
if (newfd == -1)
errExit("dup");
FILE* stream;
stream = fdopen(newfd, "r");
*childstr = '\0';
if (fgets(childstr, BUFLEN, stream)) {
// remove \n)
char *ptr = childstr;
while(*ptr !='\0' && *ptr != '\n')
ptr++;
if (*ptr == '\0')
errExit("fgets");
*ptr = '\0';
}
else {
fprintf(stderr, "Error: cannot establish communication with the parent, exiting...\n");
exit(1);
}
if (strcmp(childstr, "arg_noroot=0") == 0)
arg_noroot = 0;
fclose(stream);
}
void notify_other(int fd) {
FILE* stream;
int newfd = dup(fd);
if (newfd == -1)
errExit("dup");
stream = fdopen(newfd, "w");
fprintf(stream, "arg_noroot=%d\n", arg_noroot);
fflush(stream);
fclose(stream);
}
// This function takes a pathname supplied by the user and expands '~' and
// '${HOME}' at the start, to refer to a path relative to the user's home
// directory (supplied).
// The return value is allocated using malloc and must be freed by the caller.
// The function returns NULL if there are any errors.
char *expand_home(const char *path, const char* homedir) {
assert(path);
assert(homedir);
// Replace home macro
char *new_name = NULL;
if (strncmp(path, "${HOME}", 7) == 0) {
if (asprintf(&new_name, "%s%s", homedir, path + 7) == -1)
errExit("asprintf");
return new_name;
}
else if (*path == '~') {
if (asprintf(&new_name, "%s%s", homedir, path + 1) == -1)
errExit("asprintf");
return new_name;
}
return strdup(path);
}
// Equivalent to the GNU version of basename, which is incompatible with
// the POSIX basename. A few lines of code saves any portability pain.
// https://www.gnu.org/software/libc/manual/html_node/Finding-Tokens-in-a-String.html#index-basename
const char *gnu_basename(const char *path) {
const char *last_slash = strrchr(path, '/');
if (!last_slash)
return path;
return last_slash+1;
}
uid_t pid_get_uid(pid_t pid) {
EUID_ASSERT();
uid_t rv = 0;
// open status file
char *file;
if (asprintf(&file, "/proc/%u/status", pid) == -1) {
perror("asprintf");
exit(1);
}
EUID_ROOT(); // grsecurity fix
FILE *fp = fopen(file, "r");
if (!fp) {
free(file);
fprintf(stderr, "Error: cannot open /proc file\n");
exit(1);
}
// extract uid
static const int PIDS_BUFLEN = 1024;
char buf[PIDS_BUFLEN];
while (fgets(buf, PIDS_BUFLEN - 1, fp)) {
if (strncmp(buf, "Uid:", 4) == 0) {
char *ptr = buf + 5;
while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t')) {
ptr++;
}
if (*ptr == '\0')
break;
rv = atoi(ptr);
break; // break regardless!
}
}
fclose(fp);
free(file);
EUID_USER(); // grsecurity fix
if (rv == 0) {
fprintf(stderr, "Error: cannot read /proc file\n");
exit(1);
}
return rv;
}
void invalid_filename(const char *fname) {
EUID_ASSERT();
assert(fname);
const char *ptr = fname;
if (arg_debug_check_filename)
printf("Checking filename %s\n", fname);
if (strncmp(ptr, "${HOME}", 7) == 0)
ptr = fname + 7;
else if (strncmp(ptr, "${PATH}", 7) == 0)
ptr = fname + 7;
else if (strcmp(fname, "${DOWNLOADS}") == 0)
return;
int len = strlen(ptr);
// file globbing ('*') is allowed
if (strcspn(ptr, "\\&!?\"'<>%^(){}[];,") != (size_t)len) {
fprintf(stderr, "Error: \"%s\" is an invalid filename\n", ptr);
exit(1);
}
}
uid_t get_group_id(const char *group) {
// find tty group id
gid_t gid = 0;
struct group *g = getgrnam(group);
if (g)
gid = g->gr_gid;
return gid;
}
static int remove_callback(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
(void) sb;
(void) typeflag;
(void) ftwbuf;
int rv = remove(fpath);
if (rv)
perror(fpath);
return rv;
}
int remove_directory(const char *path) {
// FTW_PHYS - do not follow symbolic links
return nftw(path, remove_callback, 64, FTW_DEPTH | FTW_PHYS);
}
void flush_stdin(void) {
if (isatty(STDIN_FILENO)) {
int cnt = 0;
ioctl(STDIN_FILENO, FIONREAD, &cnt);
if (cnt) {
if (!arg_quiet)
printf("Warning: removing %d bytes from stdin\n", cnt);
ioctl(STDIN_FILENO, TCFLSH, TCIFLUSH);
}
}
}
// return 1 if error
int set_perms(const char *fname, uid_t uid, gid_t gid, mode_t mode) {
assert(fname);
if (chmod(fname, mode) == -1)
return 1;
if (chown(fname, uid, gid) == -1)
return 1;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3152_2 |
crossvul-cpp_data_good_2887_0 | /* $OpenBSD: sftp-server.c,v 1.111 2017/04/04 00:24:56 djm Exp $ */
/*
* Copyright (c) 2000-2004 Markus Friedl. All rights reserved.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/mount.h>
#include <sys/statvfs.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pwd.h>
#include <time.h>
#include <unistd.h>
#include <stdarg.h>
#include "xmalloc.h"
#include "sshbuf.h"
#include "ssherr.h"
#include "log.h"
#include "misc.h"
#include "match.h"
#include "uidswap.h"
#include "sftp.h"
#include "sftp-common.h"
/* Our verbosity */
static LogLevel log_level = SYSLOG_LEVEL_ERROR;
/* Our client */
static struct passwd *pw = NULL;
static char *client_addr = NULL;
/* input and output queue */
struct sshbuf *iqueue;
struct sshbuf *oqueue;
/* Version of client */
static u_int version;
/* SSH2_FXP_INIT received */
static int init_done;
/* Disable writes */
static int readonly;
/* Requests that are allowed/denied */
static char *request_whitelist, *request_blacklist;
/* portable attributes, etc. */
typedef struct Stat Stat;
struct Stat {
char *name;
char *long_name;
Attrib attrib;
};
/* Packet handlers */
static void process_open(u_int32_t id);
static void process_close(u_int32_t id);
static void process_read(u_int32_t id);
static void process_write(u_int32_t id);
static void process_stat(u_int32_t id);
static void process_lstat(u_int32_t id);
static void process_fstat(u_int32_t id);
static void process_setstat(u_int32_t id);
static void process_fsetstat(u_int32_t id);
static void process_opendir(u_int32_t id);
static void process_readdir(u_int32_t id);
static void process_remove(u_int32_t id);
static void process_mkdir(u_int32_t id);
static void process_rmdir(u_int32_t id);
static void process_realpath(u_int32_t id);
static void process_rename(u_int32_t id);
static void process_readlink(u_int32_t id);
static void process_symlink(u_int32_t id);
static void process_extended_posix_rename(u_int32_t id);
static void process_extended_statvfs(u_int32_t id);
static void process_extended_fstatvfs(u_int32_t id);
static void process_extended_hardlink(u_int32_t id);
static void process_extended_fsync(u_int32_t id);
static void process_extended(u_int32_t id);
struct sftp_handler {
const char *name; /* user-visible name for fine-grained perms */
const char *ext_name; /* extended request name */
u_int type; /* packet type, for non extended packets */
void (*handler)(u_int32_t);
int does_write; /* if nonzero, banned for readonly mode */
};
struct sftp_handler handlers[] = {
/* NB. SSH2_FXP_OPEN does the readonly check in the handler itself */
{ "open", NULL, SSH2_FXP_OPEN, process_open, 0 },
{ "close", NULL, SSH2_FXP_CLOSE, process_close, 0 },
{ "read", NULL, SSH2_FXP_READ, process_read, 0 },
{ "write", NULL, SSH2_FXP_WRITE, process_write, 1 },
{ "lstat", NULL, SSH2_FXP_LSTAT, process_lstat, 0 },
{ "fstat", NULL, SSH2_FXP_FSTAT, process_fstat, 0 },
{ "setstat", NULL, SSH2_FXP_SETSTAT, process_setstat, 1 },
{ "fsetstat", NULL, SSH2_FXP_FSETSTAT, process_fsetstat, 1 },
{ "opendir", NULL, SSH2_FXP_OPENDIR, process_opendir, 0 },
{ "readdir", NULL, SSH2_FXP_READDIR, process_readdir, 0 },
{ "remove", NULL, SSH2_FXP_REMOVE, process_remove, 1 },
{ "mkdir", NULL, SSH2_FXP_MKDIR, process_mkdir, 1 },
{ "rmdir", NULL, SSH2_FXP_RMDIR, process_rmdir, 1 },
{ "realpath", NULL, SSH2_FXP_REALPATH, process_realpath, 0 },
{ "stat", NULL, SSH2_FXP_STAT, process_stat, 0 },
{ "rename", NULL, SSH2_FXP_RENAME, process_rename, 1 },
{ "readlink", NULL, SSH2_FXP_READLINK, process_readlink, 0 },
{ "symlink", NULL, SSH2_FXP_SYMLINK, process_symlink, 1 },
{ NULL, NULL, 0, NULL, 0 }
};
/* SSH2_FXP_EXTENDED submessages */
struct sftp_handler extended_handlers[] = {
{ "posix-rename", "posix-rename@openssh.com", 0,
process_extended_posix_rename, 1 },
{ "statvfs", "statvfs@openssh.com", 0, process_extended_statvfs, 0 },
{ "fstatvfs", "fstatvfs@openssh.com", 0, process_extended_fstatvfs, 0 },
{ "hardlink", "hardlink@openssh.com", 0, process_extended_hardlink, 1 },
{ "fsync", "fsync@openssh.com", 0, process_extended_fsync, 1 },
{ NULL, NULL, 0, NULL, 0 }
};
static int
request_permitted(struct sftp_handler *h)
{
char *result;
if (readonly && h->does_write) {
verbose("Refusing %s request in read-only mode", h->name);
return 0;
}
if (request_blacklist != NULL &&
((result = match_list(h->name, request_blacklist, NULL))) != NULL) {
free(result);
verbose("Refusing blacklisted %s request", h->name);
return 0;
}
if (request_whitelist != NULL &&
((result = match_list(h->name, request_whitelist, NULL))) != NULL) {
free(result);
debug2("Permitting whitelisted %s request", h->name);
return 1;
}
if (request_whitelist != NULL) {
verbose("Refusing non-whitelisted %s request", h->name);
return 0;
}
return 1;
}
static int
errno_to_portable(int unixerrno)
{
int ret = 0;
switch (unixerrno) {
case 0:
ret = SSH2_FX_OK;
break;
case ENOENT:
case ENOTDIR:
case EBADF:
case ELOOP:
ret = SSH2_FX_NO_SUCH_FILE;
break;
case EPERM:
case EACCES:
case EFAULT:
ret = SSH2_FX_PERMISSION_DENIED;
break;
case ENAMETOOLONG:
case EINVAL:
ret = SSH2_FX_BAD_MESSAGE;
break;
case ENOSYS:
ret = SSH2_FX_OP_UNSUPPORTED;
break;
default:
ret = SSH2_FX_FAILURE;
break;
}
return ret;
}
static int
flags_from_portable(int pflags)
{
int flags = 0;
if ((pflags & SSH2_FXF_READ) &&
(pflags & SSH2_FXF_WRITE)) {
flags = O_RDWR;
} else if (pflags & SSH2_FXF_READ) {
flags = O_RDONLY;
} else if (pflags & SSH2_FXF_WRITE) {
flags = O_WRONLY;
}
if (pflags & SSH2_FXF_APPEND)
flags |= O_APPEND;
if (pflags & SSH2_FXF_CREAT)
flags |= O_CREAT;
if (pflags & SSH2_FXF_TRUNC)
flags |= O_TRUNC;
if (pflags & SSH2_FXF_EXCL)
flags |= O_EXCL;
return flags;
}
static const char *
string_from_portable(int pflags)
{
static char ret[128];
*ret = '\0';
#define PAPPEND(str) { \
if (*ret != '\0') \
strlcat(ret, ",", sizeof(ret)); \
strlcat(ret, str, sizeof(ret)); \
}
if (pflags & SSH2_FXF_READ)
PAPPEND("READ")
if (pflags & SSH2_FXF_WRITE)
PAPPEND("WRITE")
if (pflags & SSH2_FXF_APPEND)
PAPPEND("APPEND")
if (pflags & SSH2_FXF_CREAT)
PAPPEND("CREATE")
if (pflags & SSH2_FXF_TRUNC)
PAPPEND("TRUNCATE")
if (pflags & SSH2_FXF_EXCL)
PAPPEND("EXCL")
return ret;
}
/* handle handles */
typedef struct Handle Handle;
struct Handle {
int use;
DIR *dirp;
int fd;
int flags;
char *name;
u_int64_t bytes_read, bytes_write;
int next_unused;
};
enum {
HANDLE_UNUSED,
HANDLE_DIR,
HANDLE_FILE
};
Handle *handles = NULL;
u_int num_handles = 0;
int first_unused_handle = -1;
static void handle_unused(int i)
{
handles[i].use = HANDLE_UNUSED;
handles[i].next_unused = first_unused_handle;
first_unused_handle = i;
}
static int
handle_new(int use, const char *name, int fd, int flags, DIR *dirp)
{
int i;
if (first_unused_handle == -1) {
if (num_handles + 1 <= num_handles)
return -1;
num_handles++;
handles = xreallocarray(handles, num_handles, sizeof(Handle));
handle_unused(num_handles - 1);
}
i = first_unused_handle;
first_unused_handle = handles[i].next_unused;
handles[i].use = use;
handles[i].dirp = dirp;
handles[i].fd = fd;
handles[i].flags = flags;
handles[i].name = xstrdup(name);
handles[i].bytes_read = handles[i].bytes_write = 0;
return i;
}
static int
handle_is_ok(int i, int type)
{
return i >= 0 && (u_int)i < num_handles && handles[i].use == type;
}
static int
handle_to_string(int handle, u_char **stringp, int *hlenp)
{
if (stringp == NULL || hlenp == NULL)
return -1;
*stringp = xmalloc(sizeof(int32_t));
put_u32(*stringp, handle);
*hlenp = sizeof(int32_t);
return 0;
}
static int
handle_from_string(const u_char *handle, u_int hlen)
{
int val;
if (hlen != sizeof(int32_t))
return -1;
val = get_u32(handle);
if (handle_is_ok(val, HANDLE_FILE) ||
handle_is_ok(val, HANDLE_DIR))
return val;
return -1;
}
static char *
handle_to_name(int handle)
{
if (handle_is_ok(handle, HANDLE_DIR)||
handle_is_ok(handle, HANDLE_FILE))
return handles[handle].name;
return NULL;
}
static DIR *
handle_to_dir(int handle)
{
if (handle_is_ok(handle, HANDLE_DIR))
return handles[handle].dirp;
return NULL;
}
static int
handle_to_fd(int handle)
{
if (handle_is_ok(handle, HANDLE_FILE))
return handles[handle].fd;
return -1;
}
static int
handle_to_flags(int handle)
{
if (handle_is_ok(handle, HANDLE_FILE))
return handles[handle].flags;
return 0;
}
static void
handle_update_read(int handle, ssize_t bytes)
{
if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
handles[handle].bytes_read += bytes;
}
static void
handle_update_write(int handle, ssize_t bytes)
{
if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
handles[handle].bytes_write += bytes;
}
static u_int64_t
handle_bytes_read(int handle)
{
if (handle_is_ok(handle, HANDLE_FILE))
return (handles[handle].bytes_read);
return 0;
}
static u_int64_t
handle_bytes_write(int handle)
{
if (handle_is_ok(handle, HANDLE_FILE))
return (handles[handle].bytes_write);
return 0;
}
static int
handle_close(int handle)
{
int ret = -1;
if (handle_is_ok(handle, HANDLE_FILE)) {
ret = close(handles[handle].fd);
free(handles[handle].name);
handle_unused(handle);
} else if (handle_is_ok(handle, HANDLE_DIR)) {
ret = closedir(handles[handle].dirp);
free(handles[handle].name);
handle_unused(handle);
} else {
errno = ENOENT;
}
return ret;
}
static void
handle_log_close(int handle, char *emsg)
{
if (handle_is_ok(handle, HANDLE_FILE)) {
logit("%s%sclose \"%s\" bytes read %llu written %llu",
emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
handle_to_name(handle),
(unsigned long long)handle_bytes_read(handle),
(unsigned long long)handle_bytes_write(handle));
} else {
logit("%s%sclosedir \"%s\"",
emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
handle_to_name(handle));
}
}
static void
handle_log_exit(void)
{
u_int i;
for (i = 0; i < num_handles; i++)
if (handles[i].use != HANDLE_UNUSED)
handle_log_close(i, "forced");
}
static int
get_handle(struct sshbuf *queue, int *hp)
{
u_char *handle;
int r;
size_t hlen;
*hp = -1;
if ((r = sshbuf_get_string(queue, &handle, &hlen)) != 0)
return r;
if (hlen < 256)
*hp = handle_from_string(handle, hlen);
free(handle);
return 0;
}
/* send replies */
static void
send_msg(struct sshbuf *m)
{
int r;
if ((r = sshbuf_put_stringb(oqueue, m)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
sshbuf_reset(m);
}
static const char *
status_to_message(u_int32_t status)
{
const char *status_messages[] = {
"Success", /* SSH_FX_OK */
"End of file", /* SSH_FX_EOF */
"No such file", /* SSH_FX_NO_SUCH_FILE */
"Permission denied", /* SSH_FX_PERMISSION_DENIED */
"Failure", /* SSH_FX_FAILURE */
"Bad message", /* SSH_FX_BAD_MESSAGE */
"No connection", /* SSH_FX_NO_CONNECTION */
"Connection lost", /* SSH_FX_CONNECTION_LOST */
"Operation unsupported", /* SSH_FX_OP_UNSUPPORTED */
"Unknown error" /* Others */
};
return (status_messages[MINIMUM(status,SSH2_FX_MAX)]);
}
static void
send_status(u_int32_t id, u_int32_t status)
{
struct sshbuf *msg;
int r;
debug3("request %u: sent status %u", id, status);
if (log_level > SYSLOG_LEVEL_VERBOSE ||
(status != SSH2_FX_OK && status != SSH2_FX_EOF))
logit("sent status %s", status_to_message(status));
if ((msg = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((r = sshbuf_put_u8(msg, SSH2_FXP_STATUS)) != 0 ||
(r = sshbuf_put_u32(msg, id)) != 0 ||
(r = sshbuf_put_u32(msg, status)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
if (version >= 3) {
if ((r = sshbuf_put_cstring(msg,
status_to_message(status))) != 0 ||
(r = sshbuf_put_cstring(msg, "")) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
}
send_msg(msg);
sshbuf_free(msg);
}
static void
send_data_or_handle(char type, u_int32_t id, const u_char *data, int dlen)
{
struct sshbuf *msg;
int r;
if ((msg = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((r = sshbuf_put_u8(msg, type)) != 0 ||
(r = sshbuf_put_u32(msg, id)) != 0 ||
(r = sshbuf_put_string(msg, data, dlen)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
send_msg(msg);
sshbuf_free(msg);
}
static void
send_data(u_int32_t id, const u_char *data, int dlen)
{
debug("request %u: sent data len %d", id, dlen);
send_data_or_handle(SSH2_FXP_DATA, id, data, dlen);
}
static void
send_handle(u_int32_t id, int handle)
{
u_char *string;
int hlen;
handle_to_string(handle, &string, &hlen);
debug("request %u: sent handle handle %d", id, handle);
send_data_or_handle(SSH2_FXP_HANDLE, id, string, hlen);
free(string);
}
static void
send_names(u_int32_t id, int count, const Stat *stats)
{
struct sshbuf *msg;
int i, r;
if ((msg = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((r = sshbuf_put_u8(msg, SSH2_FXP_NAME)) != 0 ||
(r = sshbuf_put_u32(msg, id)) != 0 ||
(r = sshbuf_put_u32(msg, count)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: sent names count %d", id, count);
for (i = 0; i < count; i++) {
if ((r = sshbuf_put_cstring(msg, stats[i].name)) != 0 ||
(r = sshbuf_put_cstring(msg, stats[i].long_name)) != 0 ||
(r = encode_attrib(msg, &stats[i].attrib)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
}
send_msg(msg);
sshbuf_free(msg);
}
static void
send_attrib(u_int32_t id, const Attrib *a)
{
struct sshbuf *msg;
int r;
debug("request %u: sent attrib have 0x%x", id, a->flags);
if ((msg = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((r = sshbuf_put_u8(msg, SSH2_FXP_ATTRS)) != 0 ||
(r = sshbuf_put_u32(msg, id)) != 0 ||
(r = encode_attrib(msg, a)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
send_msg(msg);
sshbuf_free(msg);
}
static void
send_statvfs(u_int32_t id, struct statvfs *st)
{
struct sshbuf *msg;
u_int64_t flag;
int r;
flag = (st->f_flag & ST_RDONLY) ? SSH2_FXE_STATVFS_ST_RDONLY : 0;
flag |= (st->f_flag & ST_NOSUID) ? SSH2_FXE_STATVFS_ST_NOSUID : 0;
if ((msg = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED_REPLY)) != 0 ||
(r = sshbuf_put_u32(msg, id)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_bsize)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_frsize)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_blocks)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_bfree)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_bavail)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_files)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_ffree)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_favail)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_fsid)) != 0 ||
(r = sshbuf_put_u64(msg, flag)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_namemax)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
send_msg(msg);
sshbuf_free(msg);
}
/* parse incoming */
static void
process_init(void)
{
struct sshbuf *msg;
int r;
if ((r = sshbuf_get_u32(iqueue, &version)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
verbose("received client version %u", version);
if ((msg = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((r = sshbuf_put_u8(msg, SSH2_FXP_VERSION)) != 0 ||
(r = sshbuf_put_u32(msg, SSH2_FILEXFER_VERSION)) != 0 ||
/* POSIX rename extension */
(r = sshbuf_put_cstring(msg, "posix-rename@openssh.com")) != 0 ||
(r = sshbuf_put_cstring(msg, "1")) != 0 || /* version */
/* statvfs extension */
(r = sshbuf_put_cstring(msg, "statvfs@openssh.com")) != 0 ||
(r = sshbuf_put_cstring(msg, "2")) != 0 || /* version */
/* fstatvfs extension */
(r = sshbuf_put_cstring(msg, "fstatvfs@openssh.com")) != 0 ||
(r = sshbuf_put_cstring(msg, "2")) != 0 || /* version */
/* hardlink extension */
(r = sshbuf_put_cstring(msg, "hardlink@openssh.com")) != 0 ||
(r = sshbuf_put_cstring(msg, "1")) != 0 || /* version */
/* fsync extension */
(r = sshbuf_put_cstring(msg, "fsync@openssh.com")) != 0 ||
(r = sshbuf_put_cstring(msg, "1")) != 0) /* version */
fatal("%s: buffer error: %s", __func__, ssh_err(r));
send_msg(msg);
sshbuf_free(msg);
}
static void
process_open(u_int32_t id)
{
u_int32_t pflags;
Attrib a;
char *name;
int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE;
if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
(r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */
(r = decode_attrib(iqueue, &a)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: open flags %d", id, pflags);
flags = flags_from_portable(pflags);
mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666;
logit("open \"%s\" flags %s mode 0%o",
name, string_from_portable(pflags), mode);
if (readonly &&
((flags & O_ACCMODE) != O_RDONLY ||
(flags & (O_CREAT|O_TRUNC)) != 0)) {
verbose("Refusing open request in read-only mode");
status = SSH2_FX_PERMISSION_DENIED;
} else {
fd = open(name, flags, mode);
if (fd < 0) {
status = errno_to_portable(errno);
} else {
handle = handle_new(HANDLE_FILE, name, fd, flags, NULL);
if (handle < 0) {
close(fd);
} else {
send_handle(id, handle);
status = SSH2_FX_OK;
}
}
}
if (status != SSH2_FX_OK)
send_status(id, status);
free(name);
}
static void
process_close(u_int32_t id)
{
int r, handle, ret, status = SSH2_FX_FAILURE;
if ((r = get_handle(iqueue, &handle)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: close handle %u", id, handle);
handle_log_close(handle, NULL);
ret = handle_close(handle);
status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
}
static void
process_read(u_int32_t id)
{
u_char buf[64*1024];
u_int32_t len;
int r, handle, fd, ret, status = SSH2_FX_FAILURE;
u_int64_t off;
if ((r = get_handle(iqueue, &handle)) != 0 ||
(r = sshbuf_get_u64(iqueue, &off)) != 0 ||
(r = sshbuf_get_u32(iqueue, &len)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: read \"%s\" (handle %d) off %llu len %d",
id, handle_to_name(handle), handle, (unsigned long long)off, len);
if (len > sizeof buf) {
len = sizeof buf;
debug2("read change len %d", len);
}
fd = handle_to_fd(handle);
if (fd >= 0) {
if (lseek(fd, off, SEEK_SET) < 0) {
error("process_read: seek failed");
status = errno_to_portable(errno);
} else {
ret = read(fd, buf, len);
if (ret < 0) {
status = errno_to_portable(errno);
} else if (ret == 0) {
status = SSH2_FX_EOF;
} else {
send_data(id, buf, ret);
status = SSH2_FX_OK;
handle_update_read(handle, ret);
}
}
}
if (status != SSH2_FX_OK)
send_status(id, status);
}
static void
process_write(u_int32_t id)
{
u_int64_t off;
size_t len;
int r, handle, fd, ret, status;
u_char *data;
if ((r = get_handle(iqueue, &handle)) != 0 ||
(r = sshbuf_get_u64(iqueue, &off)) != 0 ||
(r = sshbuf_get_string(iqueue, &data, &len)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: write \"%s\" (handle %d) off %llu len %zu",
id, handle_to_name(handle), handle, (unsigned long long)off, len);
fd = handle_to_fd(handle);
if (fd < 0)
status = SSH2_FX_FAILURE;
else {
if (!(handle_to_flags(handle) & O_APPEND) &&
lseek(fd, off, SEEK_SET) < 0) {
status = errno_to_portable(errno);
error("process_write: seek failed");
} else {
/* XXX ATOMICIO ? */
ret = write(fd, data, len);
if (ret < 0) {
error("process_write: write failed");
status = errno_to_portable(errno);
} else if ((size_t)ret == len) {
status = SSH2_FX_OK;
handle_update_write(handle, ret);
} else {
debug2("nothing at all written");
status = SSH2_FX_FAILURE;
}
}
}
send_status(id, status);
free(data);
}
static void
process_do_stat(u_int32_t id, int do_lstat)
{
Attrib a;
struct stat st;
char *name;
int r, status = SSH2_FX_FAILURE;
if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: %sstat", id, do_lstat ? "l" : "");
verbose("%sstat name \"%s\"", do_lstat ? "l" : "", name);
r = do_lstat ? lstat(name, &st) : stat(name, &st);
if (r < 0) {
status = errno_to_portable(errno);
} else {
stat_to_attrib(&st, &a);
send_attrib(id, &a);
status = SSH2_FX_OK;
}
if (status != SSH2_FX_OK)
send_status(id, status);
free(name);
}
static void
process_stat(u_int32_t id)
{
process_do_stat(id, 0);
}
static void
process_lstat(u_int32_t id)
{
process_do_stat(id, 1);
}
static void
process_fstat(u_int32_t id)
{
Attrib a;
struct stat st;
int fd, r, handle, status = SSH2_FX_FAILURE;
if ((r = get_handle(iqueue, &handle)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: fstat \"%s\" (handle %u)",
id, handle_to_name(handle), handle);
fd = handle_to_fd(handle);
if (fd >= 0) {
r = fstat(fd, &st);
if (r < 0) {
status = errno_to_portable(errno);
} else {
stat_to_attrib(&st, &a);
send_attrib(id, &a);
status = SSH2_FX_OK;
}
}
if (status != SSH2_FX_OK)
send_status(id, status);
}
static struct timeval *
attrib_to_tv(const Attrib *a)
{
static struct timeval tv[2];
tv[0].tv_sec = a->atime;
tv[0].tv_usec = 0;
tv[1].tv_sec = a->mtime;
tv[1].tv_usec = 0;
return tv;
}
static void
process_setstat(u_int32_t id)
{
Attrib a;
char *name;
int r, status = SSH2_FX_OK;
if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
(r = decode_attrib(iqueue, &a)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: setstat name \"%s\"", id, name);
if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
logit("set \"%s\" size %llu",
name, (unsigned long long)a.size);
r = truncate(name, a.size);
if (r == -1)
status = errno_to_portable(errno);
}
if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
logit("set \"%s\" mode %04o", name, a.perm);
r = chmod(name, a.perm & 07777);
if (r == -1)
status = errno_to_portable(errno);
}
if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
char buf[64];
time_t t = a.mtime;
strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
localtime(&t));
logit("set \"%s\" modtime %s", name, buf);
r = utimes(name, attrib_to_tv(&a));
if (r == -1)
status = errno_to_portable(errno);
}
if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
logit("set \"%s\" owner %lu group %lu", name,
(u_long)a.uid, (u_long)a.gid);
r = chown(name, a.uid, a.gid);
if (r == -1)
status = errno_to_portable(errno);
}
send_status(id, status);
free(name);
}
static void
process_fsetstat(u_int32_t id)
{
Attrib a;
int handle, fd, r;
int status = SSH2_FX_OK;
if ((r = get_handle(iqueue, &handle)) != 0 ||
(r = decode_attrib(iqueue, &a)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: fsetstat handle %d", id, handle);
fd = handle_to_fd(handle);
if (fd < 0)
status = SSH2_FX_FAILURE;
else {
char *name = handle_to_name(handle);
if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
logit("set \"%s\" size %llu",
name, (unsigned long long)a.size);
r = ftruncate(fd, a.size);
if (r == -1)
status = errno_to_portable(errno);
}
if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
logit("set \"%s\" mode %04o", name, a.perm);
r = fchmod(fd, a.perm & 07777);
if (r == -1)
status = errno_to_portable(errno);
}
if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
char buf[64];
time_t t = a.mtime;
strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
localtime(&t));
logit("set \"%s\" modtime %s", name, buf);
r = futimes(fd, attrib_to_tv(&a));
if (r == -1)
status = errno_to_portable(errno);
}
if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
logit("set \"%s\" owner %lu group %lu", name,
(u_long)a.uid, (u_long)a.gid);
r = fchown(fd, a.uid, a.gid);
if (r == -1)
status = errno_to_portable(errno);
}
}
send_status(id, status);
}
static void
process_opendir(u_int32_t id)
{
DIR *dirp = NULL;
char *path;
int r, handle, status = SSH2_FX_FAILURE;
if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: opendir", id);
logit("opendir \"%s\"", path);
dirp = opendir(path);
if (dirp == NULL) {
status = errno_to_portable(errno);
} else {
handle = handle_new(HANDLE_DIR, path, 0, 0, dirp);
if (handle < 0) {
closedir(dirp);
} else {
send_handle(id, handle);
status = SSH2_FX_OK;
}
}
if (status != SSH2_FX_OK)
send_status(id, status);
free(path);
}
static void
process_readdir(u_int32_t id)
{
DIR *dirp;
struct dirent *dp;
char *path;
int r, handle;
if ((r = get_handle(iqueue, &handle)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: readdir \"%s\" (handle %d)", id,
handle_to_name(handle), handle);
dirp = handle_to_dir(handle);
path = handle_to_name(handle);
if (dirp == NULL || path == NULL) {
send_status(id, SSH2_FX_FAILURE);
} else {
struct stat st;
char pathname[PATH_MAX];
Stat *stats;
int nstats = 10, count = 0, i;
stats = xcalloc(nstats, sizeof(Stat));
while ((dp = readdir(dirp)) != NULL) {
if (count >= nstats) {
nstats *= 2;
stats = xreallocarray(stats, nstats, sizeof(Stat));
}
/* XXX OVERFLOW ? */
snprintf(pathname, sizeof pathname, "%s%s%s", path,
strcmp(path, "/") ? "/" : "", dp->d_name);
if (lstat(pathname, &st) < 0)
continue;
stat_to_attrib(&st, &(stats[count].attrib));
stats[count].name = xstrdup(dp->d_name);
stats[count].long_name = ls_file(dp->d_name, &st, 0, 0);
count++;
/* send up to 100 entries in one message */
/* XXX check packet size instead */
if (count == 100)
break;
}
if (count > 0) {
send_names(id, count, stats);
for (i = 0; i < count; i++) {
free(stats[i].name);
free(stats[i].long_name);
}
} else {
send_status(id, SSH2_FX_EOF);
}
free(stats);
}
}
static void
process_remove(u_int32_t id)
{
char *name;
int r, status = SSH2_FX_FAILURE;
if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: remove", id);
logit("remove name \"%s\"", name);
r = unlink(name);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
free(name);
}
static void
process_mkdir(u_int32_t id)
{
Attrib a;
char *name;
int r, mode, status = SSH2_FX_FAILURE;
if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
(r = decode_attrib(iqueue, &a)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ?
a.perm & 07777 : 0777;
debug3("request %u: mkdir", id);
logit("mkdir name \"%s\" mode 0%o", name, mode);
r = mkdir(name, mode);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
free(name);
}
static void
process_rmdir(u_int32_t id)
{
char *name;
int r, status;
if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: rmdir", id);
logit("rmdir name \"%s\"", name);
r = rmdir(name);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
free(name);
}
static void
process_realpath(u_int32_t id)
{
char resolvedname[PATH_MAX];
char *path;
int r;
if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
if (path[0] == '\0') {
free(path);
path = xstrdup(".");
}
debug3("request %u: realpath", id);
verbose("realpath \"%s\"", path);
if (realpath(path, resolvedname) == NULL) {
send_status(id, errno_to_portable(errno));
} else {
Stat s;
attrib_clear(&s.attrib);
s.name = s.long_name = resolvedname;
send_names(id, 1, &s);
}
free(path);
}
static void
process_rename(u_int32_t id)
{
char *oldpath, *newpath;
int r, status;
struct stat sb;
if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
(r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: rename", id);
logit("rename old \"%s\" new \"%s\"", oldpath, newpath);
status = SSH2_FX_FAILURE;
if (lstat(oldpath, &sb) == -1)
status = errno_to_portable(errno);
else if (S_ISREG(sb.st_mode)) {
/* Race-free rename of regular files */
if (link(oldpath, newpath) == -1) {
if (errno == EOPNOTSUPP) {
struct stat st;
/*
* fs doesn't support links, so fall back to
* stat+rename. This is racy.
*/
if (stat(newpath, &st) == -1) {
if (rename(oldpath, newpath) == -1)
status =
errno_to_portable(errno);
else
status = SSH2_FX_OK;
}
} else {
status = errno_to_portable(errno);
}
} else if (unlink(oldpath) == -1) {
status = errno_to_portable(errno);
/* clean spare link */
unlink(newpath);
} else
status = SSH2_FX_OK;
} else if (stat(newpath, &sb) == -1) {
if (rename(oldpath, newpath) == -1)
status = errno_to_portable(errno);
else
status = SSH2_FX_OK;
}
send_status(id, status);
free(oldpath);
free(newpath);
}
static void
process_readlink(u_int32_t id)
{
int r, len;
char buf[PATH_MAX];
char *path;
if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: readlink", id);
verbose("readlink \"%s\"", path);
if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1)
send_status(id, errno_to_portable(errno));
else {
Stat s;
buf[len] = '\0';
attrib_clear(&s.attrib);
s.name = s.long_name = buf;
send_names(id, 1, &s);
}
free(path);
}
static void
process_symlink(u_int32_t id)
{
char *oldpath, *newpath;
int r, status;
if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
(r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: symlink", id);
logit("symlink old \"%s\" new \"%s\"", oldpath, newpath);
/* this will fail if 'newpath' exists */
r = symlink(oldpath, newpath);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
free(oldpath);
free(newpath);
}
static void
process_extended_posix_rename(u_int32_t id)
{
char *oldpath, *newpath;
int r, status;
if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
(r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: posix-rename", id);
logit("posix-rename old \"%s\" new \"%s\"", oldpath, newpath);
r = rename(oldpath, newpath);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
free(oldpath);
free(newpath);
}
static void
process_extended_statvfs(u_int32_t id)
{
char *path;
struct statvfs st;
int r;
if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: statvfs", id);
logit("statvfs \"%s\"", path);
if (statvfs(path, &st) != 0)
send_status(id, errno_to_portable(errno));
else
send_statvfs(id, &st);
free(path);
}
static void
process_extended_fstatvfs(u_int32_t id)
{
int r, handle, fd;
struct statvfs st;
if ((r = get_handle(iqueue, &handle)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: fstatvfs \"%s\" (handle %u)",
id, handle_to_name(handle), handle);
if ((fd = handle_to_fd(handle)) < 0) {
send_status(id, SSH2_FX_FAILURE);
return;
}
if (fstatvfs(fd, &st) != 0)
send_status(id, errno_to_portable(errno));
else
send_statvfs(id, &st);
}
static void
process_extended_hardlink(u_int32_t id)
{
char *oldpath, *newpath;
int r, status;
if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
(r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: hardlink", id);
logit("hardlink old \"%s\" new \"%s\"", oldpath, newpath);
r = link(oldpath, newpath);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
free(oldpath);
free(newpath);
}
static void
process_extended_fsync(u_int32_t id)
{
int handle, fd, r, status = SSH2_FX_OP_UNSUPPORTED;
if ((r = get_handle(iqueue, &handle)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: fsync (handle %u)", id, handle);
verbose("fsync \"%s\"", handle_to_name(handle));
if ((fd = handle_to_fd(handle)) < 0)
status = SSH2_FX_NO_SUCH_FILE;
else if (handle_is_ok(handle, HANDLE_FILE)) {
r = fsync(fd);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
}
send_status(id, status);
}
static void
process_extended(u_int32_t id)
{
char *request;
int i, r;
if ((r = sshbuf_get_cstring(iqueue, &request, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
for (i = 0; extended_handlers[i].handler != NULL; i++) {
if (strcmp(request, extended_handlers[i].ext_name) == 0) {
if (!request_permitted(&extended_handlers[i]))
send_status(id, SSH2_FX_PERMISSION_DENIED);
else
extended_handlers[i].handler(id);
break;
}
}
if (extended_handlers[i].handler == NULL) {
error("Unknown extended request \"%.100s\"", request);
send_status(id, SSH2_FX_OP_UNSUPPORTED); /* MUST */
}
free(request);
}
/* stolen from ssh-agent */
static void
process(void)
{
u_int msg_len;
u_int buf_len;
u_int consumed;
u_char type;
const u_char *cp;
int i, r;
u_int32_t id;
buf_len = sshbuf_len(iqueue);
if (buf_len < 5)
return; /* Incomplete message. */
cp = sshbuf_ptr(iqueue);
msg_len = get_u32(cp);
if (msg_len > SFTP_MAX_MSG_LENGTH) {
error("bad message from %s local user %s",
client_addr, pw->pw_name);
sftp_server_cleanup_exit(11);
}
if (buf_len < msg_len + 4)
return;
if ((r = sshbuf_consume(iqueue, 4)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
buf_len -= 4;
if ((r = sshbuf_get_u8(iqueue, &type)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
switch (type) {
case SSH2_FXP_INIT:
process_init();
init_done = 1;
break;
case SSH2_FXP_EXTENDED:
if (!init_done)
fatal("Received extended request before init");
if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
process_extended(id);
break;
default:
if (!init_done)
fatal("Received %u request before init", type);
if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
for (i = 0; handlers[i].handler != NULL; i++) {
if (type == handlers[i].type) {
if (!request_permitted(&handlers[i])) {
send_status(id,
SSH2_FX_PERMISSION_DENIED);
} else {
handlers[i].handler(id);
}
break;
}
}
if (handlers[i].handler == NULL)
error("Unknown message %u", type);
}
/* discard the remaining bytes from the current packet */
if (buf_len < sshbuf_len(iqueue)) {
error("iqueue grew unexpectedly");
sftp_server_cleanup_exit(255);
}
consumed = buf_len - sshbuf_len(iqueue);
if (msg_len < consumed) {
error("msg_len %u < consumed %u", msg_len, consumed);
sftp_server_cleanup_exit(255);
}
if (msg_len > consumed &&
(r = sshbuf_consume(iqueue, msg_len - consumed)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
}
/* Cleanup handler that logs active handles upon normal exit */
void
sftp_server_cleanup_exit(int i)
{
if (pw != NULL && client_addr != NULL) {
handle_log_exit();
logit("session closed for local user %s from [%s]",
pw->pw_name, client_addr);
}
_exit(i);
}
static void
sftp_server_usage(void)
{
extern char *__progname;
fprintf(stderr,
"usage: %s [-ehR] [-d start_directory] [-f log_facility] "
"[-l log_level]\n\t[-P blacklisted_requests] "
"[-p whitelisted_requests] [-u umask]\n"
" %s -Q protocol_feature\n",
__progname, __progname);
exit(1);
}
int
sftp_server_main(int argc, char **argv, struct passwd *user_pw)
{
fd_set *rset, *wset;
int i, r, in, out, max, ch, skipargs = 0, log_stderr = 0;
ssize_t len, olen, set_size;
SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
char *cp, *homedir = NULL, buf[4*4096];
long mask;
extern char *optarg;
extern char *__progname;
ssh_malloc_init(); /* must be called before any mallocs */
log_init(__progname, log_level, log_facility, log_stderr);
pw = pwcopy(user_pw);
while (!skipargs && (ch = getopt(argc, argv,
"d:f:l:P:p:Q:u:cehR")) != -1) {
switch (ch) {
case 'Q':
if (strcasecmp(optarg, "requests") != 0) {
fprintf(stderr, "Invalid query type\n");
exit(1);
}
for (i = 0; handlers[i].handler != NULL; i++)
printf("%s\n", handlers[i].name);
for (i = 0; extended_handlers[i].handler != NULL; i++)
printf("%s\n", extended_handlers[i].name);
exit(0);
break;
case 'R':
readonly = 1;
break;
case 'c':
/*
* Ignore all arguments if we are invoked as a
* shell using "sftp-server -c command"
*/
skipargs = 1;
break;
case 'e':
log_stderr = 1;
break;
case 'l':
log_level = log_level_number(optarg);
if (log_level == SYSLOG_LEVEL_NOT_SET)
error("Invalid log level \"%s\"", optarg);
break;
case 'f':
log_facility = log_facility_number(optarg);
if (log_facility == SYSLOG_FACILITY_NOT_SET)
error("Invalid log facility \"%s\"", optarg);
break;
case 'd':
cp = tilde_expand_filename(optarg, user_pw->pw_uid);
homedir = percent_expand(cp, "d", user_pw->pw_dir,
"u", user_pw->pw_name, (char *)NULL);
free(cp);
break;
case 'p':
if (request_whitelist != NULL)
fatal("Permitted requests already set");
request_whitelist = xstrdup(optarg);
break;
case 'P':
if (request_blacklist != NULL)
fatal("Refused requests already set");
request_blacklist = xstrdup(optarg);
break;
case 'u':
errno = 0;
mask = strtol(optarg, &cp, 8);
if (mask < 0 || mask > 0777 || *cp != '\0' ||
cp == optarg || (mask == 0 && errno != 0))
fatal("Invalid umask \"%s\"", optarg);
(void)umask((mode_t)mask);
break;
case 'h':
default:
sftp_server_usage();
}
}
log_init(__progname, log_level, log_facility, log_stderr);
if ((cp = getenv("SSH_CONNECTION")) != NULL) {
client_addr = xstrdup(cp);
if ((cp = strchr(client_addr, ' ')) == NULL) {
error("Malformed SSH_CONNECTION variable: \"%s\"",
getenv("SSH_CONNECTION"));
sftp_server_cleanup_exit(255);
}
*cp = '\0';
} else
client_addr = xstrdup("UNKNOWN");
logit("session opened for local user %s from [%s]",
pw->pw_name, client_addr);
in = STDIN_FILENO;
out = STDOUT_FILENO;
max = 0;
if (in > max)
max = in;
if (out > max)
max = out;
if ((iqueue = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((oqueue = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
rset = xcalloc(howmany(max + 1, NFDBITS), sizeof(fd_mask));
wset = xcalloc(howmany(max + 1, NFDBITS), sizeof(fd_mask));
if (homedir != NULL) {
if (chdir(homedir) != 0) {
error("chdir to \"%s\" failed: %s", homedir,
strerror(errno));
}
}
set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask);
for (;;) {
memset(rset, 0, set_size);
memset(wset, 0, set_size);
/*
* Ensure that we can read a full buffer and handle
* the worst-case length packet it can generate,
* otherwise apply backpressure by stopping reads.
*/
if ((r = sshbuf_check_reserve(iqueue, sizeof(buf))) == 0 &&
(r = sshbuf_check_reserve(oqueue,
SFTP_MAX_MSG_LENGTH)) == 0)
FD_SET(in, rset);
else if (r != SSH_ERR_NO_BUFFER_SPACE)
fatal("%s: sshbuf_check_reserve failed: %s",
__func__, ssh_err(r));
olen = sshbuf_len(oqueue);
if (olen > 0)
FD_SET(out, wset);
if (select(max+1, rset, wset, NULL, NULL) < 0) {
if (errno == EINTR)
continue;
error("select: %s", strerror(errno));
sftp_server_cleanup_exit(2);
}
/* copy stdin to iqueue */
if (FD_ISSET(in, rset)) {
len = read(in, buf, sizeof buf);
if (len == 0) {
debug("read eof");
sftp_server_cleanup_exit(0);
} else if (len < 0) {
error("read: %s", strerror(errno));
sftp_server_cleanup_exit(1);
} else if ((r = sshbuf_put(iqueue, buf, len)) != 0) {
fatal("%s: buffer error: %s",
__func__, ssh_err(r));
}
}
/* send oqueue to stdout */
if (FD_ISSET(out, wset)) {
len = write(out, sshbuf_ptr(oqueue), olen);
if (len < 0) {
error("write: %s", strerror(errno));
sftp_server_cleanup_exit(1);
} else if ((r = sshbuf_consume(oqueue, len)) != 0) {
fatal("%s: buffer error: %s",
__func__, ssh_err(r));
}
}
/*
* Process requests from client if we can fit the results
* into the output buffer, otherwise stop processing input
* and let the output queue drain.
*/
r = sshbuf_check_reserve(oqueue, SFTP_MAX_MSG_LENGTH);
if (r == 0)
process();
else if (r != SSH_ERR_NO_BUFFER_SPACE)
fatal("%s: sshbuf_check_reserve: %s",
__func__, ssh_err(r));
}
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_2887_0 |
crossvul-cpp_data_bad_3233_0 | /*
===========================================================================
Return to Castle Wolfenstein multiplayer GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (RTCW MP Source Code).
RTCW MP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW MP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW MP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
// cl_main.c -- client main loop
#include "client.h"
#include <limits.h>
#ifdef __linux__
#include <sys/stat.h>
#endif
#include "../sys/sys_local.h"
#include "../sys/sys_loadlib.h"
#ifdef USE_MUMBLE
#include "libmumblelink.h"
#endif
#ifdef USE_MUMBLE
cvar_t *cl_useMumble;
cvar_t *cl_mumbleScale;
#endif
#ifdef USE_VOIP
cvar_t *cl_voipUseVAD;
cvar_t *cl_voipVADThreshold;
cvar_t *cl_voipSend;
cvar_t *cl_voipSendTarget;
cvar_t *cl_voipGainDuringCapture;
cvar_t *cl_voipCaptureMult;
cvar_t *cl_voipShowMeter;
cvar_t *cl_voipProtocol;
cvar_t *cl_voip;
#endif
#ifdef USE_RENDERER_DLOPEN
cvar_t *cl_renderer;
#endif
cvar_t *cl_wavefilerecord;
cvar_t *cl_nodelta;
cvar_t *cl_debugMove;
cvar_t *cl_noprint;
#ifdef UPDATE_SERVER_NAME
cvar_t *cl_motd;
#endif
cvar_t *cl_autoupdate; // DHM - Nerve
cvar_t *rcon_client_password;
cvar_t *rconAddress;
cvar_t *cl_timeout;
cvar_t *cl_maxpackets;
cvar_t *cl_packetdup;
cvar_t *cl_timeNudge;
cvar_t *cl_showTimeDelta;
cvar_t *cl_freezeDemo;
cvar_t *cl_showPing;
cvar_t *cl_shownet = NULL; // NERVE - SMF - This is referenced in msg.c and we need to make sure it is NULL
cvar_t *cl_shownuments; // DHM - Nerve
cvar_t *cl_visibleClients; // DHM - Nerve
cvar_t *cl_showSend;
cvar_t *cl_showServerCommands; // NERVE - SMF
cvar_t *cl_timedemo;
cvar_t *cl_timedemoLog;
cvar_t *cl_autoRecordDemo;
cvar_t *cl_aviFrameRate;
cvar_t *cl_aviMotionJpeg;
cvar_t *cl_avidemo;
cvar_t *cl_forceavidemo;
cvar_t *cl_freelook;
cvar_t *cl_sensitivity;
cvar_t *cl_mouseAccel;
cvar_t *cl_mouseAccelOffset;
cvar_t *cl_mouseAccelStyle;
cvar_t *cl_showMouseRate;
cvar_t *m_pitch;
cvar_t *m_yaw;
cvar_t *m_forward;
cvar_t *m_side;
cvar_t *m_filter;
cvar_t *j_pitch;
cvar_t *j_yaw;
cvar_t *j_forward;
cvar_t *j_side;
cvar_t *j_up;
cvar_t *j_pitch_axis;
cvar_t *j_yaw_axis;
cvar_t *j_forward_axis;
cvar_t *j_side_axis;
cvar_t *j_up_axis;
cvar_t *cl_activeAction;
cvar_t *cl_motdString;
cvar_t *cl_allowDownload;
cvar_t *cl_conXOffset;
cvar_t *cl_inGameVideo;
cvar_t *cl_serverStatusResendTime;
cvar_t *cl_missionStats;
cvar_t *cl_waitForFire;
// NERVE - SMF - localization
cvar_t *cl_language;
cvar_t *cl_debugTranslation;
// -NERVE - SMF
// DHM - Nerve :: Auto-Update
cvar_t *cl_updateavailable;
cvar_t *cl_updatefiles;
// DHM - Nerve
cvar_t *cl_lanForcePackets;
cvar_t *cl_guid;
cvar_t *cl_guidServerUniq;
cvar_t *cl_consoleKeys;
cvar_t *cl_rate;
clientActive_t cl;
clientConnection_t clc;
clientStatic_t cls;
vm_t *cgvm;
char cl_reconnectArgs[MAX_OSPATH];
char cl_oldGame[MAX_QPATH];
qboolean cl_oldGameSet;
// Structure containing functions exported from refresh DLL
refexport_t re;
#ifdef USE_RENDERER_DLOPEN
static void *rendererLib = NULL;
#endif
ping_t cl_pinglist[MAX_PINGREQUESTS];
typedef struct serverStatus_s
{
char string[BIG_INFO_STRING];
netadr_t address;
int time, startTime;
qboolean pending;
qboolean print;
qboolean retrieved;
} serverStatus_t;
serverStatus_t cl_serverStatusList[MAX_SERVERSTATUSREQUESTS];
// DHM - Nerve :: Have we heard from the auto-update server this session?
qboolean autoupdateChecked;
qboolean autoupdateStarted;
// TTimo : moved from char* to array (was getting the char* from va(), broke on big downloads)
char autoupdateFilename[MAX_QPATH];
// "updates" shifted from -7
#define AUTOUPDATE_DIR "ni]Zm^l"
#define AUTOUPDATE_DIR_SHIFT 7
static int noGameRestart = qfalse;
extern void SV_BotFrame( int time );
void CL_CheckForResend( void );
void CL_ShowIP_f( void );
void CL_ServerStatus_f( void );
void CL_ServerStatusResponse( netadr_t from, msg_t *msg );
void CL_SaveTranslations_f( void );
void CL_LoadTranslations_f( void );
/*
===============
CL_CDDialog
Called by Com_Error when a cd is needed
===============
*/
void CL_CDDialog( void ) {
cls.cddialog = qtrue; // start it next frame
}
#ifdef USE_MUMBLE
static
void CL_UpdateMumble(void)
{
vec3_t pos, forward, up;
float scale = cl_mumbleScale->value;
float tmp;
if(!cl_useMumble->integer)
return;
// !!! FIXME: not sure if this is even close to correct.
AngleVectors( cl.snap.ps.viewangles, forward, NULL, up);
pos[0] = cl.snap.ps.origin[0] * scale;
pos[1] = cl.snap.ps.origin[2] * scale;
pos[2] = cl.snap.ps.origin[1] * scale;
tmp = forward[1];
forward[1] = forward[2];
forward[2] = tmp;
tmp = up[1];
up[1] = up[2];
up[2] = tmp;
if(cl_useMumble->integer > 1) {
fprintf(stderr, "%f %f %f, %f %f %f, %f %f %f\n",
pos[0], pos[1], pos[2],
forward[0], forward[1], forward[2],
up[0], up[1], up[2]);
}
mumble_update_coordinates(pos, forward, up);
}
#endif
#ifdef USE_VOIP
static
void CL_UpdateVoipIgnore(const char *idstr, qboolean ignore)
{
if ((*idstr >= '0') && (*idstr <= '9')) {
const int id = atoi(idstr);
if ((id >= 0) && (id < MAX_CLIENTS)) {
clc.voipIgnore[id] = ignore;
CL_AddReliableCommand(va("voip %s %d",
ignore ? "ignore" : "unignore", id), qfalse);
Com_Printf("VoIP: %s ignoring player #%d\n",
ignore ? "Now" : "No longer", id);
return;
}
}
Com_Printf("VoIP: invalid player ID#\n");
}
static
void CL_UpdateVoipGain(const char *idstr, float gain)
{
if ((*idstr >= '0') && (*idstr <= '9')) {
const int id = atoi(idstr);
if (gain < 0.0f)
gain = 0.0f;
if ((id >= 0) && (id < MAX_CLIENTS)) {
clc.voipGain[id] = gain;
Com_Printf("VoIP: player #%d gain now set to %f\n", id, gain);
}
}
}
void CL_Voip_f( void )
{
const char *cmd = Cmd_Argv(1);
const char *reason = NULL;
if (clc.state != CA_ACTIVE)
reason = "Not connected to a server";
else if (!clc.voipCodecInitialized)
reason = "Voip codec not initialized";
else if (!clc.voipEnabled)
reason = "Server doesn't support VoIP";
else if (!clc.demoplaying && (Cvar_VariableValue("g_gametype") == GT_SINGLE_PLAYER || Cvar_VariableValue("ui_singlePlayerActive")))
reason = "running in single-player mode";
if (reason != NULL) {
Com_Printf("VoIP: command ignored: %s\n", reason);
return;
}
if (strcmp(cmd, "ignore") == 0) {
CL_UpdateVoipIgnore(Cmd_Argv(2), qtrue);
} else if (strcmp(cmd, "unignore") == 0) {
CL_UpdateVoipIgnore(Cmd_Argv(2), qfalse);
} else if (strcmp(cmd, "gain") == 0) {
if (Cmd_Argc() > 3) {
CL_UpdateVoipGain(Cmd_Argv(2), atof(Cmd_Argv(3)));
} else if (Q_isanumber(Cmd_Argv(2))) {
int id = atoi(Cmd_Argv(2));
if (id >= 0 && id < MAX_CLIENTS) {
Com_Printf("VoIP: current gain for player #%d "
"is %f\n", id, clc.voipGain[id]);
} else {
Com_Printf("VoIP: invalid player ID#\n");
}
} else {
Com_Printf("usage: voip gain <playerID#> [value]\n");
}
} else if (strcmp(cmd, "muteall") == 0) {
Com_Printf("VoIP: muting incoming voice\n");
CL_AddReliableCommand("voip muteall", qfalse);
clc.voipMuteAll = qtrue;
} else if (strcmp(cmd, "unmuteall") == 0) {
Com_Printf("VoIP: unmuting incoming voice\n");
CL_AddReliableCommand("voip unmuteall", qfalse);
clc.voipMuteAll = qfalse;
} else {
Com_Printf("usage: voip [un]ignore <playerID#>\n"
" voip [un]muteall\n"
" voip gain <playerID#> [value]\n");
}
}
static
void CL_VoipNewGeneration(void)
{
// don't have a zero generation so new clients won't match, and don't
// wrap to negative so MSG_ReadLong() doesn't "fail."
clc.voipOutgoingGeneration++;
if (clc.voipOutgoingGeneration <= 0)
clc.voipOutgoingGeneration = 1;
clc.voipPower = 0.0f;
clc.voipOutgoingSequence = 0;
opus_encoder_ctl(clc.opusEncoder, OPUS_RESET_STATE);
}
/*
===============
CL_VoipParseTargets
sets clc.voipTargets according to cl_voipSendTarget
Generally we don't want who's listening to change during a transmission,
so this is only called when the key is first pressed
===============
*/
void CL_VoipParseTargets(void)
{
const char *target = cl_voipSendTarget->string;
char *end;
int val;
Com_Memset(clc.voipTargets, 0, sizeof(clc.voipTargets));
clc.voipFlags &= ~VOIP_SPATIAL;
while(target)
{
while(*target == ',' || *target == ' ')
target++;
if(!*target)
break;
if(isdigit(*target))
{
val = strtol(target, &end, 10);
target = end;
}
else
{
if(!Q_stricmpn(target, "all", 3))
{
Com_Memset(clc.voipTargets, ~0, sizeof(clc.voipTargets));
return;
}
if(!Q_stricmpn(target, "spatial", 7))
{
clc.voipFlags |= VOIP_SPATIAL;
target += 7;
continue;
}
else
{
if(!Q_stricmpn(target, "attacker", 8))
{
val = VM_Call(cgvm, CG_LAST_ATTACKER);
target += 8;
}
else if(!Q_stricmpn(target, "crosshair", 9))
{
val = VM_Call(cgvm, CG_CROSSHAIR_PLAYER);
target += 9;
}
else
{
while(*target && *target != ',' && *target != ' ')
target++;
continue;
}
if(val < 0)
continue;
}
}
if(val < 0 || val >= MAX_CLIENTS)
{
Com_Printf(S_COLOR_YELLOW "WARNING: VoIP "
"target %d is not a valid client "
"number\n", val);
continue;
}
clc.voipTargets[val / 8] |= 1 << (val % 8);
}
}
/*
===============
CL_CaptureVoip
Record more audio from the hardware if required and encode it into Opus
data for later transmission.
===============
*/
static
void CL_CaptureVoip(void)
{
const float audioMult = cl_voipCaptureMult->value;
const qboolean useVad = (cl_voipUseVAD->integer != 0);
qboolean initialFrame = qfalse;
qboolean finalFrame = qfalse;
#if USE_MUMBLE
// if we're using Mumble, don't try to handle VoIP transmission ourselves.
if (cl_useMumble->integer)
return;
#endif
// If your data rate is too low, you'll get Connection Interrupted warnings
// when VoIP packets arrive, even if you have a broadband connection.
// This might work on rates lower than 25000, but for safety's sake, we'll
// just demand it. Who doesn't have at least a DSL line now, anyhow? If
// you don't, you don't need VoIP. :)
if (cl_voip->modified || cl_rate->modified) {
if ((cl_voip->integer) && (cl_rate->integer < 25000)) {
Com_Printf(S_COLOR_YELLOW "Your network rate is too slow for VoIP.\n");
Com_Printf("Set 'Data Rate' to 'LAN/Cable/xDSL' in 'Setup/System/Network'.\n");
Com_Printf("Until then, VoIP is disabled.\n");
Cvar_Set("cl_voip", "0");
}
Cvar_Set("cl_voipProtocol", cl_voip->integer ? "opus" : "");
cl_voip->modified = qfalse;
cl_rate->modified = qfalse;
}
if (!clc.voipCodecInitialized)
return; // just in case this gets called at a bad time.
if (clc.voipOutgoingDataSize > 0)
return; // packet is pending transmission, don't record more yet.
if (cl_voipUseVAD->modified) {
Cvar_Set("cl_voipSend", (useVad) ? "1" : "0");
cl_voipUseVAD->modified = qfalse;
}
if ((useVad) && (!cl_voipSend->integer))
Cvar_Set("cl_voipSend", "1"); // lots of things reset this.
if (cl_voipSend->modified) {
qboolean dontCapture = qfalse;
if (clc.state != CA_ACTIVE)
dontCapture = qtrue; // not connected to a server.
else if (!clc.voipEnabled)
dontCapture = qtrue; // server doesn't support VoIP.
else if (clc.demoplaying)
dontCapture = qtrue; // playing back a demo.
else if ( cl_voip->integer == 0 )
dontCapture = qtrue; // client has VoIP support disabled.
else if ( audioMult == 0.0f )
dontCapture = qtrue; // basically silenced incoming audio.
cl_voipSend->modified = qfalse;
if(dontCapture)
{
Cvar_Set("cl_voipSend", "0");
return;
}
if (cl_voipSend->integer) {
initialFrame = qtrue;
} else {
finalFrame = qtrue;
}
}
// try to get more audio data from the sound card...
if (initialFrame) {
S_MasterGain(Com_Clamp(0.0f, 1.0f, cl_voipGainDuringCapture->value));
S_StartCapture();
CL_VoipNewGeneration();
CL_VoipParseTargets();
}
if ((cl_voipSend->integer) || (finalFrame)) { // user wants to capture audio?
int samples = S_AvailableCaptureSamples();
const int packetSamples = (finalFrame) ? VOIP_MAX_FRAME_SAMPLES : VOIP_MAX_PACKET_SAMPLES;
// enough data buffered in audio hardware to process yet?
if (samples >= packetSamples) {
// audio capture is always MONO16.
static int16_t sampbuffer[VOIP_MAX_PACKET_SAMPLES];
float voipPower = 0.0f;
int voipFrames;
int i, bytes;
if (samples > VOIP_MAX_PACKET_SAMPLES)
samples = VOIP_MAX_PACKET_SAMPLES;
// !!! FIXME: maybe separate recording from encoding, so voipPower
// !!! FIXME: updates faster than 4Hz?
samples -= samples % VOIP_MAX_FRAME_SAMPLES;
if (samples != 120 && samples != 240 && samples != 480 && samples != 960 && samples != 1920 && samples != 2880 ) {
Com_Printf("Voip: bad number of samples %d\n", samples);
return;
}
voipFrames = samples / VOIP_MAX_FRAME_SAMPLES;
S_Capture(samples, (byte *) sampbuffer); // grab from audio card.
// check the "power" of this packet...
for (i = 0; i < samples; i++) {
const float flsamp = (float) sampbuffer[i];
const float s = fabs(flsamp);
voipPower += s * s;
sampbuffer[i] = (int16_t) ((flsamp) * audioMult);
}
// encode raw audio samples into Opus data...
bytes = opus_encode(clc.opusEncoder, sampbuffer, samples,
(unsigned char *) clc.voipOutgoingData,
sizeof (clc.voipOutgoingData));
if ( bytes <= 0 ) {
Com_DPrintf("VoIP: Error encoding %d samples\n", samples);
bytes = 0;
}
clc.voipPower = (voipPower / (32768.0f * 32768.0f *
((float) samples))) * 100.0f;
if ((useVad) && (clc.voipPower < cl_voipVADThreshold->value)) {
CL_VoipNewGeneration(); // no "talk" for at least 1/4 second.
} else {
clc.voipOutgoingDataSize = bytes;
clc.voipOutgoingDataFrames = voipFrames;
Com_DPrintf("VoIP: Send %d frames, %d bytes, %f power\n",
voipFrames, bytes, clc.voipPower);
#if 0
static FILE *encio = NULL;
if (encio == NULL) encio = fopen("voip-outgoing-encoded.bin", "wb");
if (encio != NULL) { fwrite(clc.voipOutgoingData, bytes, 1, encio); fflush(encio); }
static FILE *decio = NULL;
if (decio == NULL) decio = fopen("voip-outgoing-decoded.bin", "wb");
if (decio != NULL) { fwrite(sampbuffer, voipFrames * VOIP_MAX_FRAME_SAMPLES * 2, 1, decio); fflush(decio); }
#endif
}
}
}
// User requested we stop recording, and we've now processed the last of
// any previously-buffered data. Pause the capture device, etc.
if (finalFrame) {
S_StopCapture();
S_MasterGain(1.0f);
clc.voipPower = 0.0f; // force this value so it doesn't linger.
}
}
#endif
/*
=======================================================================
CLIENT RELIABLE COMMAND COMMUNICATION
=======================================================================
*/
/*
======================
CL_AddReliableCommand
The given command will be transmitted to the server, and is gauranteed to
not have future usercmd_t executed before it is executed
======================
*/
void CL_AddReliableCommand(const char *cmd, qboolean isDisconnectCmd)
{
int unacknowledged = clc.reliableSequence - clc.reliableAcknowledge;
// if we would be losing an old command that hasn't been acknowledged,
// we must drop the connection
// also leave one slot open for the disconnect command in this case.
if ((isDisconnectCmd && unacknowledged > MAX_RELIABLE_COMMANDS) ||
(!isDisconnectCmd && unacknowledged >= MAX_RELIABLE_COMMANDS))
{
if(com_errorEntered)
return;
else
Com_Error(ERR_DROP, "Client command overflow");
}
Q_strncpyz(clc.reliableCommands[++clc.reliableSequence & (MAX_RELIABLE_COMMANDS - 1)],
cmd, sizeof(*clc.reliableCommands));
}
/*
=======================================================================
CLIENT SIDE DEMO RECORDING
=======================================================================
*/
/*
====================
CL_WriteDemoMessage
Dumps the current net message, prefixed by the length
====================
*/
void CL_WriteDemoMessage( msg_t *msg, int headerBytes ) {
int len, swlen;
// write the packet sequence
len = clc.serverMessageSequence;
swlen = LittleLong( len );
FS_Write( &swlen, 4, clc.demofile );
// skip the packet sequencing information
len = msg->cursize - headerBytes;
swlen = LittleLong( len );
FS_Write( &swlen, 4, clc.demofile );
FS_Write( msg->data + headerBytes, len, clc.demofile );
}
/*
====================
CL_StopRecording_f
stop recording a demo
====================
*/
void CL_StopRecord_f( void ) {
int len;
if ( !clc.demorecording ) {
Com_Printf( "Not recording a demo.\n" );
return;
}
// finish up
len = -1;
FS_Write( &len, 4, clc.demofile );
FS_Write( &len, 4, clc.demofile );
FS_FCloseFile( clc.demofile );
clc.demofile = 0;
clc.demorecording = qfalse;
Com_Printf( "Stopped demo.\n" );
}
/*
==================
CL_DemoFilename
==================
*/
void CL_DemoFilename( int number, char *fileName, int fileNameSize ) {
int a,b,c,d;
if(number < 0 || number > 9999)
number = 9999;
a = number / 1000;
number -= a * 1000;
b = number / 100;
number -= b * 100;
c = number / 10;
number -= c * 10;
d = number;
Com_sprintf( fileName, fileNameSize, "demo%i%i%i%i"
, a, b, c, d );
}
/*
====================
CL_Record_f
record <demoname>
Begins recording a demo from the current position
====================
*/
static char demoName[MAX_QPATH]; // compiler bug workaround
void CL_Record_f( void ) {
char name[MAX_OSPATH];
byte bufData[MAX_MSGLEN];
msg_t buf;
int i;
int len;
entityState_t *ent;
entityState_t nullstate;
char *s;
if ( Cmd_Argc() > 2 ) {
Com_Printf( "record <demoname>\n" );
return;
}
if ( clc.demorecording ) {
Com_Printf( "Already recording.\n" );
return;
}
if ( clc.state != CA_ACTIVE ) {
Com_Printf( "You must be in a level to record.\n" );
return;
}
// sync 0 doesn't prevent recording, so not forcing it off .. everyone does g_sync 1 ; record ; g_sync 0 ..
if ( NET_IsLocalAddress( clc.serverAddress ) && !Cvar_VariableValue( "g_synchronousClients" ) ) {
Com_Printf (S_COLOR_YELLOW "WARNING: You should set 'g_synchronousClients 1' for smoother demo recording\n");
}
if ( Cmd_Argc() == 2 ) {
s = Cmd_Argv( 1 );
Q_strncpyz( demoName, s, sizeof( demoName ) );
#ifdef LEGACY_PROTOCOL
if(clc.compat)
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_legacyprotocol->integer);
else
#endif
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_protocol->integer);
} else {
int number;
// scan for a free demo name
for ( number = 0 ; number <= 9999 ; number++ ) {
CL_DemoFilename( number, demoName, sizeof( demoName ) );
#ifdef LEGACY_PROTOCOL
if(clc.compat)
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_legacyprotocol->integer);
else
#endif
Com_sprintf(name, sizeof(name), "demos/%s.%s%d", demoName, DEMOEXT, com_protocol->integer);
if (!FS_FileExists(name))
break; // file doesn't exist
}
}
// open the demo file
Com_Printf( "recording to %s.\n", name );
clc.demofile = FS_FOpenFileWrite( name );
if ( !clc.demofile ) {
Com_Printf( "ERROR: couldn't open.\n" );
return;
}
clc.demorecording = qtrue;
Q_strncpyz( clc.demoName, demoName, sizeof( clc.demoName ) );
// don't start saving messages until a non-delta compressed message is received
clc.demowaiting = qtrue;
// write out the gamestate message
MSG_Init( &buf, bufData, sizeof( bufData ) );
MSG_Bitstream( &buf );
// NOTE, MRE: all server->client messages now acknowledge
MSG_WriteLong( &buf, clc.reliableSequence );
MSG_WriteByte( &buf, svc_gamestate );
MSG_WriteLong( &buf, clc.serverCommandSequence );
// configstrings
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
if ( !cl.gameState.stringOffsets[i] ) {
continue;
}
s = cl.gameState.stringData + cl.gameState.stringOffsets[i];
MSG_WriteByte( &buf, svc_configstring );
MSG_WriteShort( &buf, i );
MSG_WriteBigString( &buf, s );
}
// baselines
Com_Memset( &nullstate, 0, sizeof( nullstate ) );
for ( i = 0; i < MAX_GENTITIES ; i++ ) {
ent = &cl.entityBaselines[i];
if ( !ent->number ) {
continue;
}
MSG_WriteByte( &buf, svc_baseline );
MSG_WriteDeltaEntity( &buf, &nullstate, ent, qtrue );
}
MSG_WriteByte( &buf, svc_EOF );
// finished writing the gamestate stuff
// write the client num
MSG_WriteLong( &buf, clc.clientNum );
// write the checksum feed
MSG_WriteLong( &buf, clc.checksumFeed );
// finished writing the client packet
MSG_WriteByte( &buf, svc_EOF );
// write it to the demo file
len = LittleLong( clc.serverMessageSequence - 1 );
FS_Write( &len, 4, clc.demofile );
len = LittleLong( buf.cursize );
FS_Write( &len, 4, clc.demofile );
FS_Write( buf.data, buf.cursize, clc.demofile );
// the rest of the demo file will be copied from net messages
}
/*
=======================================================================
CLIENT SIDE DEMO PLAYBACK
=======================================================================
*/
/*
=================
CL_DemoFrameDurationSDev
=================
*/
static float CL_DemoFrameDurationSDev( void )
{
int i;
int numFrames;
float mean = 0.0f;
float variance = 0.0f;
if( ( clc.timeDemoFrames - 1 ) > MAX_TIMEDEMO_DURATIONS )
numFrames = MAX_TIMEDEMO_DURATIONS;
else
numFrames = clc.timeDemoFrames - 1;
for( i = 0; i < numFrames; i++ )
mean += clc.timeDemoDurations[ i ];
mean /= numFrames;
for( i = 0; i < numFrames; i++ )
{
float x = clc.timeDemoDurations[ i ];
variance += ( ( x - mean ) * ( x - mean ) );
}
variance /= numFrames;
return sqrt( variance );
}
/*
=================
CL_DemoCompleted
=================
*/
void CL_DemoCompleted( void )
{
char buffer[ MAX_STRING_CHARS ];
if( cl_timedemo && cl_timedemo->integer )
{
int time;
time = Sys_Milliseconds() - clc.timeDemoStart;
if( time > 0 )
{
// Millisecond times are frame durations:
// minimum/average/maximum/std deviation
Com_sprintf( buffer, sizeof( buffer ),
"%i frames %3.1f seconds %3.1f fps %d.0/%.1f/%d.0/%.1f ms\n",
clc.timeDemoFrames,
time/1000.0,
clc.timeDemoFrames*1000.0 / time,
clc.timeDemoMinDuration,
time / (float)clc.timeDemoFrames,
clc.timeDemoMaxDuration,
CL_DemoFrameDurationSDev( ) );
Com_Printf( "%s", buffer );
// Write a log of all the frame durations
if( cl_timedemoLog && strlen( cl_timedemoLog->string ) > 0 )
{
int i;
int numFrames;
fileHandle_t f;
if( ( clc.timeDemoFrames - 1 ) > MAX_TIMEDEMO_DURATIONS )
numFrames = MAX_TIMEDEMO_DURATIONS;
else
numFrames = clc.timeDemoFrames - 1;
f = FS_FOpenFileWrite( cl_timedemoLog->string );
if( f )
{
FS_Printf( f, "# %s", buffer );
for( i = 0; i < numFrames; i++ )
FS_Printf( f, "%d\n", clc.timeDemoDurations[ i ] );
FS_FCloseFile( f );
Com_Printf( "%s written\n", cl_timedemoLog->string );
}
else
{
Com_Printf( "Couldn't open %s for writing\n",
cl_timedemoLog->string );
}
}
}
}
CL_Disconnect( qtrue );
CL_NextDemo();
}
/*
=================
CL_ReadDemoMessage
=================
*/
void CL_ReadDemoMessage( void ) {
int r;
msg_t buf;
byte bufData[ MAX_MSGLEN ];
int s;
if ( !clc.demofile ) {
CL_DemoCompleted();
return;
}
// get the sequence number
r = FS_Read( &s, 4, clc.demofile );
if ( r != 4 ) {
CL_DemoCompleted();
return;
}
clc.serverMessageSequence = LittleLong( s );
// init the message
MSG_Init( &buf, bufData, sizeof( bufData ) );
// get the length
r = FS_Read( &buf.cursize, 4, clc.demofile );
if ( r != 4 ) {
CL_DemoCompleted();
return;
}
buf.cursize = LittleLong( buf.cursize );
if ( buf.cursize == -1 ) {
CL_DemoCompleted();
return;
}
if ( buf.cursize > buf.maxsize ) {
Com_Error( ERR_DROP, "CL_ReadDemoMessage: demoMsglen > MAX_MSGLEN" );
}
r = FS_Read( buf.data, buf.cursize, clc.demofile );
if ( r != buf.cursize ) {
Com_Printf( "Demo file was truncated.\n" );
CL_DemoCompleted();
return;
}
clc.lastPacketTime = cls.realtime;
buf.readcount = 0;
CL_ParseServerMessage( &buf );
}
/*
====================
CL_WalkDemoExt
====================
*/
static int CL_WalkDemoExt(char *arg, char *name, int *demofile)
{
int i = 0;
*demofile = 0;
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer > 0)
{
Com_sprintf(name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, com_legacyprotocol->integer);
FS_FOpenFileRead(name, demofile, qtrue);
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return com_legacyprotocol->integer;
}
}
if(com_protocol->integer != com_legacyprotocol->integer)
#endif
{
Com_sprintf(name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, com_protocol->integer);
FS_FOpenFileRead(name, demofile, qtrue);
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return com_protocol->integer;
}
}
Com_Printf("Not found: %s\n", name);
while(demo_protocols[i])
{
#ifdef LEGACY_PROTOCOL
if(demo_protocols[i] == com_legacyprotocol->integer)
continue;
#endif
if(demo_protocols[i] == com_protocol->integer)
continue;
Com_sprintf (name, MAX_OSPATH, "demos/%s.%s%d", arg, DEMOEXT, demo_protocols[i]);
FS_FOpenFileRead( name, demofile, qtrue );
if (*demofile)
{
Com_Printf("Demo file: %s\n", name);
return demo_protocols[i];
}
else
Com_Printf("Not found: %s\n", name);
i++;
}
return -1;
}
/*
====================
CL_CompleteDemoName
====================
*/
static void CL_CompleteDemoName( char *args, int argNum )
{
if( argNum == 2 )
{
char demoExt[ 16 ];
Com_sprintf(demoExt, sizeof(demoExt), ".%s%d", DEMOEXT, com_protocol->integer);
Field_CompleteFilename( "demos", demoExt, qtrue, qtrue );
}
}
/*
====================
CL_PlayDemo_f
demo <demoname>
====================
*/
void CL_PlayDemo_f( void ) {
char name[MAX_OSPATH];
char *arg, *ext_test;
int protocol, i;
char retry[MAX_OSPATH];
if (Cmd_Argc() != 2) {
Com_Printf ("demo <demoname>\n");
return;
}
// make sure a local server is killed
// 2 means don't force disconnect of local client
Cvar_Set( "sv_killserver", "2" );
// open the demo file
arg = Cmd_Argv(1);
CL_Disconnect( qtrue );
// check for an extension .DEMOEXT_?? (?? is protocol)
ext_test = strrchr(arg, '.');
if(ext_test && !Q_stricmpn(ext_test + 1, DEMOEXT, ARRAY_LEN(DEMOEXT) - 1))
{
protocol = atoi(ext_test + ARRAY_LEN(DEMOEXT));
for(i = 0; demo_protocols[i]; i++)
{
if(demo_protocols[i] == protocol)
break;
}
if(demo_protocols[i] || protocol == com_protocol->integer
#ifdef LEGACY_PROTOCOL
|| protocol == com_legacyprotocol->integer
#endif
)
{
Com_sprintf(name, sizeof(name), "demos/%s", arg);
FS_FOpenFileRead(name, &clc.demofile, qtrue);
}
else
{
int len;
Com_Printf("Protocol %d not supported for demos\n", protocol);
len = ext_test - arg;
if(len >= ARRAY_LEN(retry))
len = ARRAY_LEN(retry) - 1;
Q_strncpyz(retry, arg, len + 1);
retry[len] = '\0';
protocol = CL_WalkDemoExt(retry, name, &clc.demofile);
}
}
else
protocol = CL_WalkDemoExt(arg, name, &clc.demofile);
if (!clc.demofile) {
Com_Error( ERR_DROP, "couldn't open %s", name);
return;
}
Q_strncpyz( clc.demoName, arg, sizeof( clc.demoName ) );
Con_Close();
clc.state = CA_CONNECTED;
clc.demoplaying = qtrue;
Q_strncpyz( clc.servername, arg, sizeof( clc.servername ) );
#ifdef LEGACY_PROTOCOL
if(protocol <= com_legacyprotocol->integer)
clc.compat = qtrue;
else
clc.compat = qfalse;
#endif
// read demo messages until connected
while ( clc.state >= CA_CONNECTED && clc.state < CA_PRIMED ) {
CL_ReadDemoMessage();
}
// don't get the first snapshot this frame, to prevent the long
// time from the gamestate load from messing causing a time skip
clc.firstDemoFrameSkipped = qfalse;
}
/*
====================
CL_StartDemoLoop
Closing the main menu will restart the demo loop
====================
*/
void CL_StartDemoLoop( void ) {
// start the demo loop again
Cbuf_AddText( "d1\n" );
Key_SetCatcher( 0 );
}
/*
==================
CL_NextDemo
Called when a demo or cinematic finishes
If the "nextdemo" cvar is set, that command will be issued
==================
*/
void CL_NextDemo( void ) {
char v[MAX_STRING_CHARS];
Q_strncpyz( v, Cvar_VariableString( "nextdemo" ), sizeof( v ) );
v[MAX_STRING_CHARS - 1] = 0;
Com_DPrintf( "CL_NextDemo: %s\n", v );
if ( !v[0] ) {
return;
}
Cvar_Set( "nextdemo","" );
Cbuf_AddText( v );
Cbuf_AddText( "\n" );
Cbuf_Execute();
}
/*
====================
Wave file saving functions
====================
void CL_WriteWaveOpen() {
// we will just save it as a 16bit stereo 22050kz pcm file
clc.wavefile = FS_FOpenFileWrite( "demodata.pcm" );
clc.wavetime = -1;
}
void CL_WriteWaveClose() {
// and we're outta here
FS_FCloseFile( clc.wavefile );
}
extern int s_soundtime;
extern portable_samplepair_t *paintbuffer;
void CL_WriteWaveFilePacket() {
int total, i;
if ( clc.wavetime == -1 ) {
clc.wavetime = s_soundtime;
return;
}
total = s_soundtime - clc.wavetime;
clc.wavetime = s_soundtime;
for ( i = 0; i < total; i++ ) {
int parm;
short out;
parm = ( paintbuffer[i].left ) >> 8;
if ( parm > 32767 ) {
parm = 32767;
}
if ( parm < -32768 ) {
parm = -32768;
}
out = parm;
FS_Write( &out, 2, clc.wavefile );
parm = ( paintbuffer[i].right ) >> 8;
if ( parm > 32767 ) {
parm = 32767;
}
if ( parm < -32768 ) {
parm = -32768;
}
out = parm;
FS_Write( &out, 2, clc.wavefile );
}
}
*/
//======================================================================
/*
=====================
CL_ShutdownAll
=====================
*/
void CL_ShutdownAll(qboolean shutdownRef)
{
if(CL_VideoRecording())
CL_CloseAVI();
if(clc.demorecording)
CL_StopRecord_f();
#ifdef USE_CURL
CL_cURL_Shutdown();
#endif
// clear sounds
S_DisableSounds();
// shutdown CGame
CL_ShutdownCGame();
// shutdown UI
CL_ShutdownUI();
// shutdown the renderer
if(shutdownRef)
CL_ShutdownRef();
else if(re.Shutdown)
re.Shutdown(qfalse); // don't destroy window or context
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.rendererStarted = qfalse;
cls.soundRegistered = qfalse;
}
/*
=================
CL_ClearMemory
Called by Com_GameRestart
=================
*/
void CL_ClearMemory(qboolean shutdownRef)
{
// shutdown all the client stuff
CL_ShutdownAll(shutdownRef);
// if not running a server clear the whole hunk
if ( !com_sv_running->integer ) {
// clear the whole hunk
Hunk_Clear();
// clear collision map data
CM_ClearMap();
} else {
// clear all the client data on the hunk
Hunk_ClearToMark();
}
}
/*
=================
CL_FlushMemory
Called by CL_MapLoading, CL_Connect_f, CL_PlayDemo_f, and CL_ParseGamestate the only
ways a client gets into a game
Also called by Com_Error
=================
*/
void CL_FlushMemory(void)
{
CL_ClearMemory(qfalse);
CL_StartHunkUsers(qfalse);
}
/*
=====================
CL_MapLoading
A local server is starting to load a map, so update the
screen to let the user know about it, then dump all client
memory on the hunk from cgame, ui, and renderer
=====================
*/
void CL_MapLoading( void ) {
if ( com_dedicated->integer ) {
clc.state = CA_DISCONNECTED;
Key_SetCatcher( KEYCATCH_CONSOLE );
return;
}
if ( !com_cl_running->integer ) {
return;
}
Con_Close();
Key_SetCatcher( 0 );
// if we are already connected to the local host, stay connected
if ( clc.state >= CA_CONNECTED && !Q_stricmp( clc.servername, "localhost" ) ) {
clc.state = CA_CONNECTED; // so the connect screen is drawn
Com_Memset( cls.updateInfoString, 0, sizeof( cls.updateInfoString ) );
Com_Memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) );
Com_Memset( &cl.gameState, 0, sizeof( cl.gameState ) );
clc.lastPacketSentTime = -9999;
SCR_UpdateScreen();
} else {
// clear nextmap so the cinematic shutdown doesn't execute it
Cvar_Set( "nextmap", "" );
CL_Disconnect( qtrue );
Q_strncpyz( clc.servername, "localhost", sizeof(clc.servername) );
clc.state = CA_CHALLENGING; // so the connect screen is drawn
Key_SetCatcher( 0 );
SCR_UpdateScreen();
clc.connectTime = -RETRANSMIT_TIMEOUT;
NET_StringToAdr( clc.servername, &clc.serverAddress, NA_UNSPEC);
// we don't need a challenge on the localhost
CL_CheckForResend();
}
}
/*
=====================
CL_ClearState
Called before parsing a gamestate
=====================
*/
void CL_ClearState( void ) {
// S_StopAllSounds();
memset( &cl, 0, sizeof( cl ) );
}
/*
====================
CL_UpdateGUID
update cl_guid using QKEY_FILE and optional prefix
====================
*/
static void CL_UpdateGUID( const char *prefix, int prefix_len )
{
#if !defined( USE_PBMD5 )
fileHandle_t f;
int len;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
if( len != QKEY_SIZE )
Cvar_Set( "cl_guid", "" );
else
Cvar_Set( "cl_guid", Com_MD5File( QKEY_FILE, QKEY_SIZE,
prefix, prefix_len ) );
#else
if ( !Q_stricmp( cl_cdkey, " " ) )
{
Cvar_Set( "cl_guid", "NO_GUID" );
return;
}
if ( !Q_stricmp( cl_guid->string, "unknown" ) )
Cvar_Set( "cl_guid", Com_PBMD5File( cl_cdkey ) );
else
return;
#endif
}
static void CL_OldGame(void)
{
if(cl_oldGameSet)
{
// change back to previous fs_game
cl_oldGameSet = qfalse;
Cvar_Set2("fs_game", cl_oldGame, qtrue);
FS_ConditionalRestart(clc.checksumFeed, qfalse);
}
}
/*
=====================
CL_Disconnect
Called when a connection, demo, or cinematic is being terminated.
Goes from a connected state to either a menu state or a console state
Sends a disconnect message to the server
This is also called on Com_Error and Com_Quit, so it shouldn't cause any errors
=====================
*/
void CL_Disconnect( qboolean showMainMenu ) {
if ( !com_cl_running || !com_cl_running->integer ) {
return;
}
// shutting down the client so enter full screen ui mode
Cvar_Set( "r_uiFullScreen", "1" );
if ( clc.demorecording ) {
CL_StopRecord_f();
}
if ( clc.download ) {
FS_FCloseFile( clc.download );
clc.download = 0;
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
#ifdef USE_MUMBLE
if (cl_useMumble->integer && mumble_islinked()) {
Com_Printf("Mumble: Unlinking from Mumble application\n");
mumble_unlink();
}
#endif
#ifdef USE_VOIP
if (cl_voipSend->integer) {
int tmp = cl_voipUseVAD->integer;
cl_voipUseVAD->integer = 0; // disable this for a moment.
clc.voipOutgoingDataSize = 0; // dump any pending VoIP transmission.
Cvar_Set("cl_voipSend", "0");
CL_CaptureVoip(); // clean up any state...
cl_voipUseVAD->integer = tmp;
}
if (clc.voipCodecInitialized) {
int i;
opus_encoder_destroy(clc.opusEncoder);
for (i = 0; i < MAX_CLIENTS; i++) {
opus_decoder_destroy(clc.opusDecoder[i]);
}
clc.voipCodecInitialized = qfalse;
}
Cmd_RemoveCommand ("voip");
#endif
if ( clc.demofile ) {
FS_FCloseFile( clc.demofile );
clc.demofile = 0;
}
if ( uivm && showMainMenu ) {
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NONE );
}
SCR_StopCinematic();
S_ClearSoundBuffer();
// send a disconnect message to the server
// send it a few times in case one is dropped
if ( clc.state >= CA_CONNECTED ) {
CL_AddReliableCommand("disconnect", qtrue);
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
// Remove pure paks
FS_PureServerSetLoadedPaks("", "");
FS_PureServerSetReferencedPaks( "", "" );
CL_ClearState();
// wipe the client connection
Com_Memset( &clc, 0, sizeof( clc ) );
clc.state = CA_DISCONNECTED;
// allow cheats locally
Cvar_Set( "sv_cheats", "1" );
// not connected to a pure server anymore
cl_connectedToPureServer = qfalse;
#ifdef USE_VOIP
// not connected to voip server anymore.
clc.voipEnabled = qfalse;
#endif
// Stop recording any video
if( CL_VideoRecording( ) ) {
// Finish rendering current frame
SCR_UpdateScreen( );
CL_CloseAVI( );
}
CL_UpdateGUID( NULL, 0 );
if(!noGameRestart)
CL_OldGame();
else
noGameRestart = qfalse;
}
/*
===================
CL_ForwardCommandToServer
adds the current command line as a clientCommand
things like godmode, noclip, etc, are commands directed to the server,
so when they are typed in at the console, they will need to be forwarded.
===================
*/
void CL_ForwardCommandToServer( const char *string ) {
char *cmd;
cmd = Cmd_Argv( 0 );
// ignore key up commands
if ( cmd[0] == '-' ) {
return;
}
if ( clc.demoplaying || clc.state < CA_CONNECTED || cmd[0] == '+' ) {
Com_Printf ("Unknown command \"%s" S_COLOR_WHITE "\"\n", cmd);
return;
}
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand(string, qfalse);
} else {
CL_AddReliableCommand(cmd, qfalse);
}
}
/*
===================
CL_RequestMotd
===================
*/
void CL_RequestMotd( void ) {
#ifdef UPDATE_SERVER_NAME
char info[MAX_INFO_STRING];
if ( !cl_motd->integer ) {
return;
}
Com_Printf( "Resolving %s\n", UPDATE_SERVER_NAME );
if ( !NET_StringToAdr( UPDATE_SERVER_NAME, &cls.updateServer, NA_IP ) ) {
Com_Printf( "Couldn't resolve address\n" );
return;
}
cls.updateServer.port = BigShort( PORT_UPDATE );
Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", UPDATE_SERVER_NAME,
cls.updateServer.ip[0], cls.updateServer.ip[1],
cls.updateServer.ip[2], cls.updateServer.ip[3],
BigShort( cls.updateServer.port ) );
info[0] = 0;
Com_sprintf( cls.updateChallenge, sizeof( cls.updateChallenge ), "%i", ( (rand() << 16 ) ^ rand() ) ^ Com_Milliseconds() );
Info_SetValueForKey( info, "challenge", cls.updateChallenge );
Info_SetValueForKey( info, "renderer", cls.glconfig.renderer_string );
Info_SetValueForKey( info, "version", com_version->string );
NET_OutOfBandPrint( NS_CLIENT, cls.updateServer, "getmotd \"%s\"\n", info );
#endif
}
/*
===================
CL_RequestAuthorization
Authorization server protocol
-----------------------------
All commands are text in Q3 out of band packets (leading 0xff 0xff 0xff 0xff).
Whenever the client tries to get a challenge from the server it wants to
connect to, it also blindly fires off a packet to the authorize server:
getKeyAuthorize <challenge> <cdkey>
cdkey may be "demo"
#OLD The authorize server returns a:
#OLD
#OLD keyAthorize <challenge> <accept | deny>
#OLD
#OLD A client will be accepted if the cdkey is valid and it has not been used by any other IP
#OLD address in the last 15 minutes.
The server sends a:
getIpAuthorize <challenge> <ip>
The authorize server returns a:
ipAuthorize <challenge> <accept | deny | demo | unknown >
A client will be accepted if a valid cdkey was sent by that ip (only) in the last 15 minutes.
If no response is received from the authorize server after two tries, the client will be let
in anyway.
===================
*/
#ifndef STANDALONE
#ifdef USE_AUTHORIZE_SERVER
void CL_RequestAuthorization( void ) {
char nums[64];
int i, j, l;
cvar_t *fs;
if ( !cls.authorizeServer.port ) {
Com_Printf( "Resolving %s\n", AUTHORIZE_SERVER_NAME );
if ( !NET_StringToAdr( AUTHORIZE_SERVER_NAME, &cls.authorizeServer, NA_IP ) ) {
Com_Printf( "Couldn't resolve address\n" );
return;
}
cls.authorizeServer.port = BigShort( PORT_AUTHORIZE );
Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", AUTHORIZE_SERVER_NAME,
cls.authorizeServer.ip[0], cls.authorizeServer.ip[1],
cls.authorizeServer.ip[2], cls.authorizeServer.ip[3],
BigShort( cls.authorizeServer.port ) );
}
if ( cls.authorizeServer.type == NA_BAD ) {
return;
}
// only grab the alphanumeric values from the cdkey, to avoid any dashes or spaces
j = 0;
l = strlen( cl_cdkey );
if ( l > 32 ) {
l = 32;
}
for ( i = 0 ; i < l ; i++ ) {
if ( ( cl_cdkey[i] >= '0' && cl_cdkey[i] <= '9' )
|| ( cl_cdkey[i] >= 'a' && cl_cdkey[i] <= 'z' )
|| ( cl_cdkey[i] >= 'A' && cl_cdkey[i] <= 'Z' ) ) {
nums[j] = cl_cdkey[i];
j++;
}
}
nums[j] = 0;
fs = Cvar_Get( "cl_anonymous", "0", CVAR_INIT | CVAR_SYSTEMINFO );
NET_OutOfBandPrint(NS_CLIENT, cls.authorizeServer, "getKeyAuthorize %i %s", fs->integer, nums );
}
#endif
#endif
/*
======================================================================
CONSOLE COMMANDS
======================================================================
*/
/*
==================
CL_ForwardToServer_f
==================
*/
void CL_ForwardToServer_f( void ) {
if ( clc.state != CA_ACTIVE || clc.demoplaying ) {
Com_Printf( "Not connected to a server.\n" );
return;
}
// don't forward the first argument
if ( Cmd_Argc() > 1 ) {
CL_AddReliableCommand(Cmd_Args(), qfalse);
}
}
/*
==================
CL_Disconnect_f
==================
*/
void CL_Disconnect_f( void ) {
SCR_StopCinematic();
Cvar_Set("ui_singlePlayerActive", "0");
if ( clc.state != CA_DISCONNECTED && clc.state != CA_CINEMATIC ) {
Com_Error( ERR_DISCONNECT, "Disconnected from server" );
}
}
/*
================
CL_Reconnect_f
================
*/
void CL_Reconnect_f( void ) {
if ( !strlen( cl_reconnectArgs ) )
return;
Cvar_Set("ui_singlePlayerActive", "0");
Cbuf_AddText( va("connect %s\n", cl_reconnectArgs ) );
}
/*
================
CL_Connect_f
================
*/
void CL_Connect_f( void ) {
char *server;
const char *serverString;
int argc = Cmd_Argc();
netadrtype_t family = NA_UNSPEC;
if ( argc != 2 && argc != 3 ) {
Com_Printf( "usage: connect [-4|-6] server\n");
return;
}
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
// save arguments for reconnect
Q_strncpyz( cl_reconnectArgs, Cmd_Args(), sizeof( cl_reconnectArgs ) );
Cvar_Set("ui_singlePlayerActive", "0");
S_StopAllSounds(); // NERVE - SMF
// starting to load a map so we get out of full screen ui mode
Cvar_Set( "r_uiFullScreen", "0" );
// fire a message off to the motd server
CL_RequestMotd();
// clear any previous "server full" type messages
clc.serverMessage[0] = 0;
if ( com_sv_running->integer && !strcmp( server, "localhost" ) ) {
// if running a local server, kill it
SV_Shutdown( "Server quit" );
}
// make sure a local server is killed
Cvar_Set( "sv_killserver", "1" );
SV_Frame( 0 );
noGameRestart = qtrue;
CL_Disconnect( qtrue );
Con_Close();
Q_strncpyz( clc.servername, server, sizeof(clc.servername) );
if (!NET_StringToAdr(clc.servername, &clc.serverAddress, family) ) {
Com_Printf( "Bad server address\n" );
clc.state = CA_DISCONNECTED;
return;
}
if ( clc.serverAddress.port == 0 ) {
clc.serverAddress.port = BigShort( PORT_SERVER );
}
serverString = NET_AdrToStringwPort(clc.serverAddress);
Com_Printf( "%s resolved to %s\n", clc.servername, serverString);
if( cl_guidServerUniq->integer )
CL_UpdateGUID( serverString, strlen( serverString ) );
else
CL_UpdateGUID( NULL, 0 );
// if we aren't playing on a lan, we need to authenticate
// with the cd key
if(NET_IsLocalAddress(clc.serverAddress))
clc.state = CA_CHALLENGING;
else
{
clc.state = CA_CONNECTING;
// Set a client challenge number that ideally is mirrored back by the server.
clc.challenge = ((rand() << 16) ^ rand()) ^ Com_Milliseconds();
}
// show_bug.cgi?id=507
// prepare to catch a connection process that would turn bad
Cvar_Set( "com_errorDiagnoseIP", NET_AdrToString( clc.serverAddress ) );
// ATVI Wolfenstein Misc #439
// we need to setup a correct default for this, otherwise the first val we set might reappear
Cvar_Set( "com_errorMessage", "" );
Key_SetCatcher( 0 );
clc.connectTime = -99999; // CL_CheckForResend() will fire immediately
clc.connectPacketCount = 0;
// server connection string
Cvar_Set( "cl_currentServerAddress", server );
// NERVE - SMF - reset some cvars
Cvar_Set( "mp_playerType", "0" );
Cvar_Set( "mp_currentPlayerType", "0" );
Cvar_Set( "mp_weapon", "0" );
Cvar_Set( "mp_team", "0" );
Cvar_Set( "mp_currentTeam", "0" );
Cvar_Set( "ui_limboOptions", "0" );
Cvar_Set( "ui_limboPrevOptions", "0" );
Cvar_Set( "ui_limboObjective", "0" );
// -NERVE - SMF
}
#define MAX_RCON_MESSAGE 1024
/*
==================
CL_CompleteRcon
==================
*/
static void CL_CompleteRcon( char *args, int argNum )
{
if( argNum == 2 )
{
// Skip "rcon "
char *p = Com_SkipTokens( args, 1, " " );
if( p > args )
Field_CompleteCommand( p, qtrue, qtrue );
}
}
/*
=====================
CL_Rcon_f
Send the rest of the command line over as
an unconnected command.
=====================
*/
void CL_Rcon_f( void ) {
char message[MAX_RCON_MESSAGE];
netadr_t to;
if ( !rcon_client_password->string[0] ) {
Com_Printf( "You must set 'rconpassword' before\n"
"issuing an rcon command.\n" );
return;
}
message[0] = -1;
message[1] = -1;
message[2] = -1;
message[3] = -1;
message[4] = 0;
Q_strcat (message, MAX_RCON_MESSAGE, "rcon ");
Q_strcat (message, MAX_RCON_MESSAGE, rcon_client_password->string);
Q_strcat (message, MAX_RCON_MESSAGE, " ");
Q_strcat (message, MAX_RCON_MESSAGE, Cmd_Cmd()+5);
if ( clc.state >= CA_CONNECTED ) {
to = clc.netchan.remoteAddress;
} else {
if ( !strlen( rconAddress->string ) ) {
Com_Printf( "You must either be connected,\n"
"or set the 'rconAddress' cvar\n"
"to issue rcon commands\n" );
return;
}
NET_StringToAdr (rconAddress->string, &to, NA_UNSPEC);
if ( to.port == 0 ) {
to.port = BigShort( PORT_SERVER );
}
}
NET_SendPacket( NS_CLIENT, strlen( message ) + 1, message, to );
}
/*
=================
CL_SendPureChecksums
=================
*/
void CL_SendPureChecksums( void ) {
char cMsg[MAX_INFO_VALUE];
// if we are pure we need to send back a command with our referenced pk3 checksums
Com_sprintf(cMsg, sizeof(cMsg), "cp %d %s", cl.serverId, FS_ReferencedPakPureChecksums());
CL_AddReliableCommand(cMsg, qfalse);
}
/*
=================
CL_ResetPureClientAtServer
=================
*/
void CL_ResetPureClientAtServer( void ) {
CL_AddReliableCommand("vdr", qfalse);
}
/*
=================
CL_Vid_Restart_f
Restart the video subsystem
we also have to reload the UI and CGame because the renderer
doesn't know what graphics to reload
=================
*/
void CL_Vid_Restart_f( void ) {
// RF, don't show percent bar, since the memory usage will just sit at the same level anyway
Cvar_Set( "com_expectedhunkusage", "-1" );
// Settings may have changed so stop recording now
if( CL_VideoRecording( ) ) {
CL_CloseAVI( );
}
if(clc.demorecording)
CL_StopRecord_f();
// don't let them loop during the restart
S_StopAllSounds();
if(!FS_ConditionalRestart(clc.checksumFeed, qtrue))
{
// if not running a server clear the whole hunk
if(com_sv_running->integer)
{
// clear all the client data on the hunk
Hunk_ClearToMark();
}
else
{
// clear the whole hunk
Hunk_Clear();
}
// shutdown the UI
CL_ShutdownUI();
// shutdown the CGame
CL_ShutdownCGame();
// shutdown the renderer and clear the renderer interface
CL_ShutdownRef();
// client is no longer pure untill new checksums are sent
CL_ResetPureClientAtServer();
// clear pak references
FS_ClearPakReferences( FS_UI_REF | FS_CGAME_REF );
// reinitialize the filesystem if the game directory or checksum has changed
S_BeginRegistration(); // all sound handles are now invalid
cls.rendererStarted = qfalse;
cls.uiStarted = qfalse;
cls.cgameStarted = qfalse;
cls.soundRegistered = qfalse;
autoupdateChecked = qfalse;
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
// initialize the renderer interface
CL_InitRef();
// startup all the client stuff
CL_StartHunkUsers(qfalse);
// start the cgame if connected
if(clc.state > CA_CONNECTED && clc.state != CA_CINEMATIC)
{
cls.cgameStarted = qtrue;
CL_InitCGame();
// send pure checksums
CL_SendPureChecksums();
}
}
}
/*
=================
CL_UI_Restart_f
Restart the ui subsystem
=================
*/
void CL_UI_Restart_f( void ) { // NERVE - SMF
// shutdown the UI
CL_ShutdownUI();
autoupdateChecked = qfalse;
// init the UI
CL_InitUI();
}
/*
=================
CL_Snd_Shutdown
Shut down the sound subsystem
=================
*/
void CL_Snd_Shutdown(void)
{
S_Shutdown();
cls.soundStarted = qfalse;
}
/*
=================
CL_Snd_Restart_f
Restart the sound subsystem
The cgame and game must also be forced to restart because
handles will be invalid
=================
*/
void CL_Snd_Restart_f(void)
{
CL_Snd_Shutdown();
// sound will be reinitialized by vid_restart
CL_Vid_Restart_f();
}
/*
==================
CL_PK3List_f
==================
*/
void CL_OpenedPK3List_f( void ) {
Com_Printf( "Opened PK3 Names: %s\n", FS_LoadedPakNames() );
}
/*
==================
CL_PureList_f
==================
*/
void CL_ReferencedPK3List_f( void ) {
Com_Printf( "Referenced PK3 Names: %s\n", FS_ReferencedPakNames() );
}
/*
==================
CL_Configstrings_f
==================
*/
void CL_Configstrings_f( void ) {
int i;
int ofs;
if ( clc.state != CA_ACTIVE ) {
Com_Printf( "Not connected to a server.\n" );
return;
}
for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
ofs = cl.gameState.stringOffsets[ i ];
if ( !ofs ) {
continue;
}
Com_Printf( "%4i: %s\n", i, cl.gameState.stringData + ofs );
}
}
/*
==============
CL_Clientinfo_f
==============
*/
void CL_Clientinfo_f( void ) {
Com_Printf( "--------- Client Information ---------\n" );
Com_Printf( "state: %i\n", clc.state );
Com_Printf( "Server: %s\n", clc.servername );
Com_Printf( "User info settings:\n" );
Info_Print( Cvar_InfoString( CVAR_USERINFO ) );
Com_Printf( "--------------------------------------\n" );
}
//====================================================================
/*
=================
CL_DownloadsComplete
Called when all downloading has been completed
=================
*/
void CL_DownloadsComplete( void ) {
#ifndef _WIN32
char *fs_write_path;
#endif
char *fn;
// DHM - Nerve :: Auto-update (not finished yet)
if ( autoupdateStarted ) {
if ( strlen( autoupdateFilename ) > 4 ) {
#ifdef _WIN32
// win32's Sys_StartProcess prepends the current dir
fn = va( "%s/%s", FS_ShiftStr( AUTOUPDATE_DIR, AUTOUPDATE_DIR_SHIFT ), autoupdateFilename );
#else
fs_write_path = Cvar_VariableString( "fs_homepath" );
fn = FS_BuildOSPath( fs_write_path, FS_ShiftStr( AUTOUPDATE_DIR, AUTOUPDATE_DIR_SHIFT ), autoupdateFilename );
#ifdef __linux__
Sys_Chmod( fn, S_IXUSR );
#endif
#endif
Sys_StartProcess( fn, qtrue );
}
autoupdateStarted = qfalse;
CL_Disconnect( qtrue );
return;
}
#ifdef USE_CURL
// if we downloaded with cURL
if(clc.cURLUsed) {
clc.cURLUsed = qfalse;
CL_cURL_Shutdown();
if( clc.cURLDisconnected ) {
if(clc.downloadRestart) {
FS_Restart(clc.checksumFeed);
clc.downloadRestart = qfalse;
}
clc.cURLDisconnected = qfalse;
CL_Reconnect_f();
return;
}
}
#endif
// if we downloaded files we need to restart the file system
if ( clc.downloadRestart ) {
clc.downloadRestart = qfalse;
FS_Restart( clc.checksumFeed ); // We possibly downloaded a pak, restart the file system to load it
// inform the server so we get new gamestate info
CL_AddReliableCommand( "donedl", qfalse );
// by sending the donedl command we request a new gamestate
// so we don't want to load stuff yet
return;
}
// let the client game init and load data
clc.state = CA_LOADING;
Com_EventLoop();
// if the gamestate was changed by calling Com_EventLoop
// then we loaded everything already and we don't want to do it again.
if ( clc.state != CA_LOADING ) {
return;
}
// starting to load a map so we get out of full screen ui mode
Cvar_Set( "r_uiFullScreen", "0" );
// flush client memory and start loading stuff
// this will also (re)load the UI
// if this is a local client then only the client part of the hunk
// will be cleared, note that this is done after the hunk mark has been set
CL_FlushMemory();
// initialize the CGame
cls.cgameStarted = qtrue;
CL_InitCGame();
// set pure checksums
CL_SendPureChecksums();
CL_WritePacket();
CL_WritePacket();
CL_WritePacket();
}
/*
=================
CL_BeginDownload
Requests a file to download from the server. Stores it in the current
game directory.
=================
*/
void CL_BeginDownload( const char *localName, const char *remoteName ) {
Com_DPrintf( "***** CL_BeginDownload *****\n"
"Localname: %s\n"
"Remotename: %s\n"
"****************************\n", localName, remoteName );
Q_strncpyz( clc.downloadName, localName, sizeof( clc.downloadName ) );
Com_sprintf( clc.downloadTempName, sizeof( clc.downloadTempName ), "%s.tmp", localName );
// Set so UI gets access to it
Cvar_Set( "cl_downloadName", remoteName );
Cvar_Set( "cl_downloadSize", "0" );
Cvar_Set( "cl_downloadCount", "0" );
Cvar_SetValue( "cl_downloadTime", cls.realtime );
clc.downloadBlock = 0; // Starting new file
clc.downloadCount = 0;
CL_AddReliableCommand( va( "download %s", remoteName ), qfalse );
}
/*
=================
CL_NextDownload
A download completed or failed
=================
*/
void CL_NextDownload( void ) {
char *s;
char *remoteName, *localName;
qboolean useCURL = qfalse;
// A download has finished, check whether this matches a referenced checksum
if( *clc.downloadName && !autoupdateStarted ) {
char *zippath = FS_BuildOSPath(Cvar_VariableString("fs_homepath"), clc.downloadName, "");
zippath[strlen(zippath)-1] = '\0';
if(!FS_CompareZipChecksum(zippath))
Com_Error(ERR_DROP, "Incorrect checksum for file: %s", clc.downloadName);
}
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set("cl_downloadName", "");
// We are looking to start a download here
if ( *clc.downloadList ) {
s = clc.downloadList;
// format is:
// @remotename@localname@remotename@localname, etc.
if ( *s == '@' ) {
s++;
}
remoteName = s;
if ( ( s = strchr( s, '@' ) ) == NULL ) {
CL_DownloadsComplete();
return;
}
*s++ = 0;
localName = s;
if ( ( s = strchr( s, '@' ) ) != NULL ) {
*s++ = 0;
} else {
s = localName + strlen( localName ); // point at the nul byte
}
#ifdef USE_CURL
if(!(cl_allowDownload->integer & DLF_NO_REDIRECT)) {
if(clc.sv_allowDownload & DLF_NO_REDIRECT) {
Com_Printf("WARNING: server does not "
"allow download redirection "
"(sv_allowDownload is %d)\n",
clc.sv_allowDownload);
}
else if(!*clc.sv_dlURL) {
Com_Printf("WARNING: server allows "
"download redirection, but does not "
"have sv_dlURL set\n");
}
else if(!CL_cURL_Init()) {
Com_Printf("WARNING: could not load "
"cURL library\n");
}
else {
CL_cURL_BeginDownload(localName, va("%s/%s",
clc.sv_dlURL, remoteName));
useCURL = qtrue;
}
}
else if(!(clc.sv_allowDownload & DLF_NO_REDIRECT)) {
Com_Printf("WARNING: server allows download "
"redirection, but it disabled by client "
"configuration (cl_allowDownload is %d)\n",
cl_allowDownload->integer);
}
#endif /* USE_CURL */
if(!useCURL) {
if((cl_allowDownload->integer & DLF_NO_UDP)) {
Com_Error(ERR_DROP, "UDP Downloads are "
"disabled on your client. "
"(cl_allowDownload is %d)",
cl_allowDownload->integer);
return;
}
else {
CL_BeginDownload( localName, remoteName );
}
}
clc.downloadRestart = qtrue;
// move over the rest
memmove( clc.downloadList, s, strlen( s ) + 1 );
return;
}
CL_DownloadsComplete();
}
/*
=================
CL_InitDownloads
After receiving a valid game state, we valid the cgame and local zip files here
and determine if we need to download them
=================
*/
void CL_InitDownloads( void ) {
#ifndef PRE_RELEASE_DEMO
char missingfiles[1024];
char *dir = FS_ShiftStr( AUTOUPDATE_DIR, AUTOUPDATE_DIR_SHIFT );
if ( autoupdateStarted && NET_CompareAdr( cls.autoupdateServer, clc.serverAddress ) ) {
if ( strlen( cl_updatefiles->string ) > 4 ) {
Q_strncpyz( autoupdateFilename, cl_updatefiles->string, sizeof( autoupdateFilename ) );
Q_strncpyz( clc.downloadList, va( "@%s/%s@%s/%s", dir, cl_updatefiles->string, dir, cl_updatefiles->string ), MAX_INFO_STRING );
clc.state = CA_CONNECTED;
CL_NextDownload();
return;
}
} else {
if ( !(cl_allowDownload->integer & DLF_ENABLE) ) {
// autodownload is disabled on the client
// but it's possible that some referenced files on the server are missing
// whatever autodownlad configuration, store missing files in a cvar, use later in the ui maybe
if ( FS_ComparePaks( missingfiles, sizeof( missingfiles ), qfalse ) ) {
Cvar_Set( "com_missingFiles", missingfiles );
} else {
Cvar_Set( "com_missingFiles", "" );
}
Com_Printf( "\nWARNING: You are missing some files referenced by the server:\n%s"
"You might not be able to join the game\n"
"Go to the setting menu to turn on autodownload, or get the file elsewhere\n\n", missingfiles );
}
else if ( FS_ComparePaks( clc.downloadList, sizeof( clc.downloadList ), qtrue ) ) {
// this gets printed to UI, i18n
Com_Printf( CL_TranslateStringBuf( "Need paks: %s\n" ), clc.downloadList );
if ( *clc.downloadList ) {
// if autodownloading is not enabled on the server
clc.state = CA_CONNECTED;
*clc.downloadTempName = *clc.downloadName = 0;
Cvar_Set( "cl_downloadName", "" );
CL_NextDownload();
return;
}
}
}
#endif
CL_DownloadsComplete();
}
/*
=================
CL_CheckForResend
Resend a connect message if the last one has timed out
=================
*/
void CL_CheckForResend( void ) {
int port;
char info[MAX_INFO_STRING];
char data[MAX_INFO_STRING + 10];
// don't send anything if playing back a demo
if ( clc.demoplaying ) {
return;
}
// resend if we haven't gotten a reply yet
if ( clc.state != CA_CONNECTING && clc.state != CA_CHALLENGING ) {
return;
}
if ( cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT ) {
return;
}
clc.connectTime = cls.realtime; // for retransmit requests
clc.connectPacketCount++;
switch ( clc.state ) {
case CA_CONNECTING:
// requesting a challenge .. IPv6 users always get in as authorize server supports no ipv6.
#ifndef STANDALONE
#ifdef USE_AUTHORIZE_SERVER
if (!com_standalone->integer && clc.serverAddress.type == NA_IP && !Sys_IsLANAddress( clc.serverAddress ) )
CL_RequestAuthorization();
#endif
#endif
// The challenge request shall be followed by a client challenge so no malicious server can hijack this connection.
// Add the gamename so the server knows we're running the correct game or can reject the client
// with a meaningful message
Com_sprintf(data, sizeof(data), "getchallenge %d %s", clc.challenge, com_gamename->string);
NET_OutOfBandPrint(NS_CLIENT, clc.serverAddress, "%s", data);
break;
case CA_CHALLENGING:
// sending back the challenge
port = Cvar_VariableValue( "net_qport" );
Q_strncpyz( info, Cvar_InfoString( CVAR_USERINFO ), sizeof( info ) );
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer == com_protocol->integer)
clc.compat = qtrue;
if(clc.compat)
Info_SetValueForKey(info, "protocol", va("%i", com_legacyprotocol->integer));
else
#endif
Info_SetValueForKey( info, "protocol", va("%i", com_protocol->integer ) );
Info_SetValueForKey( info, "qport", va( "%i", port ) );
Info_SetValueForKey( info, "challenge", va( "%i", clc.challenge ) );
Com_sprintf( data, sizeof(data), "connect \"%s\"", info );
NET_OutOfBandData( NS_CLIENT, clc.serverAddress, (byte *) data, strlen ( data ) );
// the most current userinfo has been sent, so watch for any
// newer changes to userinfo variables
cvar_modifiedFlags &= ~CVAR_USERINFO;
break;
default:
Com_Error( ERR_FATAL, "CL_CheckForResend: bad clc.state" );
}
}
/*
===================
CL_MotdPacket
===================
*/
void CL_MotdPacket( netadr_t from ) {
#ifdef UPDATE_SERVER_NAME
char *challenge;
char *info;
// if not from our server, ignore it
if ( !NET_CompareAdr( from, cls.updateServer ) ) {
return;
}
info = Cmd_Argv( 1 );
// check challenge
challenge = Info_ValueForKey( info, "challenge" );
if ( strcmp( challenge, cls.updateChallenge ) ) {
return;
}
challenge = Info_ValueForKey( info, "motd" );
Q_strncpyz( cls.updateInfoString, info, sizeof( cls.updateInfoString ) );
Cvar_Set( "cl_motdString", challenge );
#endif
}
/*
===================
CL_PrintPackets
an OOB message from server, with potential markups
print OOB are the only messages we handle markups in
[err_dialog]: used to indicate that the connection should be aborted
no further information, just do an error diagnostic screen afterwards
[err_prot]: HACK. This is a protocol error. The client uses a custom
protocol error message (client sided) in the diagnostic window.
The space for the error message on the connection screen is limited
to 256 chars.
===================
*/
void CL_PrintPacket( netadr_t from, msg_t *msg ) {
char *s;
s = MSG_ReadBigString( msg );
if ( !Q_stricmpn( s, "[err_dialog]", 12 ) ) {
Q_strncpyz( clc.serverMessage, s + 12, sizeof( clc.serverMessage ) );
Cvar_Set( "com_errorMessage", clc.serverMessage );
} else if ( !Q_stricmpn( s, "[err_prot]", 10 ) ) {
Q_strncpyz( clc.serverMessage, s + 10, sizeof( clc.serverMessage ) );
Cvar_Set( "com_errorMessage", CL_TranslateStringBuf( PROTOCOL_MISMATCH_ERROR_LONG ) );
} else {
Q_strncpyz( clc.serverMessage, s, sizeof( clc.serverMessage ) );
}
Com_Printf( "%s", clc.serverMessage );
}
/*
===================
CL_InitServerInfo
===================
*/
void CL_InitServerInfo( serverInfo_t *server, netadr_t *address ) {
server->adr = *address;
server->clients = 0;
server->hostName[0] = '\0';
server->mapName[0] = '\0';
server->maxClients = 0;
server->maxPing = 0;
server->minPing = 0;
server->ping = -1;
server->game[0] = '\0';
server->gameType = 0;
server->netType = 0;
server->allowAnonymous = 0;
server->friendlyFire = 0; // NERVE - SMF
server->maxlives = 0; // NERVE - SMF
server->tourney = 0; // NERVE - SMF
server->punkbuster = 0; // DHM - Nerve
server->gameName[0] = '\0'; // Arnout
server->antilag = 0;
server->g_humanplayers = 0;
server->g_needpass = 0;
}
#define MAX_SERVERSPERPACKET 256
/*
===================
CL_ServersResponsePacket
===================
*/
void CL_ServersResponsePacket( const netadr_t* from, msg_t *msg, qboolean extended ) {
int i, j, count, total;
netadr_t addresses[MAX_SERVERSPERPACKET];
int numservers;
byte* buffptr;
byte* buffend;
Com_Printf( "CL_ServersResponsePacket\n" );
if ( cls.numglobalservers == -1 ) {
// state to detect lack of servers or lack of response
cls.numglobalservers = 0;
cls.numGlobalServerAddresses = 0;
}
// parse through server response string
numservers = 0;
buffptr = msg->data;
buffend = buffptr + msg->cursize;
// advance to initial token
do
{
if(*buffptr == '\\' || (extended && *buffptr == '/'))
break;
buffptr++;
} while (buffptr < buffend);
while (buffptr + 1 < buffend)
{
// IPv4 address
if (*buffptr == '\\')
{
buffptr++;
if (buffend - buffptr < sizeof(addresses[numservers].ip) + sizeof(addresses[numservers].port) + 1)
break;
for(i = 0; i < sizeof(addresses[numservers].ip); i++)
addresses[numservers].ip[i] = *buffptr++;
addresses[numservers].type = NA_IP;
}
// IPv6 address, if it's an extended response
else if (extended && *buffptr == '/')
{
buffptr++;
if (buffend - buffptr < sizeof(addresses[numservers].ip6) + sizeof(addresses[numservers].port) + 1)
break;
for(i = 0; i < sizeof(addresses[numservers].ip6); i++)
addresses[numservers].ip6[i] = *buffptr++;
addresses[numservers].type = NA_IP6;
addresses[numservers].scope_id = from->scope_id;
}
else
// syntax error!
break;
// parse out port
addresses[numservers].port = (*buffptr++) << 8;
addresses[numservers].port += *buffptr++;
addresses[numservers].port = BigShort( addresses[numservers].port );
// syntax check
if (*buffptr != '\\' && *buffptr != '/')
break;
numservers++;
if (numservers >= MAX_SERVERSPERPACKET)
break;
}
count = cls.numglobalservers;
for (i = 0; i < numservers && count < MAX_GLOBAL_SERVERS; i++) {
// build net address
serverInfo_t *server = &cls.globalServers[count];
// Tequila: It's possible to have sent many master server requests. Then
// we may receive many times the same addresses from the master server.
// We just avoid to add a server if it is still in the global servers list.
for (j = 0; j < count; j++)
{
if (NET_CompareAdr(cls.globalServers[j].adr, addresses[i]))
break;
}
if (j < count)
continue;
CL_InitServerInfo( server, &addresses[i] );
// advance to next slot
count++;
}
// if getting the global list
if ( count >= MAX_GLOBAL_SERVERS && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS )
{
// if we couldn't store the servers in the main list anymore
for (; i < numservers && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS; i++)
{
// just store the addresses in an additional list
cls.globalServerAddresses[cls.numGlobalServerAddresses++] = addresses[i];
}
}
cls.numglobalservers = count;
total = count + cls.numGlobalServerAddresses;
Com_Printf( "%d servers parsed (total %d)\n", numservers, total );
}
/*
=================
CL_ConnectionlessPacket
Responses to broadcasts, etc
=================
*/
void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) {
char *s;
char *c;
int challenge = 0;
MSG_BeginReadingOOB( msg );
MSG_ReadLong( msg ); // skip the -1
s = MSG_ReadStringLine( msg );
Cmd_TokenizeString( s );
c = Cmd_Argv( 0 );
Com_DPrintf ("CL packet %s: %s\n", NET_AdrToStringwPort(from), c);
// challenge from the server we are connecting to
if (!Q_stricmp(c, "challengeResponse"))
{
char *strver;
int ver;
if (clc.state != CA_CONNECTING)
{
Com_DPrintf("Unwanted challenge response received. Ignored.\n");
return;
}
c = Cmd_Argv( 3 );
if(*c)
challenge = atoi(c);
strver = Cmd_Argv( 4 );
if(*strver)
{
ver = atoi(strver);
if(ver != com_protocol->integer)
{
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer > 0)
{
// Server is ioq3 but has a different protocol than we do.
// Fall back to idq3 protocol.
clc.compat = qtrue;
Com_Printf(S_COLOR_YELLOW "Warning: Server reports protocol version %d, "
"we have %d. Trying legacy protocol %d.\n",
ver, com_protocol->integer, com_legacyprotocol->integer);
}
else
#endif
{
Com_Printf(S_COLOR_YELLOW "Warning: Server reports protocol version %d, we have %d. "
"Trying anyways.\n", ver, com_protocol->integer);
}
}
}
#ifdef LEGACY_PROTOCOL
else
clc.compat = qtrue;
if(clc.compat)
{
if(!NET_CompareAdr(from, clc.serverAddress))
{
// This challenge response is not coming from the expected address.
// Check whether we have a matching client challenge to prevent
// connection hi-jacking.
if(!*c || challenge != clc.challenge)
{
Com_DPrintf("Challenge response received from unexpected source. Ignored.\n");
return;
}
}
}
else
#endif
{
if(!*c || challenge != clc.challenge)
{
Com_Printf("Bad challenge for challengeResponse. Ignored.\n");
return;
}
}
// start sending challenge response instead of challenge request packets
clc.challenge = atoi(Cmd_Argv(1));
if ( Cmd_Argc() > 2 ) {
clc.onlyVisibleClients = atoi( Cmd_Argv( 2 ) ); // DHM - Nerve
} else {
clc.onlyVisibleClients = 0;
}
clc.state = CA_CHALLENGING;
clc.connectPacketCount = 0;
clc.connectTime = -99999;
// take this address as the new server address. This allows
// a server proxy to hand off connections to multiple servers
clc.serverAddress = from;
Com_DPrintf ("challengeResponse: %d\n", clc.challenge);
return;
}
// server connection
if ( !Q_stricmp( c, "connectResponse" ) ) {
if ( clc.state >= CA_CONNECTED ) {
Com_Printf( "Dup connect received. Ignored.\n" );
return;
}
if ( clc.state != CA_CHALLENGING ) {
Com_Printf( "connectResponse packet while not connecting. Ignored.\n" );
return;
}
if ( !NET_CompareAdr( from, clc.serverAddress ) ) {
Com_Printf( "connectResponse from wrong address. Ignored.\n" );
return;
}
#ifdef LEGACY_PROTOCOL
if(!clc.compat)
#endif
{
c = Cmd_Argv(1);
if(*c)
challenge = atoi(c);
else
{
Com_Printf("Bad connectResponse received. Ignored.\n");
return;
}
if(challenge != clc.challenge)
{
Com_Printf("ConnectResponse with bad challenge received. Ignored.\n");
return;
}
}
// DHM - Nerve :: If we have completed a connection to the Auto-Update server...
if ( autoupdateChecked && NET_CompareAdr( cls.autoupdateServer, clc.serverAddress ) ) {
// Mark the client as being in the process of getting an update
if ( cl_updateavailable->integer ) {
autoupdateStarted = qtrue;
}
}
#ifdef LEGACY_PROTOCOL
Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableValue("net_qport"),
clc.challenge, clc.compat);
#else
Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableValue("net_qport"),
clc.challenge, qfalse);
#endif
clc.state = CA_CONNECTED;
clc.lastPacketSentTime = -9999; // send first packet immediately
return;
}
// server responding to an info broadcast
if ( !Q_stricmp( c, "infoResponse" ) ) {
CL_ServerInfoPacket( from, msg );
return;
}
// server responding to a get playerlist
if ( !Q_stricmp( c, "statusResponse" ) ) {
CL_ServerStatusResponse( from, msg );
return;
}
// echo request from server
if ( !Q_stricmp( c, "echo" ) ) {
NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv( 1 ) );
return;
}
// cd check
if ( !Q_stricmp( c, "keyAuthorize" ) ) {
// we don't use these now, so dump them on the floor
return;
}
// global MOTD from id
if ( !Q_stricmp( c, "motd" ) ) {
CL_MotdPacket( from );
return;
}
// echo request from server
if ( !Q_stricmp( c, "print" ) ) {
s = MSG_ReadString( msg );
Q_strncpyz( clc.serverMessage, s, sizeof( clc.serverMessage ) );
Com_Printf( "%s", s );
return;
}
// DHM - Nerve :: Auto-update server response message
if ( !Q_stricmp( c, "updateResponse" ) ) {
CL_UpdateInfoPacket( from );
return;
}
// list of servers sent back by a master server (classic)
if ( !Q_strncmp( c, "getserversResponse", 18 ) ) {
CL_ServersResponsePacket( &from, msg, qfalse );
return;
}
// list of servers sent back by a master server (extended)
if ( !Q_strncmp(c, "getserversExtResponse", 21) ) {
CL_ServersResponsePacket( &from, msg, qtrue );
return;
}
Com_DPrintf( "Unknown connectionless packet command.\n" );
}
/*
=================
CL_PacketEvent
A packet has arrived from the main event loop
=================
*/
void CL_PacketEvent( netadr_t from, msg_t *msg ) {
int headerBytes;
clc.lastPacketTime = cls.realtime;
if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) {
CL_ConnectionlessPacket( from, msg );
return;
}
if ( clc.state < CA_CONNECTED ) {
return; // can't be a valid sequenced packet
}
if ( msg->cursize < 4 ) {
Com_Printf ("%s: Runt packet\n", NET_AdrToStringwPort( from ));
return;
}
//
// packet from server
//
if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
Com_DPrintf( "%s:sequenced packet without connection\n"
, NET_AdrToStringwPort( from ) );
// FIXME: send a client disconnect?
return;
}
if ( !CL_Netchan_Process( &clc.netchan, msg ) ) {
return; // out of order, duplicated, etc
}
// the header is different lengths for reliable and unreliable messages
headerBytes = msg->readcount;
// track the last message received so it can be returned in
// client messages, allowing the server to detect a dropped
// gamestate
clc.serverMessageSequence = LittleLong( *(int *)msg->data );
clc.lastPacketTime = cls.realtime;
CL_ParseServerMessage( msg );
//
// we don't know if it is ok to save a demo message until
// after we have parsed the frame
//
if ( clc.demorecording && !clc.demowaiting ) {
CL_WriteDemoMessage( msg, headerBytes );
}
}
/*
==================
CL_CheckTimeout
==================
*/
void CL_CheckTimeout( void ) {
//
// check timeout
//
if ( ( !CL_CheckPaused() || !sv_paused->integer )
&& clc.state >= CA_CONNECTED && clc.state != CA_CINEMATIC
&& cls.realtime - clc.lastPacketTime > cl_timeout->value * 1000 ) {
if ( ++cl.timeoutcount > 5 ) { // timeoutcount saves debugger
Com_Printf( "\nServer connection timed out.\n" );
CL_Disconnect( qtrue );
return;
}
} else {
cl.timeoutcount = 0;
}
}
/*
==================
CL_CheckPaused
Check whether client has been paused.
==================
*/
qboolean CL_CheckPaused(void)
{
// if cl_paused->modified is set, the cvar has only been changed in
// this frame. Keep paused in this frame to ensure the server doesn't
// lag behind.
if(cl_paused->integer || cl_paused->modified)
return qtrue;
return qfalse;
}
//============================================================================
/*
==================
CL_CheckUserinfo
==================
*/
void CL_CheckUserinfo( void ) {
// don't add reliable commands when not yet connected
if(clc.state < CA_CONNECTED)
return;
// don't overflow the reliable command buffer when paused
if(CL_CheckPaused())
return;
// send a reliable userinfo update if needed
if ( cvar_modifiedFlags & CVAR_USERINFO ) {
cvar_modifiedFlags &= ~CVAR_USERINFO;
CL_AddReliableCommand(va("userinfo \"%s\"", Cvar_InfoString( CVAR_USERINFO ) ), qfalse);
}
}
/*
==================
CL_Frame
==================
*/
void CL_Frame( int msec ) {
if ( !com_cl_running->integer ) {
return;
}
#ifdef USE_CURL
if(clc.downloadCURLM) {
CL_cURL_PerformDownload();
// we can't process frames normally when in disconnected
// download mode since the ui vm expects clc.state to be
// CA_CONNECTED
if(clc.cURLDisconnected) {
cls.realFrametime = msec;
cls.frametime = msec;
cls.realtime += cls.frametime;
SCR_UpdateScreen();
S_Update();
Con_RunConsole();
cls.framecount++;
return;
}
}
#endif
if ( cls.cddialog ) {
// bring up the cd error dialog if needed
cls.cddialog = qfalse;
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NEED_CD );
} else if ( clc.state == CA_DISCONNECTED && !( Key_GetCatcher( ) & KEYCATCH_UI )
&& !com_sv_running->integer && uivm ) {
// if disconnected, bring up the menu
S_StopAllSounds();
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_MAIN );
}
// if recording an avi, lock to a fixed fps
if ( ( CL_VideoRecording( ) && cl_aviFrameRate->integer && msec ) || ( cl_avidemo->integer && msec ) ) {
// save the current screen
if ( clc.state == CA_ACTIVE || cl_forceavidemo->integer ) {
if ( cl_avidemo->integer ) { // Legacy (screenshot) method
Cbuf_ExecuteText( EXEC_NOW, "screenshot silent\n" );
// fixed time for next frame
msec = ( 1000 / cl_avidemo->integer ) * com_timescale->value;
if ( msec == 0 ) {
msec = 1;
}
} else { // ioquake3 method
float fps = MIN(cl_aviFrameRate->value * com_timescale->value, 1000.0f);
float frameDuration = MAX(1000.0f / fps, 1.0f) + clc.aviVideoFrameRemainder;
CL_TakeVideoFrame( );
msec = (int)frameDuration;
clc.aviVideoFrameRemainder = frameDuration - msec;
}
}
}
if( cl_autoRecordDemo->integer ) {
if( clc.state == CA_ACTIVE && !clc.demorecording && !clc.demoplaying ) {
// If not recording a demo, and we should be, start one
qtime_t now;
char *nowString;
char *p;
char mapName[ MAX_QPATH ];
char serverName[ MAX_OSPATH ];
Com_RealTime( &now );
nowString = va( "%04d%02d%02d%02d%02d%02d",
1900 + now.tm_year,
1 + now.tm_mon,
now.tm_mday,
now.tm_hour,
now.tm_min,
now.tm_sec );
Q_strncpyz( serverName, clc.servername, MAX_OSPATH );
// Replace the ":" in the address as it is not a valid
// file name character
p = strstr( serverName, ":" );
if( p ) {
*p = '.';
}
Q_strncpyz( mapName, COM_SkipPath( cl.mapname ), sizeof( cl.mapname ) );
COM_StripExtension(mapName, mapName, sizeof(mapName));
Cbuf_ExecuteText( EXEC_NOW,
va( "record %s-%s-%s", nowString, serverName, mapName ) );
}
else if( clc.state != CA_ACTIVE && clc.demorecording ) {
// Recording, but not CA_ACTIVE, so stop recording
CL_StopRecord_f( );
}
}
// save the msec before checking pause
cls.realFrametime = msec;
// decide the simulation time
cls.frametime = msec;
cls.realtime += cls.frametime;
if ( cl_timegraph->integer ) {
SCR_DebugGraph ( cls.realFrametime * 0.25 );
}
// see if we need to update any userinfo
CL_CheckUserinfo();
// if we haven't gotten a packet in a long time,
// drop the connection
CL_CheckTimeout();
// send intentions now
CL_SendCmd();
// resend a connection request if necessary
CL_CheckForResend();
// decide on the serverTime to render
CL_SetCGameTime();
// update the screen
SCR_UpdateScreen();
// update audio
S_Update();
#ifdef USE_VOIP
CL_CaptureVoip();
#endif
#ifdef USE_MUMBLE
CL_UpdateMumble();
#endif
// advance local effects for next frame
SCR_RunCinematic();
Con_RunConsole();
cls.framecount++;
}
//============================================================================
// Ridah, startup-caching system
typedef struct {
char name[MAX_QPATH];
int hits;
int lastSetIndex;
} cacheItem_t;
typedef enum {
CACHE_SOUNDS,
CACHE_MODELS,
CACHE_IMAGES,
CACHE_NUMGROUPS
} cacheGroup_t;
static cacheItem_t cacheGroups[CACHE_NUMGROUPS] = {
{{'s','o','u','n','d',0}, CACHE_SOUNDS},
{{'m','o','d','e','l',0}, CACHE_MODELS},
{{'i','m','a','g','e',0}, CACHE_IMAGES},
};
#define MAX_CACHE_ITEMS 4096
#define CACHE_HIT_RATIO 0.75 // if hit on this percentage of maps, it'll get cached
static int cacheIndex;
static cacheItem_t cacheItems[CACHE_NUMGROUPS][MAX_CACHE_ITEMS];
static void CL_Cache_StartGather_f( void ) {
cacheIndex = 0;
memset( cacheItems, 0, sizeof( cacheItems ) );
Cvar_Set( "cl_cacheGathering", "1" );
}
static void CL_Cache_UsedFile_f( void ) {
char groupStr[MAX_QPATH];
char itemStr[MAX_QPATH];
int i,group;
cacheItem_t *item;
if ( Cmd_Argc() < 2 ) {
Com_Error( ERR_DROP, "usedfile without enough parameters\n" );
return;
}
strcpy( groupStr, Cmd_Argv( 1 ) );
strcpy( itemStr, Cmd_Argv( 2 ) );
for ( i = 3; i < Cmd_Argc(); i++ ) {
strcat( itemStr, " " );
strcat( itemStr, Cmd_Argv( i ) );
}
Q_strlwr( itemStr );
// find the cache group
for ( i = 0; i < CACHE_NUMGROUPS; i++ ) {
if ( !Q_strncmp( groupStr, cacheGroups[i].name, MAX_QPATH ) ) {
break;
}
}
if ( i == CACHE_NUMGROUPS ) {
Com_Error( ERR_DROP, "usedfile without a valid cache group\n" );
return;
}
// see if it's already there
group = i;
for ( i = 0, item = cacheItems[group]; i < MAX_CACHE_ITEMS; i++, item++ ) {
if ( !item->name[0] ) {
// didn't find it, so add it here
Q_strncpyz( item->name, itemStr, MAX_QPATH );
if ( cacheIndex > 9999 ) { // hack, but yeh
item->hits = cacheIndex;
} else {
item->hits++;
}
item->lastSetIndex = cacheIndex;
break;
}
if ( item->name[0] == itemStr[0] && !Q_strncmp( item->name, itemStr, MAX_QPATH ) ) {
if ( item->lastSetIndex != cacheIndex ) {
item->hits++;
item->lastSetIndex = cacheIndex;
}
break;
}
}
}
static void CL_Cache_SetIndex_f( void ) {
if ( Cmd_Argc() < 2 ) {
Com_Error( ERR_DROP, "setindex needs an index\n" );
return;
}
cacheIndex = atoi( Cmd_Argv( 1 ) );
}
static void CL_Cache_MapChange_f( void ) {
cacheIndex++;
}
static void CL_Cache_EndGather_f( void ) {
// save the frequently used files to the cache list file
int i, j, handle, cachePass;
char filename[MAX_QPATH];
cachePass = (int)floor( (float)cacheIndex * CACHE_HIT_RATIO );
for ( i = 0; i < CACHE_NUMGROUPS; i++ ) {
Q_strncpyz( filename, cacheGroups[i].name, MAX_QPATH );
Q_strcat( filename, MAX_QPATH, ".cache" );
handle = FS_FOpenFileWrite( filename );
for ( j = 0; j < MAX_CACHE_ITEMS; j++ ) {
// if it's a valid filename, and it's been hit enough times, cache it
if ( cacheItems[i][j].hits >= cachePass && strstr( cacheItems[i][j].name, "/" ) ) {
FS_Write( cacheItems[i][j].name, strlen( cacheItems[i][j].name ), handle );
FS_Write( "\n", 1, handle );
}
}
FS_FCloseFile( handle );
}
Cvar_Set( "cl_cacheGathering", "0" );
}
// done.
//============================================================================
/*
================
CL_SetRecommended_f
================
*/
void CL_SetRecommended_f( void ) {
Com_SetRecommended();
}
/*
================
CL_RefPrintf
DLL glue
================
*/
static __attribute__ ((format (printf, 2, 3))) void QDECL CL_RefPrintf( int print_level, const char *fmt, ...) {
va_list argptr;
char msg[MAXPRINTMSG];
va_start( argptr,fmt );
Q_vsnprintf( msg, sizeof ( msg ), fmt, argptr );
va_end( argptr );
if ( print_level == PRINT_ALL ) {
Com_Printf( "%s", msg );
} else if ( print_level == PRINT_WARNING ) {
Com_Printf( S_COLOR_YELLOW "%s", msg ); // yellow
} else if ( print_level == PRINT_DEVELOPER ) {
Com_DPrintf( S_COLOR_RED "%s", msg ); // red
}
}
/*
============
CL_ShutdownRef
============
*/
void CL_ShutdownRef( void ) {
if ( re.Shutdown ) {
re.Shutdown( qtrue );
}
memset( &re, 0, sizeof( re ) );
#ifdef USE_RENDERER_DLOPEN
if ( rendererLib ) {
Sys_UnloadLibrary( rendererLib );
rendererLib = NULL;
}
#endif
}
/*
============
CL_InitRenderer
============
*/
void CL_InitRenderer( void ) {
// this sets up the renderer and calls R_Init
re.BeginRegistration( &cls.glconfig );
// load character sets
cls.charSetShader = re.RegisterShader( "gfx/2d/hudchars" );
cls.whiteShader = re.RegisterShader( "white" );
cls.consoleShader = re.RegisterShader( "console-16bit" ); // JPW NERVE shader works with 16bit
cls.consoleShader2 = re.RegisterShader( "console2-16bit" ); // JPW NERVE same
g_console_field_width = cls.glconfig.vidWidth / SMALLCHAR_WIDTH - 2;
g_consoleField.widthInChars = g_console_field_width;
}
/*
============================
CL_StartHunkUsers
After the server has cleared the hunk, these will need to be restarted
This is the only place that any of these functions are called from
============================
*/
void CL_StartHunkUsers( qboolean rendererOnly ) {
if ( !com_cl_running ) {
return;
}
if ( !com_cl_running->integer ) {
return;
}
if ( !cls.rendererStarted ) {
cls.rendererStarted = qtrue;
CL_InitRenderer();
}
if ( rendererOnly ) {
return;
}
if ( !cls.soundStarted ) {
cls.soundStarted = qtrue;
S_Init();
}
if ( !cls.soundRegistered ) {
cls.soundRegistered = qtrue;
S_BeginRegistration();
}
if( com_dedicated->integer ) {
return;
}
if ( !cls.uiStarted ) {
cls.uiStarted = qtrue;
CL_InitUI();
}
}
int CL_ScaledMilliseconds( void ) {
return Sys_Milliseconds() * com_timescale->value;
}
// DHM - Nerve
void CL_CheckAutoUpdate( void ) {
int validServerNum = 0;
int i = 0, rnd = 0;
netadr_t temp;
char *servername;
if ( !cl_autoupdate->integer ) {
return;
}
// Only check once per session
if ( autoupdateChecked ) {
return;
}
srand( Com_Milliseconds() );
// Find out how many update servers have valid DNS listings
for ( i = 0; i < MAX_AUTOUPDATE_SERVERS; i++ ) {
if ( NET_StringToAdr( cls.autoupdateServerNames[i], &temp, NA_UNSPEC ) ) {
validServerNum++;
}
}
// Pick a random server
if ( validServerNum > 1 ) {
rnd = rand() % validServerNum;
} else {
rnd = 0;
}
servername = cls.autoupdateServerNames[rnd];
Com_DPrintf( "Resolving AutoUpdate Server... " );
if ( !NET_StringToAdr( servername, &cls.autoupdateServer, NA_UNSPEC ) ) {
Com_DPrintf( "Couldn't resolve first address, trying default..." );
// Fall back to the first one
if ( !NET_StringToAdr( cls.autoupdateServerNames[0], &cls.autoupdateServer, NA_UNSPEC ) ) {
Com_DPrintf( "Failed to resolve any Auto-update servers.\n" );
autoupdateChecked = qtrue;
return;
}
}
cls.autoupdateServer.port = BigShort( PORT_SERVER );
Com_DPrintf( "%i.%i.%i.%i:%i\n", cls.autoupdateServer.ip[0], cls.autoupdateServer.ip[1],
cls.autoupdateServer.ip[2], cls.autoupdateServer.ip[3],
BigShort( cls.autoupdateServer.port ) );
NET_OutOfBandPrint( NS_CLIENT, cls.autoupdateServer, "getUpdateInfo \"%s\" \"%s\"-\"%s\"\n", Q3_VERSION, OS_STRING, ARCH_STRING );
CL_RequestMotd();
autoupdateChecked = qtrue;
}
void CL_GetAutoUpdate( void ) {
// Don't try and get an update if we haven't checked for one
if ( !autoupdateChecked ) {
return;
}
// Make sure there's a valid update file to request
if ( strlen( cl_updatefiles->string ) < 5 ) {
return;
}
Com_DPrintf( "Connecting to auto-update server...\n" );
S_StopAllSounds(); // NERVE - SMF
// starting to load a map so we get out of full screen ui mode
Cvar_Set( "r_uiFullScreen", "0" );
// clear any previous "server full" type messages
clc.serverMessage[0] = 0;
if ( com_sv_running->integer ) {
// if running a local server, kill it
SV_Shutdown( "Server quit\n" );
}
// make sure a local server is killed
Cvar_Set( "sv_killserver", "1" );
SV_Frame( 0 );
CL_Disconnect( qtrue );
Con_Close();
Q_strncpyz( clc.servername, "Auto-Updater", sizeof( clc.servername ) );
if ( cls.autoupdateServer.type == NA_BAD ) {
Com_Printf( "Bad server address\n" );
clc.state = CA_DISCONNECTED;
return;
}
// Copy auto-update server address to Server connect address
memcpy( &clc.serverAddress, &cls.autoupdateServer, sizeof( netadr_t ) );
Com_DPrintf( "%s resolved to %i.%i.%i.%i:%i\n", clc.servername,
clc.serverAddress.ip[0], clc.serverAddress.ip[1],
clc.serverAddress.ip[2], clc.serverAddress.ip[3],
BigShort( clc.serverAddress.port ) );
clc.state = CA_CONNECTING;
Key_SetCatcher( 0 );
clc.connectTime = -99999; // CL_CheckForResend() will fire immediately
clc.connectPacketCount = 0;
// server connection string
Cvar_Set( "cl_currentServerAddress", "Auto-Updater" );
}
// DHM - Nerve
/*
============
CL_RefMalloc
============
*/
#ifdef ZONE_DEBUG
void *CL_RefMallocDebug( int size, char *label, char *file, int line ) {
return Z_TagMallocDebug( size, TAG_RENDERER, label, file, line );
}
#else
void *CL_RefMalloc( int size ) {
return Z_TagMalloc( size, TAG_RENDERER );
}
#endif
/*
============
CL_RefTagFree
============
*/
void CL_RefTagFree( void ) {
Z_FreeTags( TAG_RENDERER );
return;
}
/*
============
CL_InitRef
============
*/
void CL_InitRef( void ) {
refimport_t ri;
refexport_t *ret;
#ifdef USE_RENDERER_DLOPEN
GetRefAPI_t GetRefAPI;
char dllName[MAX_OSPATH];
#endif
Com_Printf( "----- Initializing Renderer ----\n" );
#ifdef USE_RENDERER_DLOPEN
cl_renderer = Cvar_Get("cl_renderer", "opengl1", CVAR_ARCHIVE | CVAR_LATCH);
Com_sprintf(dllName, sizeof(dllName), "renderer_mp_%s_" ARCH_STRING DLL_EXT, cl_renderer->string);
if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString))
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Cvar_ForceReset("cl_renderer");
Com_sprintf(dllName, sizeof(dllName), "renderer_mp_opengl1_" ARCH_STRING DLL_EXT);
rendererLib = Sys_LoadDll(dllName, qfalse);
}
if(!rendererLib)
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Com_Error(ERR_FATAL, "Failed to load renderer");
}
GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI");
if(!GetRefAPI)
{
Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError());
}
#endif
ri.Cmd_AddCommand = Cmd_AddCommand;
ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
ri.Cmd_Argc = Cmd_Argc;
ri.Cmd_Argv = Cmd_Argv;
ri.Cmd_ExecuteText = Cbuf_ExecuteText;
ri.Printf = CL_RefPrintf;
ri.Error = Com_Error;
ri.Milliseconds = CL_ScaledMilliseconds;
#ifdef ZONE_DEBUG
ri.Z_MallocDebug = CL_RefMallocDebug;
#else
ri.Z_Malloc = CL_RefMalloc;
#endif
ri.Free = Z_Free;
ri.Tag_Free = CL_RefTagFree;
ri.Hunk_Clear = Hunk_ClearToMark;
#ifdef HUNK_DEBUG
ri.Hunk_AllocDebug = Hunk_AllocDebug;
#else
ri.Hunk_Alloc = Hunk_Alloc;
#endif
ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
ri.CM_ClusterPVS = CM_ClusterPVS;
ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
ri.FS_ReadFile = FS_ReadFile;
ri.FS_FreeFile = FS_FreeFile;
ri.FS_WriteFile = FS_WriteFile;
ri.FS_FreeFileList = FS_FreeFileList;
ri.FS_ListFiles = FS_ListFiles;
ri.FS_FileIsInPAK = FS_FileIsInPAK;
ri.FS_FileExists = FS_FileExists;
ri.Cvar_Get = Cvar_Get;
ri.Cvar_Set = Cvar_Set;
ri.Cvar_SetValue = Cvar_SetValue;
ri.Cvar_CheckRange = Cvar_CheckRange;
ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
// cinematic stuff
ri.CIN_UploadCinematic = CIN_UploadCinematic;
ri.CIN_PlayCinematic = CIN_PlayCinematic;
ri.CIN_RunCinematic = CIN_RunCinematic;
ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;
ri.IN_Init = IN_Init;
ri.IN_Shutdown = IN_Shutdown;
ri.IN_Restart = IN_Restart;
ri.ftol = Q_ftol;
ri.Sys_SetEnv = Sys_SetEnv;
ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit;
ri.Sys_GLimpInit = Sys_GLimpInit;
ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;
ret = GetRefAPI( REF_API_VERSION, &ri );
if ( !ret ) {
Com_Error( ERR_FATAL, "Couldn't initialize refresh" );
}
re = *ret;
Com_Printf( "---- Renderer Initialization Complete ----\n" );
// unpause so the cgame definately gets a snapshot and renders a frame
Cvar_Set( "cl_paused", "0" );
}
// RF, trap manual client damage commands so users can't issue them manually
void CL_ClientDamageCommand( void ) {
// do nothing
}
#if defined (__i386__)
#define BIN_STRING "x86"
#endif
// NERVE - SMF
void CL_startSingleplayer_f( void ) {
char binName[MAX_OSPATH];
#if defined(_WIN64) || defined(__WIN64__)
Com_sprintf(binName, sizeof(binName), "ioWolfSP." ARCH_STRING ".exe");
Sys_StartProcess( binName, qtrue );
#elif defined(_WIN32) || defined(__WIN32__)
Com_sprintf(binName, sizeof(binName), "ioWolfSP." BIN_STRING ".exe");
Sys_StartProcess( binName, qtrue );
#elif defined(__i386__) && (!defined(_WIN32) || !defined(__WIN32__))
Com_sprintf(binName, sizeof(binName), "./iowolfsp." BIN_STRING );
Sys_StartProcess( binName, qtrue );
#else
Com_sprintf(binName, sizeof(binName), "./iowolfsp." ARCH_STRING );
Sys_StartProcess( binName, qtrue );
#endif
}
void CL_SaveTranslations_f( void ) {
CL_SaveTransTable( "scripts/translation.cfg", qfalse );
}
void CL_SaveNewTranslations_f( void ) {
char fileName[512];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: SaveNewTranslations <filename>\n" );
return;
}
strcpy( fileName, va( "translations/%s.cfg", Cmd_Argv( 1 ) ) );
CL_SaveTransTable( fileName, qtrue );
}
void CL_LoadTranslations_f( void ) {
CL_ReloadTranslation();
}
// -NERVE - SMF
//===========================================================================================
/*
===============
CL_Video_f
video
video [filename]
===============
*/
void CL_Video_f( void )
{
char filename[ MAX_OSPATH ];
int i, last;
if( !clc.demoplaying )
{
Com_Printf( "The video command can only be used when playing back demos\n" );
return;
}
if( Cmd_Argc( ) == 2 )
{
// explicit filename
Com_sprintf( filename, MAX_OSPATH, "videos/%s.avi", Cmd_Argv( 1 ) );
}
else
{
// scan for a free filename
for( i = 0; i <= 9999; i++ )
{
int a, b, c, d;
last = i;
a = last / 1000;
last -= a * 1000;
b = last / 100;
last -= b * 100;
c = last / 10;
last -= c * 10;
d = last;
Com_sprintf( filename, MAX_OSPATH, "videos/video%d%d%d%d.avi", a, b, c, d );
if( !FS_FileExists( filename ) )
break; // file doesn't exist
}
if( i > 9999 )
{
Com_Printf( S_COLOR_RED "ERROR: no free file names to create video\n" );
return;
}
}
CL_OpenAVIForWriting( filename );
}
/*
===============
CL_StopVideo_f
===============
*/
void CL_StopVideo_f( void )
{
CL_CloseAVI( );
}
/*
===============
CL_GenerateQKey
test to see if a valid QKEY_FILE exists. If one does not, try to generate
it by filling it with 2048 bytes of random data.
===============
*/
static void CL_GenerateQKey(void)
{
int len = 0;
unsigned char buff[ QKEY_SIZE ];
fileHandle_t f;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
if( len == QKEY_SIZE ) {
Com_Printf( "RTCWKEY found.\n" );
return;
}
else {
if( len > 0 ) {
Com_Printf( "RTCWKEY file size != %d, regenerating\n",
QKEY_SIZE );
}
Com_Printf( "RTCWKEY building random string\n" );
Com_RandomBytes( buff, sizeof(buff) );
f = FS_SV_FOpenFileWrite( QKEY_FILE );
if( !f ) {
Com_Printf( "RTCWKEY could not open %s for write\n",
QKEY_FILE );
return;
}
FS_Write( buff, sizeof(buff), f );
FS_FCloseFile( f );
Com_Printf( "RTCWKEY generated\n" );
}
}
/*
====================
CL_Init
====================
*/
void CL_Init( void ) {
Com_Printf( "----- Client Initialization -----\n" );
Con_Init();
if(!com_fullyInitialized)
{
CL_ClearState();
clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
cl_oldGameSet = qfalse;
}
cls.realtime = 0;
CL_InitInput();
//
// register our variables
//
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
#ifdef UPDATE_SERVER_NAME
cl_motd = Cvar_Get( "cl_motd", "1", 0 );
#endif
cl_autoupdate = Cvar_Get( "cl_autoupdate", "0", CVAR_ARCHIVE );
cl_timeout = Cvar_Get( "cl_timeout", "200", 0 );
cl_wavefilerecord = Cvar_Get( "cl_wavefilerecord", "0", CVAR_TEMP );
cl_timeNudge = Cvar_Get( "cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get( "cl_shownet", "0", CVAR_TEMP );
cl_shownuments = Cvar_Get( "cl_shownuments", "0", CVAR_TEMP );
cl_visibleClients = Cvar_Get( "cl_visibleClients", "0", CVAR_TEMP );
cl_showServerCommands = Cvar_Get( "cl_showServerCommands", "0", 0 );
cl_showSend = Cvar_Get( "cl_showSend", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get( "cl_showTimeDelta", "0", CVAR_TEMP );
cl_freezeDemo = Cvar_Get( "cl_freezeDemo", "0", CVAR_TEMP );
rcon_client_password = Cvar_Get( "rconPassword", "", CVAR_TEMP );
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_timedemo = Cvar_Get( "timedemo", "0", 0 );
cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE);
cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE);
cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE);
cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE);
cl_avidemo = Cvar_Get( "cl_avidemo", "0", 0 );
cl_forceavidemo = Cvar_Get( "cl_forceavidemo", "0", 0 );
rconAddress = Cvar_Get( "rconAddress", "", 0 );
cl_yawspeed = Cvar_Get( "cl_yawspeed", "140", CVAR_ARCHIVE );
cl_pitchspeed = Cvar_Get( "cl_pitchspeed", "140", CVAR_ARCHIVE );
cl_anglespeedkey = Cvar_Get( "cl_anglespeedkey", "1.5", 0 );
cl_maxpackets = Cvar_Get( "cl_maxpackets", "38", CVAR_ARCHIVE );
cl_packetdup = Cvar_Get( "cl_packetdup", "1", CVAR_ARCHIVE );
cl_showPing = Cvar_Get( "cl_showPing", "0", CVAR_ARCHIVE );
cl_run = Cvar_Get( "cl_run", "1", CVAR_ARCHIVE );
cl_sensitivity = Cvar_Get( "sensitivity", "5", CVAR_ARCHIVE );
cl_mouseAccel = Cvar_Get( "cl_mouseAccel", "0", CVAR_ARCHIVE );
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE );
// 0: legacy mouse acceleration
// 1: new implementation
cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE );
// offset for the power function (for style 1, ignored otherwise)
// this should be set to the max rate value
cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE );
Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse);
cl_showMouseRate = Cvar_Get( "cl_showmouserate", "0", 0 );
cl_allowDownload = Cvar_Get( "cl_allowDownload", "1", CVAR_ARCHIVE );
#ifdef USE_CURL_DLOPEN
cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE);
#endif
// init autoswitch so the ui will have it correctly even
// if the cgame hasn't been started
// -NERVE - SMF - disabled autoswitch by default
Cvar_Get( "cg_autoswitch", "0", CVAR_ARCHIVE );
// Rafael - particle switch
Cvar_Get( "cg_wolfparticles", "1", CVAR_ARCHIVE );
// done
cl_conXOffset = Cvar_Get( "cl_conXOffset", "0", 0 );
cl_inGameVideo = Cvar_Get( "r_inGameVideo", "1", CVAR_ARCHIVE );
cl_serverStatusResendTime = Cvar_Get( "cl_serverStatusResendTime", "750", 0 );
// RF
cl_recoilPitch = Cvar_Get( "cg_recoilPitch", "0", CVAR_ROM );
cl_bypassMouseInput = Cvar_Get( "cl_bypassMouseInput", "0", 0 ); //CVAR_ROM ); // NERVE - SMF
m_pitch = Cvar_Get( "m_pitch", "0.022", CVAR_ARCHIVE );
m_yaw = Cvar_Get( "m_yaw", "0.022", CVAR_ARCHIVE );
m_forward = Cvar_Get( "m_forward", "0.25", CVAR_ARCHIVE );
m_side = Cvar_Get( "m_side", "0.25", CVAR_ARCHIVE );
m_filter = Cvar_Get( "m_filter", "0", CVAR_ARCHIVE );
j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE);
j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE);
j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE);
j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE);
j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE);
j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE);
j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE);
j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE);
j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE);
j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE);
Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM );
Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE );
cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE);
cl_guid = Cvar_Get( "cl_guid", "unknown", CVAR_USERINFO | CVAR_ROM );
cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE);
// ~ and `, as keys and characters
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE);
// NERVE - SMF
Cvar_Get( "cg_drawCompass", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_drawNotifyText", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_quickMessageAlt", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_popupLimboMenu", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_descriptiveText", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_drawTeamOverlay", "2", CVAR_ARCHIVE );
Cvar_Get( "cg_uselessNostalgia", "0", CVAR_ARCHIVE ); // JPW NERVE
Cvar_Get( "cg_drawGun", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_cursorHints", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_voiceSpriteTime", "6000", CVAR_ARCHIVE );
Cvar_Get( "cg_teamChatsOnly", "0", CVAR_ARCHIVE );
Cvar_Get( "cg_noVoiceChats", "0", CVAR_ARCHIVE );
Cvar_Get( "cg_noVoiceText", "0", CVAR_ARCHIVE );
Cvar_Get( "cg_crosshairSize", "48", CVAR_ARCHIVE );
Cvar_Get( "cg_drawCrosshair", "1", CVAR_ARCHIVE );
Cvar_Get( "cg_zoomDefaultSniper", "20", CVAR_ARCHIVE );
Cvar_Get( "cg_zoomstepsniper", "2", CVAR_ARCHIVE );
Cvar_Get( "mp_playerType", "0", 0 );
Cvar_Get( "mp_currentPlayerType", "0", 0 );
Cvar_Get( "mp_weapon", "0", 0 );
Cvar_Get( "mp_team", "0", 0 );
Cvar_Get( "mp_currentTeam", "0", 0 );
// -NERVE - SMF
// userinfo
Cvar_Get( "name", "WolfPlayer", CVAR_USERINFO | CVAR_ARCHIVE );
cl_rate = Cvar_Get( "rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE ); // NERVE - SMF - changed from 3000
Cvar_Get( "snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "model", "multi", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "head", "default", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "color", "4", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "sex", "male", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "password", "", CVAR_USERINFO );
Cvar_Get( "cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE );
#ifdef USE_MUMBLE
cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH);
cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE);
#endif
#ifdef USE_VOIP
cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0);
cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0);
cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE);
cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE);
cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE);
cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE);
cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE);
cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE);
Cvar_CheckRange( cl_voip, 0, 1, qtrue );
cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM);
#endif
//----(SA) added
Cvar_Get( "cg_autoactivate", "1", CVAR_USERINFO | CVAR_ARCHIVE );
//----(SA) end
// cgame might not be initialized before menu is used
Cvar_Get( "cg_viewsize", "100", CVAR_ARCHIVE );
// Make sure cg_stereoSeparation is zero as that variable is deprecated and should not be used anymore.
Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM);
Cvar_Get( "cg_autoReload", "1", CVAR_ARCHIVE | CVAR_USERINFO );
cl_missionStats = Cvar_Get( "g_missionStats", "0", CVAR_ROM );
cl_waitForFire = Cvar_Get( "cl_waitForFire", "0", CVAR_ROM );
// NERVE - SMF - localization
cl_language = Cvar_Get( "cl_language", "0", CVAR_ARCHIVE );
cl_debugTranslation = Cvar_Get( "cl_debugTranslation", "0", 0 );
// -NERVE - SMF
// DHM - Nerve :: Auto-update
cl_updateavailable = Cvar_Get( "cl_updateavailable", "0", CVAR_ROM );
cl_updatefiles = Cvar_Get( "cl_updatefiles", "", CVAR_ROM );
Q_strncpyz( cls.autoupdateServerNames[0], AUTOUPDATE_SERVER1_NAME, MAX_QPATH );
Q_strncpyz( cls.autoupdateServerNames[1], AUTOUPDATE_SERVER2_NAME, MAX_QPATH );
Q_strncpyz( cls.autoupdateServerNames[2], AUTOUPDATE_SERVER3_NAME, MAX_QPATH );
Q_strncpyz( cls.autoupdateServerNames[3], AUTOUPDATE_SERVER4_NAME, MAX_QPATH );
Q_strncpyz( cls.autoupdateServerNames[4], AUTOUPDATE_SERVER5_NAME, MAX_QPATH );
// DHM - Nerve
//
// register our commands
//
Cmd_AddCommand( "cmd", CL_ForwardToServer_f );
Cmd_AddCommand( "configstrings", CL_Configstrings_f );
Cmd_AddCommand( "clientinfo", CL_Clientinfo_f );
Cmd_AddCommand( "snd_restart", CL_Snd_Restart_f );
Cmd_AddCommand( "vid_restart", CL_Vid_Restart_f );
Cmd_AddCommand( "ui_restart", CL_UI_Restart_f ); // NERVE - SMF
Cmd_AddCommand( "disconnect", CL_Disconnect_f );
Cmd_AddCommand( "record", CL_Record_f );
Cmd_AddCommand( "demo", CL_PlayDemo_f );
Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName );
Cmd_AddCommand( "cinematic", CL_PlayCinematic_f );
Cmd_AddCommand( "stoprecord", CL_StopRecord_f );
Cmd_AddCommand( "connect", CL_Connect_f );
Cmd_AddCommand( "reconnect", CL_Reconnect_f );
Cmd_AddCommand( "localservers", CL_LocalServers_f );
Cmd_AddCommand( "globalservers", CL_GlobalServers_f );
Cmd_AddCommand( "rcon", CL_Rcon_f );
Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon );
Cmd_AddCommand( "ping", CL_Ping_f );
Cmd_AddCommand( "serverstatus", CL_ServerStatus_f );
Cmd_AddCommand( "showip", CL_ShowIP_f );
Cmd_AddCommand( "fs_openedList", CL_OpenedPK3List_f );
Cmd_AddCommand( "fs_referencedList", CL_ReferencedPK3List_f );
Cmd_AddCommand ("video", CL_Video_f );
Cmd_AddCommand ("stopvideo", CL_StopVideo_f );
// Ridah, startup-caching system
Cmd_AddCommand( "cache_startgather", CL_Cache_StartGather_f );
Cmd_AddCommand( "cache_usedfile", CL_Cache_UsedFile_f );
Cmd_AddCommand( "cache_setindex", CL_Cache_SetIndex_f );
Cmd_AddCommand( "cache_mapchange", CL_Cache_MapChange_f );
Cmd_AddCommand( "cache_endgather", CL_Cache_EndGather_f );
Cmd_AddCommand( "updatehunkusage", CL_UpdateLevelHunkUsage );
Cmd_AddCommand( "updatescreen", SCR_UpdateScreen );
// done.
Cmd_AddCommand( "SaveTranslations", CL_SaveTranslations_f ); // NERVE - SMF - localization
Cmd_AddCommand( "SaveNewTranslations", CL_SaveNewTranslations_f ); // NERVE - SMF - localization
Cmd_AddCommand( "LoadTranslations", CL_LoadTranslations_f ); // NERVE - SMF - localization
// NERVE - SMF - don't do this in multiplayer
// RF, add this command so clients can't bind a key to send client damage commands to the server
// Cmd_AddCommand( "cld", CL_ClientDamageCommand );
Cmd_AddCommand( "startSingleplayer", CL_startSingleplayer_f ); // NERVE - SMF
Cmd_AddCommand( "setRecommended", CL_SetRecommended_f );
CL_InitRef();
SCR_Init();
// Cbuf_Execute();
Cvar_Set( "cl_running", "1" );
// DHM - Nerve
autoupdateChecked = qfalse;
autoupdateStarted = qfalse;
CL_InitTranslation(); // NERVE - SMF - localization
CL_GenerateQKey();
CL_UpdateGUID( NULL, 0 );
Com_Printf( "----- Client Initialization Complete -----\n" );
}
/*
===============
CL_Shutdown
===============
*/
void CL_Shutdown( char *finalmsg, qboolean disconnect, qboolean quit ) {
static qboolean recursive = qfalse;
// check whether the client is running at all.
if(!(com_cl_running && com_cl_running->integer))
return;
Com_Printf( "----- Client Shutdown (%s) -----\n", finalmsg );
if ( recursive ) {
Com_Printf( "WARNING: Recursive shutdown\n" );
return;
}
recursive = qtrue;
noGameRestart = quit;
if(disconnect)
CL_Disconnect(qtrue);
CL_ClearMemory(qtrue);
CL_Snd_Shutdown();
Cmd_RemoveCommand( "cmd" );
Cmd_RemoveCommand( "configstrings" );
Cmd_RemoveCommand ("clientinfo");
Cmd_RemoveCommand( "snd_restart" );
Cmd_RemoveCommand( "vid_restart" );
Cmd_RemoveCommand( "ui_restart" );
Cmd_RemoveCommand( "disconnect" );
Cmd_RemoveCommand( "record" );
Cmd_RemoveCommand( "demo" );
Cmd_RemoveCommand( "cinematic" );
Cmd_RemoveCommand( "stoprecord" );
Cmd_RemoveCommand( "connect" );
Cmd_RemoveCommand ("reconnect");
Cmd_RemoveCommand( "localservers" );
Cmd_RemoveCommand( "globalservers" );
Cmd_RemoveCommand( "rcon" );
Cmd_RemoveCommand( "ping" );
Cmd_RemoveCommand( "serverstatus" );
Cmd_RemoveCommand( "showip" );
Cmd_RemoveCommand ("fs_openedList");
Cmd_RemoveCommand ("fs_referencedList");
Cmd_RemoveCommand( "model" );
Cmd_RemoveCommand ("video");
Cmd_RemoveCommand ("stopvideo");
// Ridah, startup-caching system
Cmd_RemoveCommand( "cache_startgather" );
Cmd_RemoveCommand( "cache_usedfile" );
Cmd_RemoveCommand( "cache_setindex" );
Cmd_RemoveCommand( "cache_mapchange" );
Cmd_RemoveCommand( "cache_endgather" );
Cmd_RemoveCommand( "updatehunkusage" );
// done.
Cmd_RemoveCommand( "updatescreen" );
Cmd_RemoveCommand( "SaveTranslations" ); // NERVE - SMF - localization
Cmd_RemoveCommand( "SaveNewTranslations" ); // NERVE - SMF - localization
Cmd_RemoveCommand( "LoadTranslations" ); // NERVE - SMF - localization
Cmd_RemoveCommand( "startSingleplayer" ); // NERVE - SMF
Cmd_RemoveCommand( "setRecommended" );
CL_ShutdownInput();
Con_Shutdown();
Cvar_Set( "cl_running", "0" );
recursive = qfalse;
memset( &cls, 0, sizeof( cls ) );
Key_SetCatcher( 0 );
Com_Printf( "-----------------------\n" );
}
static void CL_SetServerInfo( serverInfo_t *server, const char *info, int ping ) {
if ( server ) {
if ( info ) {
server->clients = atoi( Info_ValueForKey( info, "clients" ) );
Q_strncpyz( server->hostName,Info_ValueForKey( info, "hostname" ), MAX_NAME_LENGTH );
Q_strncpyz( server->mapName, Info_ValueForKey( info, "mapname" ), MAX_NAME_LENGTH );
server->maxClients = atoi( Info_ValueForKey( info, "sv_maxclients" ) );
Q_strncpyz( server->game,Info_ValueForKey( info, "game" ), MAX_NAME_LENGTH );
server->gameType = atoi( Info_ValueForKey( info, "gametype" ) );
server->netType = atoi( Info_ValueForKey( info, "nettype" ) );
server->minPing = atoi( Info_ValueForKey( info, "minping" ) );
server->maxPing = atoi( Info_ValueForKey( info, "maxping" ) );
server->allowAnonymous = atoi( Info_ValueForKey( info, "sv_allowAnonymous" ) );
server->friendlyFire = atoi( Info_ValueForKey( info, "friendlyFire" ) ); // NERVE - SMF
server->maxlives = atoi( Info_ValueForKey( info, "maxlives" ) ); // NERVE - SMF
server->tourney = atoi( Info_ValueForKey( info, "tourney" ) ); // NERVE - SMF
server->punkbuster = atoi( Info_ValueForKey( info, "punkbuster" ) ); // DHM - Nerve
Q_strncpyz( server->gameName, Info_ValueForKey( info, "gamename" ), MAX_NAME_LENGTH ); // Arnout
server->antilag = atoi( Info_ValueForKey( info, "g_antilag" ) );
server->g_humanplayers = atoi( Info_ValueForKey( info, "g_humanplayers" ) );
server->g_needpass = atoi( Info_ValueForKey( info, "g_needpass" ) );
}
server->ping = ping;
}
}
static void CL_SetServerInfoByAddress( netadr_t from, const char *info, int ping ) {
int i;
for ( i = 0; i < MAX_OTHER_SERVERS; i++ ) {
if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) {
CL_SetServerInfo( &cls.localServers[i], info, ping );
}
}
for ( i = 0; i < MAX_GLOBAL_SERVERS; i++ ) {
if ( NET_CompareAdr( from, cls.globalServers[i].adr ) ) {
CL_SetServerInfo( &cls.globalServers[i], info, ping );
}
}
for ( i = 0; i < MAX_OTHER_SERVERS; i++ ) {
if ( NET_CompareAdr( from, cls.favoriteServers[i].adr ) ) {
CL_SetServerInfo( &cls.favoriteServers[i], info, ping );
}
}
}
/*
===================
CL_ServerInfoPacket
===================
*/
void CL_ServerInfoPacket( netadr_t from, msg_t *msg ) {
int i, type;
char info[MAX_INFO_STRING];
char *infoString;
int prot;
char *gamename;
qboolean gameMismatch;
infoString = MSG_ReadString( msg );
// if this isn't the correct gamename, ignore it
gamename = Info_ValueForKey( infoString, "gamename" );
#ifdef LEGACY_PROTOCOL
// gamename is optional for legacy protocol
if (com_legacyprotocol->integer && !*gamename)
gameMismatch = qfalse;
else
#endif
gameMismatch = !*gamename || strcmp(gamename, com_gamename->string) != 0;
if (gameMismatch)
{
Com_DPrintf( "Game mismatch in info packet: %s\n", infoString );
return;
}
// if this isn't the correct protocol version, ignore it
prot = atoi( Info_ValueForKey( infoString, "protocol" ) );
if(prot != com_protocol->integer
#ifdef LEGACY_PROTOCOL
&& prot != com_legacyprotocol->integer
#endif
)
{
Com_DPrintf( "Different protocol info packet: %s\n", infoString );
return;
}
// iterate servers waiting for ping response
for ( i = 0; i < MAX_PINGREQUESTS; i++ )
{
if ( cl_pinglist[i].adr.port && !cl_pinglist[i].time && NET_CompareAdr( from, cl_pinglist[i].adr ) ) {
// calc ping time
cl_pinglist[i].time = Sys_Milliseconds() - cl_pinglist[i].start;
Com_DPrintf( "ping time %dms from %s\n", cl_pinglist[i].time, NET_AdrToString( from ) );
// save of info
Q_strncpyz( cl_pinglist[i].info, infoString, sizeof( cl_pinglist[i].info ) );
// tack on the net type
// NOTE: make sure these types are in sync with the netnames strings in the UI
switch ( from.type )
{
case NA_BROADCAST:
case NA_IP:
type = 1;
break;
case NA_IP6:
type = 2;
break;
default:
type = 0;
break;
}
Info_SetValueForKey( cl_pinglist[i].info, "nettype", va( "%d", type ) );
CL_SetServerInfoByAddress( from, infoString, cl_pinglist[i].time );
return;
}
}
// if not just sent a local broadcast or pinging local servers
if ( cls.pingUpdateSource != AS_LOCAL ) {
return;
}
for ( i = 0 ; i < MAX_OTHER_SERVERS ; i++ ) {
// empty slot
if ( cls.localServers[i].adr.port == 0 ) {
break;
}
// avoid duplicate
if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) {
return;
}
}
if ( i == MAX_OTHER_SERVERS ) {
Com_DPrintf( "MAX_OTHER_SERVERS hit, dropping infoResponse\n" );
return;
}
// add this to the list
cls.numlocalservers = i + 1;
CL_InitServerInfo( &cls.localServers[i], &from );
Q_strncpyz( info, MSG_ReadString( msg ), MAX_INFO_STRING );
if ( strlen( info ) ) {
if ( info[strlen( info ) - 1] != '\n' ) {
Q_strcat( info, sizeof(info), "\n" );
}
Com_Printf( "%s: %s", NET_AdrToStringwPort( from ), info );
}
}
/*
===================
CL_UpdateInfoPacket
===================
*/
void CL_UpdateInfoPacket( netadr_t from ) {
if ( cls.autoupdateServer.type == NA_BAD ) {
Com_DPrintf( "CL_UpdateInfoPacket: Auto-Updater has bad address\n" );
return;
}
Com_DPrintf( "Auto-Updater resolved to %i.%i.%i.%i:%i\n",
cls.autoupdateServer.ip[0], cls.autoupdateServer.ip[1],
cls.autoupdateServer.ip[2], cls.autoupdateServer.ip[3],
BigShort( cls.autoupdateServer.port ) );
if ( !NET_CompareAdr( from, cls.autoupdateServer ) ) {
Com_DPrintf( "CL_UpdateInfoPacket: Received packet from %i.%i.%i.%i:%i\n",
from.ip[0], from.ip[1], from.ip[2], from.ip[3],
BigShort( from.port ) );
return;
}
Cvar_Set( "cl_updateavailable", Cmd_Argv( 1 ) );
if ( !Q_stricmp( cl_updateavailable->string, "1" ) ) {
Cvar_Set( "cl_updatefiles", Cmd_Argv( 2 ) );
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_WM_AUTOUPDATE );
}
}
// DHM - Nerve
/*
===================
CL_GetServerStatus
===================
*/
serverStatus_t *CL_GetServerStatus( netadr_t from ) {
int i, oldest, oldestTime;
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
return &cl_serverStatusList[i];
}
}
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( cl_serverStatusList[i].retrieved ) {
return &cl_serverStatusList[i];
}
}
oldest = -1;
oldestTime = 0;
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( oldest == -1 || cl_serverStatusList[i].startTime < oldestTime ) {
oldest = i;
oldestTime = cl_serverStatusList[i].startTime;
}
}
return &cl_serverStatusList[oldest];
}
/*
===================
CL_ServerStatus
===================
*/
int CL_ServerStatus( char *serverAddress, char *serverStatusString, int maxLen ) {
int i;
netadr_t to;
serverStatus_t *serverStatus;
// if no server address then reset all server status requests
if ( !serverAddress ) {
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
cl_serverStatusList[i].address.port = 0;
cl_serverStatusList[i].retrieved = qtrue;
}
return qfalse;
}
// get the address
if ( !NET_StringToAdr( serverAddress, &to, NA_UNSPEC) ) {
return qfalse;
}
serverStatus = CL_GetServerStatus( to );
// if no server status string then reset the server status request for this address
if ( !serverStatusString ) {
serverStatus->retrieved = qtrue;
return qfalse;
}
// if this server status request has the same address
if ( NET_CompareAdr( to, serverStatus->address ) ) {
// if we received a response for this server status request
if ( !serverStatus->pending ) {
Q_strncpyz( serverStatusString, serverStatus->string, maxLen );
serverStatus->retrieved = qtrue;
serverStatus->startTime = 0;
return qtrue;
}
// resend the request regularly
else if ( serverStatus->startTime < Com_Milliseconds() - cl_serverStatusResendTime->integer ) {
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->time = 0;
serverStatus->startTime = Com_Milliseconds();
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
}
// if retrieved
else if ( serverStatus->retrieved ) {
serverStatus->address = to;
serverStatus->print = qfalse;
serverStatus->pending = qtrue;
serverStatus->retrieved = qfalse;
serverStatus->startTime = Com_Milliseconds();
serverStatus->time = 0;
NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
return qfalse;
}
return qfalse;
}
/*
===================
CL_ServerStatusResponse
===================
*/
void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) {
char *s;
char info[MAX_INFO_STRING];
int i, l, score, ping;
int len;
serverStatus_t *serverStatus;
serverStatus = NULL;
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
serverStatus = &cl_serverStatusList[i];
break;
}
}
// if we didn't request this server status
if ( !serverStatus ) {
return;
}
s = MSG_ReadStringLine( msg );
len = 0;
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "%s", s );
if ( serverStatus->print ) {
Com_Printf( "Server settings:\n" );
// print cvars
while ( *s ) {
for ( i = 0; i < 2 && *s; i++ ) {
if ( *s == '\\' ) {
s++;
}
l = 0;
while ( *s ) {
info[l++] = *s;
if ( l >= MAX_INFO_STRING - 1 ) {
break;
}
s++;
if ( *s == '\\' ) {
break;
}
}
info[l] = '\0';
if ( i ) {
Com_Printf( "%s\n", info );
} else {
Com_Printf( "%-24s", info );
}
}
}
}
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\" );
if ( serverStatus->print ) {
Com_Printf( "\nPlayers:\n" );
Com_Printf( "num: score: ping: name:\n" );
}
for ( i = 0, s = MSG_ReadStringLine( msg ); *s; s = MSG_ReadStringLine( msg ), i++ ) {
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\%s", s );
if ( serverStatus->print ) {
score = ping = 0;
sscanf( s, "%d %d", &score, &ping );
s = strchr( s, ' ' );
if ( s ) {
s = strchr( s + 1, ' ' );
}
if ( s ) {
s++;
} else {
s = "unknown";
}
Com_Printf( "%-2d %-3d %-3d %s\n", i, score, ping, s );
}
}
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\" );
serverStatus->time = Com_Milliseconds();
serverStatus->address = from;
serverStatus->pending = qfalse;
if (serverStatus->print) {
serverStatus->retrieved = qtrue;
}
}
/*
==================
CL_LocalServers_f
==================
*/
void CL_LocalServers_f( void ) {
char *message;
int i, j;
netadr_t to;
Com_Printf( "Scanning for servers on the local network...\n" );
// reset the list, waiting for response
cls.numlocalservers = 0;
cls.pingUpdateSource = AS_LOCAL;
for ( i = 0; i < MAX_OTHER_SERVERS; i++ ) {
qboolean b = cls.localServers[i].visible;
Com_Memset( &cls.localServers[i], 0, sizeof( cls.localServers[i] ) );
cls.localServers[i].visible = b;
}
Com_Memset( &to, 0, sizeof( to ) );
// The 'xxx' in the message is a challenge that will be echoed back
// by the server. We don't care about that here, but master servers
// can use that to prevent spoofed server responses from invalid ip
message = "\377\377\377\377getinfo xxx";
// send each message twice in case one is dropped
for ( i = 0 ; i < 2 ; i++ ) {
// send a broadcast packet on each server port
// we support multiple server ports so a single machine
// can nicely run multiple servers
for ( j = 0 ; j < NUM_SERVER_PORTS ; j++ ) {
to.port = BigShort( (short)( PORT_SERVER + j ) );
to.type = NA_BROADCAST;
NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
to.type = NA_MULTICAST6;
NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
}
}
}
/*
==================
CL_GlobalServers_f
==================
*/
void CL_GlobalServers_f( void ) {
netadr_t to;
int count, i, masterNum;
char command[1024], *masteraddress;
if ((count = Cmd_Argc()) < 3 || (masterNum = atoi(Cmd_Argv(1))) < 0 || masterNum > MAX_MASTER_SERVERS - 1)
{
Com_Printf("usage: globalservers <master# 0-%d> <protocol> [keywords]\n", MAX_MASTER_SERVERS - 1);
return;
}
sprintf(command, "sv_master%d", masterNum + 1);
masteraddress = Cvar_VariableString(command);
if(!*masteraddress)
{
Com_Printf( "CL_GlobalServers_f: Error: No master server address given.\n");
return;
}
// reset the list, waiting for response
// -1 is used to distinguish a "no response"
i = NET_StringToAdr(masteraddress, &to, NA_UNSPEC);
if(!i)
{
Com_Printf( "CL_GlobalServers_f: Error: could not resolve address of master %s\n", masteraddress);
return;
}
else if(i == 2)
to.port = BigShort(PORT_MASTER);
Com_Printf("Requesting servers from master %s...\n", masteraddress);
cls.numglobalservers = -1;
cls.pingUpdateSource = AS_GLOBAL;
// Use the extended query for IPv6 masters
if (to.type == NA_IP6 || to.type == NA_MULTICAST6)
{
int v4enabled = Cvar_VariableIntegerValue("net_enabled") & NET_ENABLEV4;
if(v4enabled)
{
Com_sprintf(command, sizeof(command), "getserversExt %s %s",
com_gamename->string, Cmd_Argv(2));
}
else
{
Com_sprintf(command, sizeof(command), "getserversExt %s %s ipv6",
com_gamename->string, Cmd_Argv(2));
}
}
else if ( !Q_stricmp( com_gamename->string, LEGACY_MASTER_GAMENAME ) )
Com_sprintf(command, sizeof(command), "getservers %s",
Cmd_Argv(2));
else
Com_sprintf(command, sizeof(command), "getservers %s %s",
com_gamename->string, Cmd_Argv(2));
for (i=3; i < count; i++)
{
Q_strcat(command, sizeof(command), " ");
Q_strcat(command, sizeof(command), Cmd_Argv(i));
}
NET_OutOfBandPrint( NS_SERVER, to, "%s", command );
}
/*
==================
CL_GetPing
==================
*/
void CL_GetPing( int n, char *buf, int buflen, int *pingtime ) {
const char *str;
int time;
int maxPing;
if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port)
{
// empty or invalid slot
buf[0] = '\0';
*pingtime = 0;
return;
}
str = NET_AdrToStringwPort( cl_pinglist[n].adr );
Q_strncpyz( buf, str, buflen );
time = cl_pinglist[n].time;
if ( !time ) {
// check for timeout
time = Sys_Milliseconds() - cl_pinglist[n].start;
maxPing = Cvar_VariableIntegerValue( "cl_maxPing" );
if ( maxPing < 100 ) {
maxPing = 100;
}
if ( time < maxPing ) {
// not timed out yet
time = 0;
}
}
CL_SetServerInfoByAddress( cl_pinglist[n].adr, cl_pinglist[n].info, cl_pinglist[n].time );
*pingtime = time;
}
/*
==================
CL_GetPingInfo
==================
*/
void CL_GetPingInfo( int n, char *buf, int buflen ) {
if ( n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port ) {
// empty or invalid slot
if ( buflen ) {
buf[0] = '\0';
}
return;
}
Q_strncpyz( buf, cl_pinglist[n].info, buflen );
}
/*
==================
CL_ClearPing
==================
*/
void CL_ClearPing( int n ) {
if ( n < 0 || n >= MAX_PINGREQUESTS ) {
return;
}
cl_pinglist[n].adr.port = 0;
}
/*
==================
CL_GetPingQueueCount
==================
*/
int CL_GetPingQueueCount( void ) {
int i;
int count;
ping_t* pingptr;
count = 0;
pingptr = cl_pinglist;
for ( i = 0; i < MAX_PINGREQUESTS; i++, pingptr++ ) {
if ( pingptr->adr.port ) {
count++;
}
}
return ( count );
}
/*
==================
CL_GetFreePing
==================
*/
ping_t* CL_GetFreePing( void ) {
ping_t* pingptr;
ping_t* best;
int oldest;
int i;
int time;
pingptr = cl_pinglist;
for ( i = 0; i < MAX_PINGREQUESTS; i++, pingptr++ )
{
// find free ping slot
if ( pingptr->adr.port ) {
if ( !pingptr->time ) {
if (Sys_Milliseconds() - pingptr->start < 500)
{
// still waiting for response
continue;
}
} else if ( pingptr->time < 500 ) {
// results have not been queried
continue;
}
}
// clear it
pingptr->adr.port = 0;
return ( pingptr );
}
// use oldest entry
pingptr = cl_pinglist;
best = cl_pinglist;
oldest = INT_MIN;
for ( i = 0; i < MAX_PINGREQUESTS; i++, pingptr++ )
{
// scan for oldest
time = Sys_Milliseconds() - pingptr->start;
if ( time > oldest ) {
oldest = time;
best = pingptr;
}
}
return ( best );
}
/*
==================
CL_Ping_f
==================
*/
void CL_Ping_f( void ) {
netadr_t to;
ping_t* pingptr;
char* server;
int argc;
netadrtype_t family = NA_UNSPEC;
argc = Cmd_Argc();
if ( argc != 2 && argc != 3 ) {
Com_Printf( "usage: ping [-4|-6] server\n");
return;
}
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
Com_Memset( &to, 0, sizeof( netadr_t ) );
if ( !NET_StringToAdr( server, &to, family ) ) {
return;
}
pingptr = CL_GetFreePing();
memcpy( &pingptr->adr, &to, sizeof( netadr_t ) );
pingptr->start = Sys_Milliseconds();
pingptr->time = 0;
CL_SetServerInfoByAddress( pingptr->adr, NULL, 0 );
NET_OutOfBandPrint( NS_CLIENT, to, "getinfo xxx" );
}
/*
==================
CL_UpdateVisiblePings_f
==================
*/
qboolean CL_UpdateVisiblePings_f( int source ) {
int slots, i;
char buff[MAX_STRING_CHARS];
int pingTime;
int max;
qboolean status = qfalse;
if ( source < 0 || source > AS_FAVORITES ) {
return qfalse;
}
cls.pingUpdateSource = source;
slots = CL_GetPingQueueCount();
if ( slots < MAX_PINGREQUESTS ) {
serverInfo_t *server = NULL;
switch ( source ) {
case AS_LOCAL:
server = &cls.localServers[0];
max = cls.numlocalservers;
break;
case AS_GLOBAL:
server = &cls.globalServers[0];
max = cls.numglobalservers;
break;
case AS_FAVORITES:
server = &cls.favoriteServers[0];
max = cls.numfavoriteservers;
break;
default:
return qfalse;
}
for ( i = 0; i < max; i++ ) {
if ( server[i].visible ) {
if ( server[i].ping == -1 ) {
int j;
if ( slots >= MAX_PINGREQUESTS ) {
break;
}
for ( j = 0; j < MAX_PINGREQUESTS; j++ ) {
if ( !cl_pinglist[j].adr.port ) {
continue;
}
if ( NET_CompareAdr( cl_pinglist[j].adr, server[i].adr ) ) {
// already on the list
break;
}
}
if ( j >= MAX_PINGREQUESTS ) {
status = qtrue;
for ( j = 0; j < MAX_PINGREQUESTS; j++ ) {
if ( !cl_pinglist[j].adr.port ) {
break;
}
}
memcpy( &cl_pinglist[j].adr, &server[i].adr, sizeof( netadr_t ) );
cl_pinglist[j].start = Sys_Milliseconds();
cl_pinglist[j].time = 0;
NET_OutOfBandPrint( NS_CLIENT, cl_pinglist[j].adr, "getinfo xxx" );
slots++;
}
}
// if the server has a ping higher than cl_maxPing or
// the ping packet got lost
else if ( server[i].ping == 0 ) {
// if we are updating global servers
if ( source == AS_GLOBAL ) {
//
if ( cls.numGlobalServerAddresses > 0 ) {
// overwrite this server with one from the additional global servers
cls.numGlobalServerAddresses--;
CL_InitServerInfo( &server[i], &cls.globalServerAddresses[cls.numGlobalServerAddresses] );
// NOTE: the server[i].visible flag stays untouched
}
}
}
}
}
}
if ( slots ) {
status = qtrue;
}
for ( i = 0; i < MAX_PINGREQUESTS; i++ ) {
if ( !cl_pinglist[i].adr.port ) {
continue;
}
CL_GetPing( i, buff, MAX_STRING_CHARS, &pingTime );
if ( pingTime != 0 ) {
CL_ClearPing( i );
status = qtrue;
}
}
return status;
}
/*
==================
CL_UpdateServerInfo
==================
*/
void CL_UpdateServerInfo( int n ) {
if ( !cl_pinglist[n].adr.port ) {
return;
}
CL_SetServerInfoByAddress( cl_pinglist[n].adr, cl_pinglist[n].info, cl_pinglist[n].time );
}
/*
==================
CL_ServerStatus_f
==================
*/
void CL_ServerStatus_f( void ) {
netadr_t to, *toptr = NULL;
char *server;
serverStatus_t *serverStatus;
int argc;
netadrtype_t family = NA_UNSPEC;
argc = Cmd_Argc();
if ( argc != 2 && argc != 3 )
{
if (clc.state != CA_ACTIVE || clc.demoplaying)
{
Com_Printf( "Not connected to a server.\n" );
Com_Printf( "usage: serverstatus [-4|-6] server\n");
return;
}
toptr = &clc.serverAddress;
}
if(!toptr)
{
Com_Memset( &to, 0, sizeof(netadr_t) );
if(argc == 2)
server = Cmd_Argv(1);
else
{
if(!strcmp(Cmd_Argv(1), "-4"))
family = NA_IP;
else if(!strcmp(Cmd_Argv(1), "-6"))
family = NA_IP6;
else
Com_Printf( "warning: only -4 or -6 as address type understood.\n");
server = Cmd_Argv(2);
}
toptr = &to;
if ( !NET_StringToAdr( server, toptr, family ) )
return;
}
NET_OutOfBandPrint( NS_CLIENT, *toptr, "getstatus" );
serverStatus = CL_GetServerStatus( *toptr );
serverStatus->address = *toptr;
serverStatus->print = qtrue;
serverStatus->pending = qtrue;
}
/*
==================
CL_ShowIP_f
==================
*/
void CL_ShowIP_f( void ) {
Sys_ShowIP();
}
/*
=================
CL_CDKeyValidate
=================
*/
qboolean CL_CDKeyValidate( const char *key, const char *checksum ) {
#ifdef STANDALONE
return qtrue;
#else
char ch;
byte sum;
char chs[3];
int i, len;
len = strlen( key );
if ( len != CDKEY_LEN ) {
return qfalse;
}
if ( checksum && strlen( checksum ) != CDCHKSUM_LEN ) {
return qfalse;
}
sum = 0;
// for loop gets rid of conditional assignment warning
for ( i = 0; i < len; i++ ) {
ch = *key++;
if ( ch >= 'a' && ch <= 'z' ) {
ch -= 32;
}
switch ( ch ) {
case '2':
case '3':
case '7':
case 'A':
case 'B':
case 'C':
case 'D':
case 'G':
case 'H':
case 'J':
case 'L':
case 'P':
case 'R':
case 'S':
case 'T':
case 'W':
sum = ( sum << 1 ) ^ ch;
continue;
default:
return qfalse;
}
}
sprintf( chs, "%02x", sum );
if ( checksum && !Q_stricmp( chs, checksum ) ) {
return qtrue;
}
if ( !checksum ) {
return qtrue;
}
return qfalse;
#endif
}
// NERVE - SMF
/*
=======================
CL_AddToLimboChat
=======================
*/
void CL_AddToLimboChat( const char *str ) {
int len = 0;
char *p;
int i;
cl.limboChatPos = LIMBOCHAT_HEIGHT - 1;
// copy old strings
for ( i = cl.limboChatPos; i > 0; i-- ) {
strcpy( cl.limboChatMsgs[i], cl.limboChatMsgs[i - 1] );
}
// copy new string
p = cl.limboChatMsgs[0];
*p = 0;
while ( *str ) {
if ( len > LIMBOCHAT_WIDTH - 1 ) {
break;
}
if ( Q_IsColorString( str ) ) {
*p++ = *str++;
*p++ = *str++;
continue;
}
*p++ = *str++;
len++;
}
*p = 0;
}
/*
=======================
CL_GetLimboString
=======================
*/
qboolean CL_GetLimboString( int index, char *buf ) {
if ( index >= LIMBOCHAT_HEIGHT ) {
return qfalse;
}
strncpy( buf, cl.limboChatMsgs[index], 140 );
return qtrue;
}
// -NERVE - SMF
// NERVE - SMF - Localization code
#define FILE_HASH_SIZE 1024
#define MAX_VA_STRING 32000
#define MAX_TRANS_STRING 4096
typedef struct trans_s {
char original[MAX_TRANS_STRING];
char translated[MAX_LANGUAGES][MAX_TRANS_STRING];
struct trans_s *next;
float x_offset;
float y_offset;
qboolean fromFile;
} trans_t;
static trans_t* transTable[FILE_HASH_SIZE];
/*
=======================
AllocTrans
=======================
*/
static trans_t* AllocTrans( char *original, char *translated[MAX_LANGUAGES] ) {
trans_t *t;
int i;
t = malloc( sizeof( trans_t ) );
memset( t, 0, sizeof( trans_t ) );
if ( original ) {
strncpy( t->original, original, MAX_TRANS_STRING );
}
if ( translated ) {
for ( i = 0; i < MAX_LANGUAGES; i++ )
strncpy( t->translated[i], translated[i], MAX_TRANS_STRING );
}
return t;
}
/*
=======================
generateHashValue
=======================
*/
static long generateHashValue( const char *fname ) {
int i;
long hash;
char letter;
hash = 0;
i = 0;
while ( fname[i] != '\0' ) {
letter = tolower( fname[i] );
hash += (long)( letter ) * ( i + 119 );
i++;
}
hash &= ( FILE_HASH_SIZE - 1 );
return hash;
}
/*
=======================
LookupTrans
=======================
*/
static trans_t* LookupTrans( char *original, char *translated[MAX_LANGUAGES], qboolean isLoading ) {
trans_t *t, *newt, *prev = NULL;
long hash;
hash = generateHashValue( original );
for ( t = transTable[hash]; t; prev = t, t = t->next ) {
if ( !Q_stricmp( original, t->original ) ) {
if ( isLoading ) {
Com_DPrintf( S_COLOR_YELLOW "WARNING: Duplicate string found: \"%s\"\n", original );
}
return t;
}
}
newt = AllocTrans( original, translated );
if ( prev ) {
prev->next = newt;
} else {
transTable[hash] = newt;
}
if ( cl_debugTranslation->integer >= 1 && !isLoading ) {
Com_Printf( "Missing translation: \'%s\'\n", original );
}
// see if we want to save out the translation table everytime a string is added
// if ( cl_debugTranslation->integer == 2 && !isLoading ) {
// CL_SaveTransTable();
// }
return newt;
}
/*
=======================
CL_SaveTransTable
=======================
*/
void CL_SaveTransTable( const char *fileName, qboolean newOnly ) {
int bucketlen, bucketnum, maxbucketlen, avebucketlen;
int untransnum, transnum;
const char *buf;
fileHandle_t f;
trans_t *t;
int i, j, len;
if ( cl.corruptedTranslationFile ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Cannot save corrupted translation file. Please reload first." );
return;
}
FS_FOpenFileByMode( fileName, &f, FS_WRITE );
bucketnum = 0;
maxbucketlen = 0;
avebucketlen = 0;
transnum = 0;
untransnum = 0;
// write out version, if one
if ( strlen( cl.translationVersion ) ) {
buf = va( "#version\t\t\"%s\"\n", cl.translationVersion );
} else {
buf = va( "#version\t\t\"1.0 01/01/01\"\n" );
}
len = strlen( buf );
FS_Write( buf, len, f );
// write out translated strings
for ( j = 0; j < 2; j++ ) {
for ( i = 0; i < FILE_HASH_SIZE; i++ ) {
t = transTable[i];
if ( !t || ( newOnly && t->fromFile ) ) {
continue;
}
bucketlen = 0;
for ( ; t; t = t->next ) {
bucketlen++;
if ( strlen( t->translated[0] ) ) {
if ( j ) {
continue;
}
transnum++;
} else {
if ( !j ) {
continue;
}
untransnum++;
}
buf = va( "{\n\tenglish\t\t\"%s\"\n", t->original );
len = strlen( buf );
FS_Write( buf, len, f );
buf = va( "\tfrench\t\t\"%s\"\n", t->translated[LANGUAGE_FRENCH] );
len = strlen( buf );
FS_Write( buf, len, f );
buf = va( "\tgerman\t\t\"%s\"\n", t->translated[LANGUAGE_GERMAN] );
len = strlen( buf );
FS_Write( buf, len, f );
buf = va( "\titalian\t\t\"%s\"\n", t->translated[LANGUAGE_ITALIAN] );
len = strlen( buf );
FS_Write( buf, len, f );
buf = va( "\tspanish\t\t\"%s\"\n", t->translated[LANGUAGE_SPANISH] );
len = strlen( buf );
FS_Write( buf, len, f );
buf = va( "}\n" );
len = strlen( buf );
FS_Write( buf, len, f );
}
if ( bucketlen > maxbucketlen ) {
maxbucketlen = bucketlen;
}
if ( bucketlen ) {
bucketnum++;
avebucketlen += bucketlen;
}
}
}
Com_Printf( "Saved translation table.\nTotal = %i, Translated = %i, Untranslated = %i, aveblen = %2.2f, maxblen = %i\n",
transnum + untransnum, transnum, untransnum, (float)avebucketlen / bucketnum, maxbucketlen );
FS_FCloseFile( f );
}
/*
=======================
CL_CheckTranslationString
NERVE - SMF - compare formatting characters
=======================
*/
qboolean CL_CheckTranslationString( char *original, char *translated ) {
char format_org[128], format_trans[128];
int len, i;
memset( format_org, 0, 128 );
memset( format_trans, 0, 128 );
// generate formatting string for original
len = strlen( original );
for ( i = 0; i < len; i++ ) {
if ( original[i] != '%' ) {
continue;
}
strcat( format_org, va( "%c%c ", '%', original[i + 1] ) );
}
// generate formatting string for translated
len = strlen( translated );
if ( !len ) {
return qtrue;
}
for ( i = 0; i < len; i++ ) {
if ( translated[i] != '%' ) {
continue;
}
strcat( format_trans, va( "%c%c ", '%', translated[i + 1] ) );
}
// compare
len = strlen( format_org );
if ( len != strlen( format_trans ) ) {
return qfalse;
}
for ( i = 0; i < len; i++ ) {
if ( format_org[i] != format_trans[i] ) {
return qfalse;
}
}
return qtrue;
}
/*
=======================
CL_LoadTransTable
=======================
*/
void CL_LoadTransTable( const char *fileName ) {
char translated[MAX_LANGUAGES][MAX_VA_STRING];
char original[MAX_VA_STRING];
qboolean aborted;
char *text;
fileHandle_t f;
char *text_p;
char *token;
int len, i;
trans_t *t;
int count;
count = 0;
aborted = qfalse;
cl.corruptedTranslationFile = qfalse;
len = FS_FOpenFileByMode( fileName, &f, FS_READ );
if ( len <= 0 ) {
return;
}
text = malloc( len + 1 );
if ( !text ) {
return;
}
FS_Read( text, len, f );
text[len] = 0;
FS_FCloseFile( f );
// parse the text
text_p = text;
do {
token = COM_Parse( &text_p );
if ( Q_stricmp( "{", token ) ) {
// parse version number
if ( !Q_stricmp( "#version", token ) ) {
token = COM_Parse( &text_p );
strcpy( cl.translationVersion, token );
continue;
}
break;
}
// english
token = COM_Parse( &text_p );
if ( Q_stricmp( "english", token ) ) {
aborted = qtrue;
break;
}
token = COM_Parse( &text_p );
strcpy( original, token );
if ( cl_debugTranslation->integer == 3 ) {
Com_Printf( "%i Loading: \"%s\"\n", count, original );
}
// french
token = COM_Parse( &text_p );
if ( Q_stricmp( "french", token ) ) {
aborted = qtrue;
break;
}
token = COM_Parse( &text_p );
strcpy( translated[LANGUAGE_FRENCH], token );
if ( !CL_CheckTranslationString( original, translated[LANGUAGE_FRENCH] ) ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Translation formatting doesn't match up with English version!\n" );
aborted = qtrue;
break;
}
// german
token = COM_Parse( &text_p );
if ( Q_stricmp( "german", token ) ) {
aborted = qtrue;
break;
}
token = COM_Parse( &text_p );
strcpy( translated[LANGUAGE_GERMAN], token );
if ( !CL_CheckTranslationString( original, translated[LANGUAGE_GERMAN] ) ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Translation formatting doesn't match up with English version!\n" );
aborted = qtrue;
break;
}
// italian
token = COM_Parse( &text_p );
if ( Q_stricmp( "italian", token ) ) {
aborted = qtrue;
break;
}
token = COM_Parse( &text_p );
strcpy( translated[LANGUAGE_ITALIAN], token );
if ( !CL_CheckTranslationString( original, translated[LANGUAGE_ITALIAN] ) ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Translation formatting doesn't match up with English version!\n" );
aborted = qtrue;
break;
}
// spanish
token = COM_Parse( &text_p );
if ( Q_stricmp( "spanish", token ) ) {
aborted = qtrue;
break;
}
token = COM_Parse( &text_p );
strcpy( translated[LANGUAGE_SPANISH], token );
if ( !CL_CheckTranslationString( original, translated[LANGUAGE_SPANISH] ) ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Translation formatting doesn't match up with English version!\n" );
aborted = qtrue;
break;
}
// do lookup
t = LookupTrans( original, NULL, qtrue );
if ( t ) {
t->fromFile = qtrue;
for ( i = 0; i < MAX_LANGUAGES; i++ )
strncpy( t->translated[i], translated[i], MAX_TRANS_STRING );
}
token = COM_Parse( &text_p );
// set offset if we have one
if ( !Q_stricmp( "offset", token ) ) {
if ( t )
{
token = COM_Parse( &text_p );
t->x_offset = atof( token );
token = COM_Parse( &text_p );
t->y_offset = atof( token );
token = COM_Parse( &text_p );
}
}
if ( Q_stricmp( "}", token ) ) {
aborted = qtrue;
break;
}
count++;
} while ( token );
if ( aborted ) {
int i, line = 1;
for ( i = 0; i < len && ( text + i ) < text_p; i++ ) {
if ( text[i] == '\n' ) {
line++;
}
}
Com_Printf( S_COLOR_YELLOW "WARNING: Problem loading %s on line %i\n", fileName, line );
cl.corruptedTranslationFile = qtrue;
} else {
Com_Printf( "Loaded %i translation strings from %s\n", count, fileName );
}
// cleanup
free( text );
}
/*
=======================
CL_ReloadTranslation
=======================
*/
void CL_ReloadTranslation( void ) {
char **fileList;
int numFiles, i;
char fileName[MAX_QPATH];
for ( i = 0; i < FILE_HASH_SIZE; i++ ) {
if ( transTable[i] ) {
free( transTable[i] );
}
}
memset( transTable, 0, sizeof( trans_t* ) * FILE_HASH_SIZE );
CL_LoadTransTable( "scripts/translation.cfg" );
fileList = FS_ListFiles( "translations", ".cfg", &numFiles );
for ( i = 0; i < numFiles; i++ ) {
Com_sprintf( fileName, sizeof (fileName), "translations/%s", fileList[i] );
CL_LoadTransTable( fileName );
}
}
/*
=======================
CL_InitTranslation
=======================
*/
void CL_InitTranslation( void ) {
char **fileList;
int numFiles, i;
char fileName[MAX_QPATH];
memset( transTable, 0, sizeof( trans_t* ) * FILE_HASH_SIZE );
CL_LoadTransTable( "scripts/translation.cfg" );
fileList = FS_ListFiles( "translations", ".cfg", &numFiles );
for ( i = 0; i < numFiles; i++ ) {
Com_sprintf( fileName, sizeof (fileName), "translations/%s", fileList[i] );
CL_LoadTransTable( fileName );
}
}
/*
=======================
CL_TranslateString
=======================
*/
void CL_TranslateString( const char *string, char *dest_buffer ) {
int i, count, currentLanguage;
trans_t *t;
qboolean newline = qfalse;
char *buf;
buf = dest_buffer;
currentLanguage = cl_language->integer - 1;
// early bail if we only want english or bad language type
if ( !string ) {
strcpy( buf, "(null)" );
return;
} else if ( currentLanguage == -1 || currentLanguage >= MAX_LANGUAGES || !strlen( string ) ) {
strcpy( buf, string );
return;
}
// ignore newlines
if ( string[strlen( string ) - 1] == '\n' ) {
newline = qtrue;
}
for ( i = 0, count = 0; string[i] != '\0'; i++ ) {
if ( string[i] != '\n' ) {
buf[count++] = string[i];
}
}
buf[count] = '\0';
t = LookupTrans( buf, NULL, qfalse );
if ( t && strlen( t->translated[currentLanguage] ) ) {
int offset = 0;
if ( cl_debugTranslation->integer >= 1 ) {
buf[0] = '^';
buf[1] = '1';
buf[2] = '[';
offset = 3;
}
strcpy( buf + offset, t->translated[currentLanguage] );
if ( cl_debugTranslation->integer >= 1 ) {
int len2 = strlen( buf );
buf[len2] = ']';
buf[len2 + 1] = '^';
buf[len2 + 2] = '7';
buf[len2 + 3] = '\0';
}
if ( newline ) {
int len2 = strlen( buf );
buf[len2] = '\n';
buf[len2 + 1] = '\0';
}
} else {
int offset = 0;
if ( cl_debugTranslation->integer >= 1 ) {
buf[0] = '^';
buf[1] = '1';
buf[2] = '[';
offset = 3;
}
strcpy( buf + offset, string );
if ( cl_debugTranslation->integer >= 1 ) {
int len2 = strlen( buf );
qboolean addnewline = qfalse;
if ( buf[len2 - 1] == '\n' ) {
len2--;
addnewline = qtrue;
}
buf[len2] = ']';
buf[len2 + 1] = '^';
buf[len2 + 2] = '7';
buf[len2 + 3] = '\0';
if ( addnewline ) {
buf[len2 + 3] = '\n';
buf[len2 + 4] = '\0';
}
}
}
}
/*
=======================
CL_TranslateStringBuf
TTimo - handy, stores in a static buf, converts \n to chr(13)
=======================
*/
const char* CL_TranslateStringBuf( const char *string ) {
char *p;
int i,l;
static char buf[MAX_VA_STRING];
CL_TranslateString( string, buf );
while ( ( p = strstr( buf, "\\n" ) ) )
{
*p = '\n';
p++;
// Com_Memcpy(p, p+1, strlen(p) ); b0rks on win32
l = strlen( p );
for ( i = 0; i < l; i++ )
{
*p = *( p + 1 );
p++;
}
}
return buf;
}
/*
=======================
CL_OpenURLForCvar
=======================
*/
void CL_OpenURL( const char *url ) {
if ( !url || !strlen( url ) ) {
Com_Printf( "%s", CL_TranslateStringBuf( "invalid/empty URL\n" ) );
return;
}
Sys_OpenURL( url, qtrue );
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_3233_0 |
crossvul-cpp_data_good_3231_2 | /*
===========================================================================
Return to Castle Wolfenstein single player GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein single player GPL Source Code (RTCW SP Source Code).
RTCW SP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW SP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
// console.c
#include "client.h"
int g_console_field_width = 78;
#define COLNSOLE_COLOR COLOR_WHITE //COLOR_BLACK
#define NUM_CON_TIMES 4
//#define CON_TEXTSIZE 32768
#define CON_TEXTSIZE 65536 // (SA) DM want's more console...
typedef struct {
qboolean initialized;
short text[CON_TEXTSIZE];
int current; // line where next message will be printed
int x; // offset in current line for next print
int display; // bottom of console displays this line
int linewidth; // characters across screen
int totallines; // total lines in console scrollback
float xadjust; // for wide aspect screens
float displayFrac; // aproaches finalFrac at scr_conspeed
float finalFrac; // 0.0 to 1.0 lines of console to display
int vislines; // in scanlines
int times[NUM_CON_TIMES]; // cls.realtime time the line was generated
// for transparent notify lines
vec4_t color;
} console_t;
console_t con;
cvar_t *con_debug;
cvar_t *con_conspeed;
cvar_t *con_notifytime;
#define DEFAULT_CONSOLE_WIDTH 78
/*
================
Con_ToggleConsole_f
================
*/
void Con_ToggleConsole_f( void ) {
// Can't toggle the console when it's the only thing available
if ( clc.state == CA_DISCONNECTED && Key_GetCatcher( ) == KEYCATCH_CONSOLE ) {
return;
}
Field_Clear( &g_consoleField );
g_consoleField.widthInChars = g_console_field_width;
Con_ClearNotify();
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_CONSOLE );
}
/*
===================
Con_ToggleMenu_f
===================
*/
void Con_ToggleMenu_f( void ) {
CL_KeyEvent( K_ESCAPE, qtrue, Sys_Milliseconds() );
CL_KeyEvent( K_ESCAPE, qfalse, Sys_Milliseconds() );
}
/*
================
Con_MessageMode_f
================
*/
void Con_MessageMode_f( void ) {
chat_playerNum = -1;
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode2_f
================
*/
void Con_MessageMode2_f( void ) {
chat_playerNum = -1;
chat_team = qtrue;
Field_Clear( &chatField );
chatField.widthInChars = 25;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode3_f
================
*/
void Con_MessageMode3_f( void ) {
chat_playerNum = VM_Call( cgvm, CG_CROSSHAIR_PLAYER );
if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) {
chat_playerNum = -1;
return;
}
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode4_f
================
*/
void Con_MessageMode4_f( void ) {
chat_playerNum = VM_Call( cgvm, CG_LAST_ATTACKER );
if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) {
chat_playerNum = -1;
return;
}
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
// NERVE - SMF
/*
================
Con_StartLimboMode_f
================
*/
void Con_StartLimboMode_f( void ) {
chat_limbo = qtrue;
}
/*
================
Con_StopLimboMode_f
================
*/
void Con_StopLimboMode_f( void ) {
chat_limbo = qfalse;
}
// -NERVE - SMF
/*
================
Con_Clear_f
================
*/
void Con_Clear_f( void ) {
int i;
for ( i = 0 ; i < CON_TEXTSIZE ; i++ ) {
con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
}
Con_Bottom(); // go to end
}
/*
================
Con_Dump_f
Save the console contents out to a file
================
*/
void Con_Dump_f( void ) {
int l, x, i;
short *line;
fileHandle_t f;
int bufferlen;
char *buffer;
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: condump <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".txt" );
if (!COM_CompareExtension(filename, ".txt"))
{
Com_Printf("Con_Dump_f: Only the \".txt\" extension is supported by this command!\n");
return;
}
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf ("ERROR: couldn't open %s.\n", filename);
return;
}
Com_Printf ("Dumped console text to %s.\n", filename );
// skip empty lines
for ( l = con.current - con.totallines + 1 ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( x = 0 ; x < con.linewidth ; x++ )
if ( ( line[x] & 0xff ) != ' ' ) {
break;
}
if ( x != con.linewidth ) {
break;
}
}
#ifdef _WIN32
bufferlen = con.linewidth + 3 * sizeof ( char );
#else
bufferlen = con.linewidth + 2 * sizeof ( char );
#endif
buffer = Hunk_AllocateTempMemory( bufferlen );
// write the remaining lines
buffer[bufferlen-1] = 0;
for ( ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( i = 0; i < con.linewidth; i++ )
buffer[i] = line[i] & 0xff;
for ( x = con.linewidth - 1 ; x >= 0 ; x-- )
{
if ( buffer[x] == ' ' ) {
buffer[x] = 0;
} else {
break;
}
}
#ifdef _WIN32
Q_strcat(buffer, bufferlen, "\r\n");
#else
Q_strcat(buffer, bufferlen, "\n");
#endif
FS_Write( buffer, strlen( buffer ), f );
}
Hunk_FreeTempMemory( buffer );
FS_FCloseFile( f );
}
/*
================
Con_ClearNotify
================
*/
void Con_ClearNotify( void ) {
int i;
for ( i = 0 ; i < NUM_CON_TIMES ; i++ ) {
con.times[i] = 0;
}
}
/*
================
Con_CheckResize
If the line width has changed, reformat the buffer.
================
*/
void Con_CheckResize( void ) {
int i, j, width, oldwidth, oldtotallines, numlines, numchars;
short tbuf[CON_TEXTSIZE];
width = ( SCREEN_WIDTH / SMALLCHAR_WIDTH ) - 2;
if ( width == con.linewidth ) {
return;
}
if ( width < 1 ) { // video hasn't been initialized yet
width = DEFAULT_CONSOLE_WIDTH;
con.linewidth = width;
con.totallines = CON_TEXTSIZE / con.linewidth;
for ( i = 0; i < CON_TEXTSIZE; i++ )
con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
} else
{
oldwidth = con.linewidth;
con.linewidth = width;
oldtotallines = con.totallines;
con.totallines = CON_TEXTSIZE / con.linewidth;
numlines = oldtotallines;
if ( con.totallines < numlines ) {
numlines = con.totallines;
}
numchars = oldwidth;
if ( con.linewidth < numchars ) {
numchars = con.linewidth;
}
memcpy( tbuf, con.text, CON_TEXTSIZE * sizeof( short ) );
for ( i = 0; i < CON_TEXTSIZE; i++ )
con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
for ( i = 0 ; i < numlines ; i++ )
{
for ( j = 0 ; j < numchars ; j++ )
{
con.text[( con.totallines - 1 - i ) * con.linewidth + j] =
tbuf[( ( con.current - i + oldtotallines ) %
oldtotallines ) * oldwidth + j];
}
}
Con_ClearNotify();
}
con.current = con.totallines - 1;
con.display = con.current;
}
/*
==================
Cmd_CompleteTxtName
==================
*/
void Cmd_CompleteTxtName( char *args, int argNum ) {
if( argNum == 2 ) {
Field_CompleteFilename( "", "txt", qfalse, qtrue );
}
}
/*
================
Con_Init
================
*/
void Con_Init( void ) {
int i;
con_notifytime = Cvar_Get( "con_notifytime", "3", 0 );
con_conspeed = Cvar_Get( "scr_conspeed", "3", 0 );
con_debug = Cvar_Get( "con_debug", "0", CVAR_ARCHIVE ); //----(SA) added
Field_Clear( &g_consoleField );
g_consoleField.widthInChars = g_console_field_width;
for ( i = 0 ; i < COMMAND_HISTORY ; i++ ) {
Field_Clear( &historyEditLines[i] );
historyEditLines[i].widthInChars = g_console_field_width;
}
CL_LoadConsoleHistory( );
Cmd_AddCommand( "toggleconsole", Con_ToggleConsole_f );
Cmd_AddCommand ("togglemenu", Con_ToggleMenu_f);
Cmd_AddCommand( "messagemode", Con_MessageMode_f );
Cmd_AddCommand( "messagemode2", Con_MessageMode2_f );
Cmd_AddCommand( "messagemode3", Con_MessageMode3_f );
Cmd_AddCommand( "messagemode4", Con_MessageMode4_f );
Cmd_AddCommand( "startLimboMode", Con_StartLimboMode_f ); // NERVE - SMF
Cmd_AddCommand( "stopLimboMode", Con_StopLimboMode_f ); // NERVE - SMF
Cmd_AddCommand( "clear", Con_Clear_f );
Cmd_AddCommand( "condump", Con_Dump_f );
Cmd_SetCommandCompletionFunc( "condump", Cmd_CompleteTxtName );
}
/*
================
Con_Shutdown
================
*/
void Con_Shutdown(void)
{
Cmd_RemoveCommand("toggleconsole");
Cmd_RemoveCommand("togglemenu");
Cmd_RemoveCommand("messagemode");
Cmd_RemoveCommand("messagemode2");
Cmd_RemoveCommand("messagemode3");
Cmd_RemoveCommand("messagemode4");
Cmd_RemoveCommand("startLimboMode");
Cmd_RemoveCommand("stopLimboMode");
Cmd_RemoveCommand("clear");
Cmd_RemoveCommand("condump");
}
/*
===============
Con_Linefeed
===============
*/
void Con_Linefeed( void ) {
int i;
// mark time for transparent overlay
if ( con.current >= 0 ) {
con.times[con.current % NUM_CON_TIMES] = cls.realtime;
}
con.x = 0;
if ( con.display == con.current ) {
con.display++;
}
con.current++;
for ( i = 0; i < con.linewidth; i++ )
con.text[( con.current % con.totallines ) * con.linewidth + i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
}
/*
================
CL_ConsolePrint
Handles cursor positioning, line wrapping, etc
All console printing must go through this in order to be logged to disk
If no console is visible, the text will appear at the top of the game window
================
*/
void CL_ConsolePrint( char *txt ) {
int y, l;
unsigned char c;
unsigned short color;
// for some demos we don't want to ever show anything on the console
if ( cl_noprint && cl_noprint->integer ) {
return;
}
if ( !con.initialized ) {
con.color[0] =
con.color[1] =
con.color[2] =
con.color[3] = 1.0f;
con.linewidth = -1;
Con_CheckResize();
con.initialized = qtrue;
}
color = ColorIndex( COLNSOLE_COLOR );
while ( (c = *((unsigned char *) txt)) != 0 ) {
if ( Q_IsColorString( txt ) ) {
color = ColorIndex( *( txt + 1 ) );
txt += 2;
continue;
}
// count word length
for ( l = 0 ; l < con.linewidth ; l++ ) {
if ( txt[l] <= ' ' ) {
break;
}
}
// word wrap
if ( l != con.linewidth && ( con.x + l >= con.linewidth ) ) {
Con_Linefeed();
}
txt++;
switch ( c )
{
case '\n':
Con_Linefeed();
break;
case '\r':
con.x = 0;
break;
default: // display character and advance
y = con.current % con.totallines;
con.text[y * con.linewidth + con.x] = ( color << 8 ) | c;
con.x++;
if(con.x >= con.linewidth)
Con_Linefeed();
break;
}
}
// mark time for transparent overlay
if ( con.current >= 0 ) {
con.times[con.current % NUM_CON_TIMES] = cls.realtime;
}
}
/*
==============================================================================
DRAWING
==============================================================================
*/
/*
================
Con_DrawInput
Draw the editline after a ] prompt
================
*/
void Con_DrawInput( void ) {
int y;
if ( clc.state != CA_DISCONNECTED && !(Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ) {
return;
}
y = con.vislines - ( SMALLCHAR_HEIGHT * 2 );
re.SetColor( con.color );
SCR_DrawSmallChar( con.xadjust + 1 * SMALLCHAR_WIDTH, y, ']' );
Field_Draw( &g_consoleField, con.xadjust + 2 * SMALLCHAR_WIDTH, y,
SCREEN_WIDTH - 3 * SMALLCHAR_WIDTH, qtrue, qtrue );
}
/*
================
Con_DrawNotify
Draws the last few lines of output transparently over the game top
================
*/
void Con_DrawNotify( void ) {
int x, v;
short *text;
int i;
int time;
int skip;
int currentColor;
currentColor = 7;
re.SetColor( g_color_table[currentColor] );
v = 0;
for ( i = con.current - NUM_CON_TIMES + 1 ; i <= con.current ; i++ )
{
if ( i < 0 ) {
continue;
}
time = con.times[i % NUM_CON_TIMES];
if ( time == 0 ) {
continue;
}
time = cls.realtime - time;
if ( time > con_notifytime->value * 1000 ) {
continue;
}
text = con.text + ( i % con.totallines ) * con.linewidth;
if (cl.snap.ps.pm_type != PM_INTERMISSION && Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME) ) {
continue;
}
for ( x = 0 ; x < con.linewidth ; x++ ) {
if ( ( text[x] & 0xff ) == ' ' ) {
continue;
}
if ( ColorIndexForNumber( text[x] >> 8 ) != currentColor ) {
currentColor = ColorIndexForNumber( text[x] >> 8 );
re.SetColor( g_color_table[currentColor] );
}
SCR_DrawSmallChar( cl_conXOffset->integer + con.xadjust + ( x + 1 ) * SMALLCHAR_WIDTH, v, text[x] & 0xff );
}
v += SMALLCHAR_HEIGHT;
}
re.SetColor( NULL );
if (Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME) ) {
return;
}
// draw the chat line
if ( Key_GetCatcher( ) & KEYCATCH_MESSAGE ) {
if ( chat_team ) {
SCR_DrawBigString (8, v, "say_team:", 1.0f, qfalse );
skip = 10;
} else
{
SCR_DrawBigString (8, v, "say:", 1.0f, qfalse );
skip = 5;
}
Field_BigDraw( &chatField, skip * BIGCHAR_WIDTH, v, SCREEN_WIDTH - ( skip + 1 ) * BIGCHAR_WIDTH, qtrue, qtrue );
}
}
/*
================
Con_DrawSolidConsole
Draws the console with the solid background
================
*/
void Con_DrawSolidConsole( float frac ) {
int i, x, y;
int rows;
short *text;
int row;
int lines;
int currentColor;
vec4_t color;
lines = cls.glconfig.vidHeight * frac;
if ( lines <= 0 ) {
return;
}
if ( lines > cls.glconfig.vidHeight ) {
lines = cls.glconfig.vidHeight;
}
// on wide screens, we will center the text
con.xadjust = 0;
SCR_AdjustFrom640( &con.xadjust, NULL, NULL, NULL );
// draw the background
y = frac * SCREEN_HEIGHT;
if ( y < 1 ) {
y = 0;
} else {
SCR_DrawPic( 0, 0, SCREEN_WIDTH, y, cls.consoleShader );
if ( frac >= 0.5f ) {
color[0] = color[1] = color[2] = frac * 2.0f;
color[3] = 1.0f;
re.SetColor( color );
// draw the logo
SCR_DrawPic( 192, 70, 256, 128, cls.consoleShader2 );
re.SetColor( NULL );
}
}
color[0] = 0;
color[1] = 0;
color[2] = 0;
color[3] = 0.6f;
SCR_FillRect( 0, y, SCREEN_WIDTH, 2, color );
// draw the version number
re.SetColor( g_color_table[ColorIndex( COLNSOLE_COLOR )] );
i = strlen( Q3_VERSION );
for ( x = 0 ; x < i ; x++ ) {
SCR_DrawSmallChar( cls.glconfig.vidWidth - ( i - x + 1 ) * SMALLCHAR_WIDTH, lines - SMALLCHAR_HEIGHT, Q3_VERSION[x] );
}
// draw the text
con.vislines = lines;
rows = ( lines - SMALLCHAR_HEIGHT ) / SMALLCHAR_HEIGHT; // rows of text to draw
y = lines - ( SMALLCHAR_HEIGHT * 3 );
// draw from the bottom up
if ( con.display != con.current ) {
// draw arrows to show the buffer is backscrolled
re.SetColor( g_color_table[ColorIndex( COLOR_WHITE )] );
for ( x = 0 ; x < con.linewidth ; x += 4 )
SCR_DrawSmallChar( con.xadjust + ( x + 1 ) * SMALLCHAR_WIDTH, y, '^' );
y -= SMALLCHAR_HEIGHT;
rows--;
}
row = con.display;
if ( con.x == 0 ) {
row--;
}
currentColor = 7;
re.SetColor( g_color_table[currentColor] );
for ( i = 0 ; i < rows ; i++, y -= SMALLCHAR_HEIGHT, row-- )
{
if ( row < 0 ) {
break;
}
if ( con.current - row >= con.totallines ) {
// past scrollback wrap point
continue;
}
text = con.text + ( row % con.totallines ) * con.linewidth;
for ( x = 0 ; x < con.linewidth ; x++ ) {
if ( ( text[x] & 0xff ) == ' ' ) {
continue;
}
if ( ColorIndexForNumber( text[x] >> 8 ) != currentColor ) {
currentColor = ColorIndexForNumber( text[x] >> 8 );
re.SetColor( g_color_table[currentColor] );
}
SCR_DrawSmallChar( con.xadjust + ( x + 1 ) * SMALLCHAR_WIDTH, y, text[x] & 0xff );
}
}
// draw the input prompt, user text, and cursor if desired
Con_DrawInput();
re.SetColor( NULL );
}
/*
==================
Con_DrawConsole
==================
*/
void Con_DrawConsole( void ) {
// check for console width changes from a vid mode change
Con_CheckResize();
// if disconnected, render console full screen
switch ( clc.state ) {
case CA_UNINITIALIZED:
case CA_CONNECTING: // sending request packets to the server
case CA_CHALLENGING: // sending challenge packets to the server
case CA_CONNECTED: // netchan_t established, getting gamestate
case CA_PRIMED: // got gamestate, waiting for first frame
case CA_LOADING: // only during cgame initialization, never during main loop
if ( !con_debug->integer ) { // these are all 'no console at all' when con_debug is not set
return;
}
if ( Key_GetCatcher( ) & KEYCATCH_UI ) {
return;
}
Con_DrawSolidConsole( 1.0 );
return;
case CA_DISCONNECTED: // not talking to a server
if ( !( Key_GetCatcher( ) & KEYCATCH_UI ) ) {
Con_DrawSolidConsole( 1.0 );
return;
}
break;
case CA_ACTIVE: // game views should be displayed
if ( con.displayFrac ) {
if ( con_debug->integer == 2 ) { // 2 means draw full screen console at '~'
// Con_DrawSolidConsole( 1.0f );
Con_DrawSolidConsole( con.displayFrac * 2.0f );
return;
}
}
break;
case CA_CINEMATIC: // playing a cinematic or a static pic, not connected to a server
default:
break;
}
if ( con.displayFrac ) {
Con_DrawSolidConsole( con.displayFrac );
} else {
Con_DrawNotify(); // draw notify lines
}
}
//================================================================
/*
==================
Con_RunConsole
Scroll it up or down
==================
*/
void Con_RunConsole( void ) {
// decide on the destination height of the console
if ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) {
con.finalFrac = 0.5; // half screen
} else {
con.finalFrac = 0; // none visible
}
// scroll towards the destination height
if ( con.finalFrac < con.displayFrac ) {
con.displayFrac -= con_conspeed->value * cls.realFrametime * 0.001;
if ( con.finalFrac > con.displayFrac ) {
con.displayFrac = con.finalFrac;
}
} else if ( con.finalFrac > con.displayFrac ) {
con.displayFrac += con_conspeed->value * cls.realFrametime * 0.001;
if ( con.finalFrac < con.displayFrac ) {
con.displayFrac = con.finalFrac;
}
}
}
void Con_PageUp( void ) {
con.display -= 2;
if ( con.current - con.display >= con.totallines ) {
con.display = con.current - con.totallines + 1;
}
}
void Con_PageDown( void ) {
con.display += 2;
if ( con.display > con.current ) {
con.display = con.current;
}
}
void Con_Top( void ) {
con.display = con.totallines;
if ( con.current - con.display >= con.totallines ) {
con.display = con.current - con.totallines + 1;
}
}
void Con_Bottom( void ) {
con.display = con.current;
}
void Con_Close( void ) {
if ( !com_cl_running->integer ) {
return;
}
Field_Clear( &g_consoleField );
Con_ClearNotify();
Key_SetCatcher( Key_GetCatcher( ) & ~KEYCATCH_CONSOLE );
con.finalFrac = 0; // none visible
con.displayFrac = 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3231_2 |
crossvul-cpp_data_good_3233_2 | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include <signal.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/types.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#ifndef DEDICATED
#ifdef USE_LOCAL_HEADERS
# include "SDL.h"
# include "SDL_cpuinfo.h"
#else
# include <SDL.h>
# include <SDL_cpuinfo.h>
#endif
#endif
#include "sys_local.h"
#include "sys_loadlib.h"
#include "../qcommon/q_shared.h"
#include "../qcommon/qcommon.h"
static char binaryPath[ MAX_OSPATH ] = { 0 };
static char installPath[ MAX_OSPATH ] = { 0 };
/*
=================
Sys_SetBinaryPath
=================
*/
void Sys_SetBinaryPath(const char *path)
{
Q_strncpyz(binaryPath, path, sizeof(binaryPath));
}
/*
=================
Sys_BinaryPath
=================
*/
char *Sys_BinaryPath(void)
{
return binaryPath;
}
/*
=================
Sys_SetDefaultInstallPath
=================
*/
void Sys_SetDefaultInstallPath(const char *path)
{
Q_strncpyz(installPath, path, sizeof(installPath));
}
/*
=================
Sys_DefaultInstallPath
=================
*/
char *Sys_DefaultInstallPath(void)
{
if (*installPath)
return installPath;
else
return Sys_Cwd();
}
/*
=================
Sys_DefaultAppPath
=================
*/
char *Sys_DefaultAppPath(void)
{
return Sys_BinaryPath();
}
/*
=================
Sys_In_Restart_f
Restart the input subsystem
=================
*/
void Sys_In_Restart_f( void )
{
IN_Restart( );
}
/*
=================
Sys_ConsoleInput
Handle new console input
=================
*/
char *Sys_ConsoleInput(void)
{
return CON_Input( );
}
/*
==================
Sys_GetClipboardData
==================
*/
char *Sys_GetClipboardData(void)
{
#ifdef DEDICATED
return NULL;
#else
char *data = NULL;
char *cliptext;
if ( ( cliptext = SDL_GetClipboardText() ) != NULL ) {
if ( cliptext[0] != '\0' ) {
size_t bufsize = strlen( cliptext ) + 1;
data = Z_Malloc( bufsize );
Q_strncpyz( data, cliptext, bufsize );
// find first listed char and set to '\0'
strtok( data, "\n\r\b" );
}
SDL_free( cliptext );
}
return data;
#endif
}
#ifdef DEDICATED
# define PID_FILENAME "iowolfmp_server.pid"
#else
# define PID_FILENAME "iowolfmp.pid"
#endif
/*
=================
Sys_PIDFileName
=================
*/
static char *Sys_PIDFileName( const char *gamedir )
{
const char *homePath = Cvar_VariableString( "fs_homepath" );
if( *homePath != '\0' )
return va( "%s/%s/%s", homePath, gamedir, PID_FILENAME );
return NULL;
}
/*
=================
Sys_RemovePIDFile
=================
*/
void Sys_RemovePIDFile( const char *gamedir )
{
char *pidFile = Sys_PIDFileName( gamedir );
if( pidFile != NULL )
remove( pidFile );
}
/*
=================
Sys_WritePIDFile
Return qtrue if there is an existing stale PID file
=================
*/
static qboolean Sys_WritePIDFile( const char *gamedir )
{
char *pidFile = Sys_PIDFileName( gamedir );
FILE *f;
qboolean stale = qfalse;
if( pidFile == NULL )
return qfalse;
// First, check if the pid file is already there
if( ( f = fopen( pidFile, "r" ) ) != NULL )
{
char pidBuffer[ 64 ] = { 0 };
int pid;
pid = fread( pidBuffer, sizeof( char ), sizeof( pidBuffer ) - 1, f );
fclose( f );
if(pid > 0)
{
pid = atoi( pidBuffer );
if( !Sys_PIDIsRunning( pid ) )
stale = qtrue;
}
else
stale = qtrue;
}
if( FS_CreatePath( pidFile ) ) {
return 0;
}
if( ( f = fopen( pidFile, "w" ) ) != NULL )
{
fprintf( f, "%d", Sys_PID( ) );
fclose( f );
}
else
Com_Printf( S_COLOR_YELLOW "Couldn't write %s.\n", pidFile );
return stale;
}
/*
=================
Sys_InitPIDFile
=================
*/
void Sys_InitPIDFile( const char *gamedir ) {
if( Sys_WritePIDFile( gamedir ) ) {
#ifndef DEDICATED
char message[1024];
char modName[MAX_OSPATH];
FS_GetModDescription( gamedir, modName, sizeof ( modName ) );
Q_CleanStr( modName );
Com_sprintf( message, sizeof (message), "The last time %s ran, "
"it didn't exit properly. This may be due to inappropriate video "
"settings. Would you like to start with \"safe\" video settings?", modName );
if( Sys_Dialog( DT_YES_NO, message, "Abnormal Exit" ) == DR_YES ) {
Cvar_Set( "com_abnormalExit", "1" );
}
#endif
}
}
/*
=================
Sys_Exit
Single exit point (regular exit or in case of error)
=================
*/
static __attribute__ ((noreturn)) void Sys_Exit( int exitCode )
{
CON_Shutdown( );
#ifndef DEDICATED
SDL_Quit( );
#endif
if( exitCode < 2 && com_fullyInitialized )
{
// Normal exit
Sys_RemovePIDFile( FS_GetCurrentGameDir() );
}
NET_Shutdown( );
Sys_PlatformExit( );
exit( exitCode );
}
/*
=================
Sys_Quit
=================
*/
void Sys_Quit( void )
{
Sys_Exit( 0 );
}
/*
=================
Sys_GetProcessorFeatures
=================
*/
cpuFeatures_t Sys_GetProcessorFeatures( void )
{
cpuFeatures_t features = 0;
#ifndef DEDICATED
if( SDL_HasRDTSC( ) ) features |= CF_RDTSC;
if( SDL_Has3DNow( ) ) features |= CF_3DNOW;
if( SDL_HasMMX( ) ) features |= CF_MMX;
if( SDL_HasSSE( ) ) features |= CF_SSE;
if( SDL_HasSSE2( ) ) features |= CF_SSE2;
if( SDL_HasAltiVec( ) ) features |= CF_ALTIVEC;
#endif
return features;
}
/*
=================
Sys_Init
=================
*/
void Sys_Init(void)
{
Cmd_AddCommand( "in_restart", Sys_In_Restart_f );
Cvar_Set( "arch", OS_STRING " " ARCH_STRING );
Cvar_Set( "username", Sys_GetCurrentUser( ) );
}
/*
=================
Sys_AnsiColorPrint
Transform Q3 colour codes to ANSI escape sequences
=================
*/
void Sys_AnsiColorPrint( const char *msg )
{
static char buffer[ MAXPRINTMSG ];
int length = 0;
static int q3ToAnsi[ 8 ] =
{
30, // COLOR_BLACK
31, // COLOR_RED
32, // COLOR_GREEN
33, // COLOR_YELLOW
34, // COLOR_BLUE
36, // COLOR_CYAN
35, // COLOR_MAGENTA
0 // COLOR_WHITE
};
while( *msg )
{
if( Q_IsColorString( msg ) || *msg == '\n' )
{
// First empty the buffer
if( length > 0 )
{
buffer[ length ] = '\0';
fputs( buffer, stderr );
length = 0;
}
if( *msg == '\n' )
{
// Issue a reset and then the newline
fputs( "\033[0m\n", stderr );
msg++;
}
else
{
// Print the color code
Com_sprintf( buffer, sizeof( buffer ), "\033[%dm",
q3ToAnsi[ ColorIndex( *( msg + 1 ) ) ] );
fputs( buffer, stderr );
msg += 2;
}
}
else
{
if( length >= MAXPRINTMSG - 1 )
break;
buffer[ length ] = *msg;
length++;
msg++;
}
}
// Empty anything still left in the buffer
if( length > 0 )
{
buffer[ length ] = '\0';
fputs( buffer, stderr );
}
}
/*
=================
Sys_Print
=================
*/
void Sys_Print( const char *msg )
{
CON_LogWrite( msg );
CON_Print( msg );
}
/*
=================
Sys_Error
=================
*/
void Sys_Error( const char *error, ... )
{
va_list argptr;
char string[1024];
va_start (argptr,error);
Q_vsnprintf (string, sizeof(string), error, argptr);
va_end (argptr);
Sys_ErrorDialog( string );
Sys_Exit( 3 );
}
#if 0
/*
=================
Sys_Warn
=================
*/
static __attribute__ ((format (printf, 1, 2))) void Sys_Warn( char *warning, ... )
{
va_list argptr;
char string[1024];
va_start (argptr,warning);
Q_vsnprintf (string, sizeof(string), warning, argptr);
va_end (argptr);
CON_Print( va( "Warning: %s", string ) );
}
#endif
/*
============
Sys_FileTime
returns -1 if not present
============
*/
int Sys_FileTime( char *path )
{
struct stat buf;
if (stat (path,&buf) == -1)
return -1;
return buf.st_mtime;
}
/*
=================
Sys_UnloadDll
=================
*/
void Sys_UnloadDll( void *dllHandle )
{
if( !dllHandle )
{
Com_Printf("Sys_UnloadDll(NULL)\n");
return;
}
Sys_UnloadLibrary(dllHandle);
}
/*
=================
Sys_LoadDll
First try to load library name from system library path,
from executable path, then fs_basepath.
=================
*/
void *Sys_LoadDll(const char *name, qboolean useSystemLib)
{
void *dllhandle;
// Don't load any DLLs that end with the pk3 extension
if (COM_CompareExtension(name, ".pk3"))
{
Com_Printf("Rejecting DLL named \"%s\"", name);
return NULL;
}
if(useSystemLib)
Com_Printf("Trying to load \"%s\"...\n", name);
if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name)))
{
const char *topDir;
char libPath[MAX_OSPATH];
topDir = Sys_BinaryPath();
if(!*topDir)
topDir = ".";
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name);
if(!(dllhandle = Sys_LoadLibrary(libPath)))
{
const char *basePath = Cvar_VariableString("fs_basepath");
if(!basePath || !*basePath)
basePath = ".";
if(FS_FilenameCompare(topDir, basePath))
{
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name);
dllhandle = Sys_LoadLibrary(libPath);
}
if(!dllhandle)
Com_Printf("Loading \"%s\" failed\n", name);
}
}
return dllhandle;
}
/*
=================
Sys_LoadGameDll
Used to load a development dll instead of a virtual machine
=================
*/
void *Sys_LoadGameDll(const char *name,
intptr_t (QDECL **entryPoint)(intptr_t, ...),
intptr_t (*systemcalls)(intptr_t, ...))
{
void *libHandle;
void (*dllEntry)(intptr_t (*syscallptr)(intptr_t, ...));
assert(name);
Com_Printf( "Loading DLL file: %s\n", name);
libHandle = Sys_LoadLibrary(name);
if(!libHandle)
{
Com_Printf("Sys_LoadGameDll(%s) failed:\n\"%s\"\n", name, Sys_LibraryError());
return NULL;
}
dllEntry = Sys_LoadFunction( libHandle, "dllEntry" );
*entryPoint = Sys_LoadFunction( libHandle, "vmMain" );
if ( !*entryPoint || !dllEntry )
{
Com_Printf ( "Sys_LoadGameDll(%s) failed to find vmMain function:\n\"%s\" !\n", name, Sys_LibraryError( ) );
Sys_UnloadLibrary(libHandle);
return NULL;
}
Com_Printf ( "Sys_LoadGameDll(%s) found vmMain function at %p\n", name, *entryPoint );
dllEntry( systemcalls );
return libHandle;
}
/*
=================
Sys_ParseArgs
=================
*/
void Sys_ParseArgs( int argc, char **argv )
{
if( argc == 2 )
{
if( !strcmp( argv[1], "--version" ) ||
!strcmp( argv[1], "-v" ) )
{
const char* date = PRODUCT_DATE;
#ifdef DEDICATED
fprintf( stdout, Q3_VERSION " dedicated server (%s)\n", date );
#else
fprintf( stdout, Q3_VERSION " client (%s)\n", date );
#endif
Sys_Exit( 0 );
}
}
}
#ifndef DEFAULT_BASEDIR
# ifdef __APPLE__
# define DEFAULT_BASEDIR Sys_StripAppBundle(Sys_BinaryPath())
# else
# define DEFAULT_BASEDIR Sys_BinaryPath()
# endif
#endif
/*
=================
Sys_SigHandler
=================
*/
void Sys_SigHandler( int signal )
{
static qboolean signalcaught = qfalse;
if( signalcaught )
{
fprintf( stderr, "DOUBLE SIGNAL FAULT: Received signal %d, exiting...\n",
signal );
}
else
{
signalcaught = qtrue;
VM_Forced_Unload_Start();
#ifndef DEDICATED
CL_Shutdown(va("Received signal %d", signal), qtrue, qtrue);
#endif
SV_Shutdown(va("Received signal %d", signal) );
VM_Forced_Unload_Done();
}
if( signal == SIGTERM || signal == SIGINT )
Sys_Exit( 1 );
else
Sys_Exit( 2 );
}
/*
=================
main
=================
*/
int main( int argc, char **argv )
{
int i;
char commandLine[ MAX_STRING_CHARS ] = { 0 };
#ifndef DEDICATED
// SDL version check
// Compile time
# if !SDL_VERSION_ATLEAST(MINSDL_MAJOR,MINSDL_MINOR,MINSDL_PATCH)
# error A more recent version of SDL is required
# endif
// Run time
SDL_version ver;
SDL_GetVersion( &ver );
#define MINSDL_VERSION \
XSTRING(MINSDL_MAJOR) "." \
XSTRING(MINSDL_MINOR) "." \
XSTRING(MINSDL_PATCH)
if( SDL_VERSIONNUM( ver.major, ver.minor, ver.patch ) <
SDL_VERSIONNUM( MINSDL_MAJOR, MINSDL_MINOR, MINSDL_PATCH ) )
{
Sys_Dialog( DT_ERROR, va( "SDL version " MINSDL_VERSION " or greater is required, "
"but only version %d.%d.%d was found. You may be able to obtain a more recent copy "
"from http://www.libsdl.org/.", ver.major, ver.minor, ver.patch ), "SDL Library Too Old" );
Sys_Exit( 1 );
}
#endif
Sys_PlatformInit( );
// Set the initial time base
Sys_Milliseconds( );
#ifdef __APPLE__
// This is passed if we are launched by double-clicking
if ( argc >= 2 && Q_strncmp ( argv[1], "-psn", 4 ) == 0 )
argc = 1;
#endif
Sys_ParseArgs( argc, argv );
Sys_SetBinaryPath( Sys_Dirname( argv[ 0 ] ) );
Sys_SetDefaultInstallPath( DEFAULT_BASEDIR );
// Concatenate the command line for passing to Com_Init
for( i = 1; i < argc; i++ )
{
const qboolean containsSpaces = strchr(argv[i], ' ') != NULL;
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), argv[ i ] );
if (containsSpaces)
Q_strcat( commandLine, sizeof( commandLine ), "\"" );
Q_strcat( commandLine, sizeof( commandLine ), " " );
}
Com_Init( commandLine );
NET_Init( );
CON_Init( );
signal( SIGILL, Sys_SigHandler );
signal( SIGFPE, Sys_SigHandler );
signal( SIGSEGV, Sys_SigHandler );
signal( SIGTERM, Sys_SigHandler );
signal( SIGINT, Sys_SigHandler );
while( 1 )
{
IN_Frame( );
Com_Frame( );
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3233_2 |
crossvul-cpp_data_good_2473_0 | /* bubblewrap
* Copyright (C) 2016 Alexander Larsson
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include <poll.h>
#include <sched.h>
#include <pwd.h>
#include <grp.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/eventfd.h>
#include <sys/fsuid.h>
#include <sys/signalfd.h>
#include <sys/capability.h>
#include <sys/prctl.h>
#include <linux/sched.h>
#include <linux/seccomp.h>
#include <linux/filter.h>
#include "utils.h"
#include "network.h"
#include "bind-mount.h"
#ifndef CLONE_NEWCGROUP
#define CLONE_NEWCGROUP 0x02000000 /* New cgroup namespace */
#endif
#ifndef TEMP_FAILURE_RETRY
#define TEMP_FAILURE_RETRY(expression) \
(__extension__ \
({ long int __result; \
do __result = (long int) (expression); \
while (__result == -1L && errno == EINTR); \
__result; }))
#endif
/* Globals to avoid having to use getuid(), since the uid/gid changes during runtime */
static uid_t real_uid;
static gid_t real_gid;
static uid_t overflow_uid;
static gid_t overflow_gid;
static bool is_privileged; /* See acquire_privs() */
static const char *argv0;
static const char *host_tty_dev;
static int proc_fd = -1;
static const char *opt_exec_label = NULL;
static const char *opt_file_label = NULL;
static bool opt_as_pid_1;
const char *opt_chdir_path = NULL;
bool opt_unshare_user = FALSE;
bool opt_unshare_user_try = FALSE;
bool opt_unshare_pid = FALSE;
bool opt_unshare_ipc = FALSE;
bool opt_unshare_net = FALSE;
bool opt_unshare_uts = FALSE;
bool opt_unshare_cgroup = FALSE;
bool opt_unshare_cgroup_try = FALSE;
bool opt_needs_devpts = FALSE;
bool opt_new_session = FALSE;
bool opt_die_with_parent = FALSE;
uid_t opt_sandbox_uid = -1;
gid_t opt_sandbox_gid = -1;
int opt_sync_fd = -1;
int opt_block_fd = -1;
int opt_userns_block_fd = -1;
int opt_info_fd = -1;
int opt_json_status_fd = -1;
int opt_seccomp_fd = -1;
const char *opt_sandbox_hostname = NULL;
char *opt_args_data = NULL; /* owned */
int opt_userns_fd = -1;
int opt_userns2_fd = -1;
int opt_pidns_fd = -1;
#define CAP_TO_MASK_0(x) (1L << ((x) & 31))
#define CAP_TO_MASK_1(x) CAP_TO_MASK_0(x - 32)
typedef struct _NsInfo NsInfo;
struct _NsInfo {
const char *name;
bool *do_unshare;
ino_t id;
};
static NsInfo ns_infos[] = {
{"cgroup", &opt_unshare_cgroup, 0},
{"ipc", &opt_unshare_ipc, 0},
{"mnt", NULL, 0},
{"net", &opt_unshare_net, 0},
{"pid", &opt_unshare_pid, 0},
/* user namespace info omitted because it
* is not (yet) valid when we obtain the
* namespace info (get un-shared later) */
{"uts", &opt_unshare_uts, 0},
{NULL, NULL, 0}
};
typedef enum {
SETUP_BIND_MOUNT,
SETUP_RO_BIND_MOUNT,
SETUP_DEV_BIND_MOUNT,
SETUP_MOUNT_PROC,
SETUP_MOUNT_DEV,
SETUP_MOUNT_TMPFS,
SETUP_MOUNT_MQUEUE,
SETUP_MAKE_DIR,
SETUP_MAKE_FILE,
SETUP_MAKE_BIND_FILE,
SETUP_MAKE_RO_BIND_FILE,
SETUP_MAKE_SYMLINK,
SETUP_REMOUNT_RO_NO_RECURSIVE,
SETUP_SET_HOSTNAME,
} SetupOpType;
typedef enum {
NO_CREATE_DEST = (1 << 0),
ALLOW_NOTEXIST = (2 << 0),
} SetupOpFlag;
typedef struct _SetupOp SetupOp;
struct _SetupOp
{
SetupOpType type;
const char *source;
const char *dest;
int fd;
SetupOpFlag flags;
SetupOp *next;
};
typedef struct _LockFile LockFile;
struct _LockFile
{
const char *path;
int fd;
LockFile *next;
};
static SetupOp *ops = NULL;
static SetupOp *last_op = NULL;
static LockFile *lock_files = NULL;
static LockFile *last_lock_file = NULL;
enum {
PRIV_SEP_OP_DONE,
PRIV_SEP_OP_BIND_MOUNT,
PRIV_SEP_OP_PROC_MOUNT,
PRIV_SEP_OP_TMPFS_MOUNT,
PRIV_SEP_OP_DEVPTS_MOUNT,
PRIV_SEP_OP_MQUEUE_MOUNT,
PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE,
PRIV_SEP_OP_SET_HOSTNAME,
};
typedef struct
{
uint32_t op;
uint32_t flags;
uint32_t arg1_offset;
uint32_t arg2_offset;
} PrivSepOp;
static SetupOp *
setup_op_new (SetupOpType type)
{
SetupOp *op = xcalloc (sizeof (SetupOp));
op->type = type;
op->fd = -1;
op->flags = 0;
if (last_op != NULL)
last_op->next = op;
else
ops = op;
last_op = op;
return op;
}
static LockFile *
lock_file_new (const char *path)
{
LockFile *lock = xcalloc (sizeof (LockFile));
lock->path = path;
if (last_lock_file != NULL)
last_lock_file->next = lock;
else
lock_files = lock;
last_lock_file = lock;
return lock;
}
static void
usage (int ecode, FILE *out)
{
fprintf (out, "usage: %s [OPTIONS...] [--] COMMAND [ARGS...]\n\n", argv0);
fprintf (out,
" --help Print this help\n"
" --version Print version\n"
" --args FD Parse NUL-separated args from FD\n"
" --unshare-all Unshare every namespace we support by default\n"
" --share-net Retain the network namespace (can only combine with --unshare-all)\n"
" --unshare-user Create new user namespace (may be automatically implied if not setuid)\n"
" --unshare-user-try Create new user namespace if possible else continue by skipping it\n"
" --unshare-ipc Create new ipc namespace\n"
" --unshare-pid Create new pid namespace\n"
" --unshare-net Create new network namespace\n"
" --unshare-uts Create new uts namespace\n"
" --unshare-cgroup Create new cgroup namespace\n"
" --unshare-cgroup-try Create new cgroup namespace if possible else continue by skipping it\n"
" --userns FD Use this user namespace (cannot combine with --unshare-user)\n"
" --userns2 FD After setup switch to this user namspace, only useful with --userns\n"
" --pidns FD Use this user namespace (as parent namespace if using --unshare-pid)\n"
" --uid UID Custom uid in the sandbox (requires --unshare-user or --userns)\n"
" --gid GID Custom gid in the sandbox (requires --unshare-user or --userns)\n"
" --hostname NAME Custom hostname in the sandbox (requires --unshare-uts)\n"
" --chdir DIR Change directory to DIR\n"
" --setenv VAR VALUE Set an environment variable\n"
" --unsetenv VAR Unset an environment variable\n"
" --lock-file DEST Take a lock on DEST while sandbox is running\n"
" --sync-fd FD Keep this fd open while sandbox is running\n"
" --bind SRC DEST Bind mount the host path SRC on DEST\n"
" --bind-try SRC DEST Equal to --bind but ignores non-existent SRC\n"
" --dev-bind SRC DEST Bind mount the host path SRC on DEST, allowing device access\n"
" --dev-bind-try SRC DEST Equal to --dev-bind but ignores non-existent SRC\n"
" --ro-bind SRC DEST Bind mount the host path SRC readonly on DEST\n"
" --ro-bind-try SRC DEST Equal to --ro-bind but ignores non-existent SRC\n"
" --remount-ro DEST Remount DEST as readonly; does not recursively remount\n"
" --exec-label LABEL Exec label for the sandbox\n"
" --file-label LABEL File label for temporary sandbox content\n"
" --proc DEST Mount new procfs on DEST\n"
" --dev DEST Mount new dev on DEST\n"
" --tmpfs DEST Mount new tmpfs on DEST\n"
" --mqueue DEST Mount new mqueue on DEST\n"
" --dir DEST Create dir at DEST\n"
" --file FD DEST Copy from FD to destination DEST\n"
" --bind-data FD DEST Copy from FD to file which is bind-mounted on DEST\n"
" --ro-bind-data FD DEST Copy from FD to file which is readonly bind-mounted on DEST\n"
" --symlink SRC DEST Create symlink at DEST with target SRC\n"
" --seccomp FD Load and use seccomp rules from FD\n"
" --block-fd FD Block on FD until some data to read is available\n"
" --userns-block-fd FD Block on FD until the user namespace is ready\n"
" --info-fd FD Write information about the running container to FD\n"
" --json-status-fd FD Write container status to FD as multiple JSON documents\n"
" --new-session Create a new terminal session\n"
" --die-with-parent Kills with SIGKILL child process (COMMAND) when bwrap or bwrap's parent dies.\n"
" --as-pid-1 Do not install a reaper process with PID=1\n"
" --cap-add CAP Add cap CAP when running as privileged user\n"
" --cap-drop CAP Drop cap CAP when running as privileged user\n"
);
exit (ecode);
}
/* If --die-with-parent was specified, use PDEATHSIG to ensure SIGKILL
* is sent to the current process when our parent dies.
*/
static void
handle_die_with_parent (void)
{
if (opt_die_with_parent && prctl (PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0) != 0)
die_with_error ("prctl");
}
static void
block_sigchild (void)
{
sigset_t mask;
int status;
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
if (sigprocmask (SIG_BLOCK, &mask, NULL) == -1)
die_with_error ("sigprocmask");
/* Reap any outstanding zombies that we may have inherited */
while (waitpid (-1, &status, WNOHANG) > 0)
;
}
static void
unblock_sigchild (void)
{
sigset_t mask;
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
if (sigprocmask (SIG_UNBLOCK, &mask, NULL) == -1)
die_with_error ("sigprocmask");
}
/* Closes all fd:s except 0,1,2 and the passed in array of extra fds */
static int
close_extra_fds (void *data, int fd)
{
int *extra_fds = (int *) data;
int i;
for (i = 0; extra_fds[i] != -1; i++)
if (fd == extra_fds[i])
return 0;
if (fd <= 2)
return 0;
close (fd);
return 0;
}
static int
propagate_exit_status (int status)
{
if (WIFEXITED (status))
return WEXITSTATUS (status);
/* The process died of a signal, we can't really report that, but we
* can at least be bash-compatible. The bash manpage says:
* The return value of a simple command is its
* exit status, or 128+n if the command is
* terminated by signal n.
*/
if (WIFSIGNALED (status))
return 128 + WTERMSIG (status);
/* Weird? */
return 255;
}
static void
dump_info (int fd, const char *output, bool exit_on_error)
{
size_t len = strlen (output);
if (write_to_fd (fd, output, len))
{
if (exit_on_error)
die_with_error ("Write to info_fd");
}
}
static void
report_child_exit_status (int exitc, int setup_finished_fd)
{
ssize_t s;
char data[2];
cleanup_free char *output = NULL;
if (opt_json_status_fd == -1 || setup_finished_fd == -1)
return;
s = TEMP_FAILURE_RETRY (read (setup_finished_fd, data, sizeof data));
if (s == -1 && errno != EAGAIN)
die_with_error ("read eventfd");
if (s != 1) // Is 0 if pipe closed before exec, is 2 if closed after exec.
return;
output = xasprintf ("{ \"exit-code\": %i }\n", exitc);
dump_info (opt_json_status_fd, output, FALSE);
close (opt_json_status_fd);
opt_json_status_fd = -1;
close (setup_finished_fd);
}
/* This stays around for as long as the initial process in the app does
* and when that exits it exits, propagating the exit status. We do this
* by having pid 1 in the sandbox detect this exit and tell the monitor
* the exit status via a eventfd. We also track the exit of the sandbox
* pid 1 via a signalfd for SIGCHLD, and exit with an error in this case.
* This is to catch e.g. problems during setup. */
static int
monitor_child (int event_fd, pid_t child_pid, int setup_finished_fd)
{
int res;
uint64_t val;
ssize_t s;
int signal_fd;
sigset_t mask;
struct pollfd fds[2];
int num_fds;
struct signalfd_siginfo fdsi;
int dont_close[] = {-1, -1, -1, -1};
int j = 0;
int exitc;
pid_t died_pid;
int died_status;
/* Close all extra fds in the monitoring process.
Any passed in fds have been passed on to the child anyway. */
if (event_fd != -1)
dont_close[j++] = event_fd;
if (opt_json_status_fd != -1)
dont_close[j++] = opt_json_status_fd;
if (setup_finished_fd != -1)
dont_close[j++] = setup_finished_fd;
assert (j < sizeof(dont_close)/sizeof(*dont_close));
fdwalk (proc_fd, close_extra_fds, dont_close);
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
signal_fd = signalfd (-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK);
if (signal_fd == -1)
die_with_error ("Can't create signalfd");
num_fds = 1;
fds[0].fd = signal_fd;
fds[0].events = POLLIN;
if (event_fd != -1)
{
fds[1].fd = event_fd;
fds[1].events = POLLIN;
num_fds++;
}
while (1)
{
fds[0].revents = fds[1].revents = 0;
res = poll (fds, num_fds, -1);
if (res == -1 && errno != EINTR)
die_with_error ("poll");
/* Always read from the eventfd first, if pid 2 died then pid 1 often
* dies too, and we could race, reporting that first and we'd lose
* the real exit status. */
if (event_fd != -1)
{
s = read (event_fd, &val, 8);
if (s == -1 && errno != EINTR && errno != EAGAIN)
die_with_error ("read eventfd");
else if (s == 8)
{
exitc = (int) val - 1;
report_child_exit_status (exitc, setup_finished_fd);
return exitc;
}
}
/* We need to read the signal_fd, or it will keep polling as read,
* however we ignore the details as we get them from waitpid
* below anyway */
s = read (signal_fd, &fdsi, sizeof (struct signalfd_siginfo));
if (s == -1 && errno != EINTR && errno != EAGAIN)
die_with_error ("read signalfd");
/* We may actually get several sigchld compressed into one
SIGCHLD, so we have to handle all of them. */
while ((died_pid = waitpid (-1, &died_status, WNOHANG)) > 0)
{
/* We may be getting sigchild from other children too. For instance if
someone created a child process, and then exec:ed bubblewrap. Ignore them */
if (died_pid == child_pid)
{
exitc = propagate_exit_status (died_status);
report_child_exit_status (exitc, setup_finished_fd);
return exitc;
}
}
}
die ("Should not be reached");
return 0;
}
/* This is pid 1 in the app sandbox. It is needed because we're using
* pid namespaces, and someone has to reap zombies in it. We also detect
* when the initial process (pid 2) dies and report its exit status to
* the monitor so that it can return it to the original spawner.
*
* When there are no other processes in the sandbox the wait will return
* ECHILD, and we then exit pid 1 to clean up the sandbox. */
static int
do_init (int event_fd, pid_t initial_pid, struct sock_fprog *seccomp_prog)
{
int initial_exit_status = 1;
LockFile *lock;
for (lock = lock_files; lock != NULL; lock = lock->next)
{
int fd = open (lock->path, O_RDONLY | O_CLOEXEC);
if (fd == -1)
die_with_error ("Unable to open lock file %s", lock->path);
struct flock l = {
.l_type = F_RDLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0
};
if (fcntl (fd, F_SETLK, &l) < 0)
die_with_error ("Unable to lock file %s", lock->path);
/* Keep fd open to hang on to lock */
lock->fd = fd;
}
/* Optionally bind our lifecycle to that of the caller */
handle_die_with_parent ();
if (seccomp_prog != NULL &&
prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, seccomp_prog) != 0)
die_with_error ("prctl(PR_SET_SECCOMP)");
while (TRUE)
{
pid_t child;
int status;
child = wait (&status);
if (child == initial_pid)
{
initial_exit_status = propagate_exit_status (status);
if(event_fd != -1)
{
uint64_t val;
int res UNUSED;
val = initial_exit_status + 1;
res = write (event_fd, &val, 8);
/* Ignore res, if e.g. the parent died and closed event_fd
we don't want to error out here */
}
}
if (child == -1 && errno != EINTR)
{
if (errno != ECHILD)
die_with_error ("init wait()");
break;
}
}
/* Close FDs. */
for (lock = lock_files; lock != NULL; lock = lock->next)
{
if (lock->fd >= 0)
{
close (lock->fd);
lock->fd = -1;
}
}
return initial_exit_status;
}
#define CAP_TO_MASK_0(x) (1L << ((x) & 31))
#define CAP_TO_MASK_1(x) CAP_TO_MASK_0(x - 32)
/* Set if --cap-add or --cap-drop were used */
static bool opt_cap_add_or_drop_used;
/* The capability set we'll target, used if above is true */
static uint32_t requested_caps[2] = {0, 0};
/* low 32bit caps needed */
/* CAP_SYS_PTRACE is needed to dereference the symlinks in /proc/<pid>/ns/, see namespaces(7) */
#define REQUIRED_CAPS_0 (CAP_TO_MASK_0 (CAP_SYS_ADMIN) | CAP_TO_MASK_0 (CAP_SYS_CHROOT) | CAP_TO_MASK_0 (CAP_NET_ADMIN) | CAP_TO_MASK_0 (CAP_SETUID) | CAP_TO_MASK_0 (CAP_SETGID) | CAP_TO_MASK_0 (CAP_SYS_PTRACE))
/* high 32bit caps needed */
#define REQUIRED_CAPS_1 0
static void
set_required_caps (void)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
/* Drop all non-require capabilities */
data[0].effective = REQUIRED_CAPS_0;
data[0].permitted = REQUIRED_CAPS_0;
data[0].inheritable = 0;
data[1].effective = REQUIRED_CAPS_1;
data[1].permitted = REQUIRED_CAPS_1;
data[1].inheritable = 0;
if (capset (&hdr, data) < 0)
die_with_error ("capset failed");
}
static void
drop_all_caps (bool keep_requested_caps)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (keep_requested_caps)
{
/* Avoid calling capset() unless we need to; currently
* systemd-nspawn at least is known to install a seccomp
* policy denying capset() for dubious reasons.
* <https://github.com/projectatomic/bubblewrap/pull/122>
*/
if (!opt_cap_add_or_drop_used && real_uid == 0)
{
assert (!is_privileged);
return;
}
data[0].effective = requested_caps[0];
data[0].permitted = requested_caps[0];
data[0].inheritable = requested_caps[0];
data[1].effective = requested_caps[1];
data[1].permitted = requested_caps[1];
data[1].inheritable = requested_caps[1];
}
if (capset (&hdr, data) < 0)
{
/* While the above logic ensures we don't call capset() for the primary
* process unless configured to do so, we still try to drop privileges for
* the init process unconditionally. Since due to the systemd seccomp
* filter that will fail, let's just ignore it.
*/
if (errno == EPERM && real_uid == 0 && !is_privileged)
return;
else
die_with_error ("capset failed");
}
}
static bool
has_caps (void)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (capget (&hdr, data) < 0)
die_with_error ("capget failed");
return data[0].permitted != 0 || data[1].permitted != 0;
}
/* Most of the code here is used both to add caps to the ambient capabilities
* and drop caps from the bounding set. Handle both cases here and add
* drop_cap_bounding_set/set_ambient_capabilities wrappers to facilitate its usage.
*/
static void
prctl_caps (uint32_t *caps, bool do_cap_bounding, bool do_set_ambient)
{
unsigned long cap;
/* We ignore both EINVAL and EPERM, as we are actually relying
* on PR_SET_NO_NEW_PRIVS to ensure the right capabilities are
* available. EPERM in particular can happen with old, buggy
* kernels. See:
* https://github.com/projectatomic/bubblewrap/pull/175#issuecomment-278051373
* https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/security/commoncap.c?id=160da84dbb39443fdade7151bc63a88f8e953077
*/
for (cap = 0; cap <= CAP_LAST_CAP; cap++)
{
bool keep = FALSE;
if (cap < 32)
{
if (CAP_TO_MASK_0 (cap) & caps[0])
keep = TRUE;
}
else
{
if (CAP_TO_MASK_1 (cap) & caps[1])
keep = TRUE;
}
if (keep && do_set_ambient)
{
#ifdef PR_CAP_AMBIENT
int res = prctl (PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, cap, 0, 0);
if (res == -1 && !(errno == EINVAL || errno == EPERM))
die_with_error ("Adding ambient capability %ld", cap);
#else
/* We ignore the EINVAL that results from not having PR_CAP_AMBIENT
* in the current kernel at runtime, so also ignore not having it
* in the current kernel headers at compile-time */
#endif
}
if (!keep && do_cap_bounding)
{
int res = prctl (PR_CAPBSET_DROP, cap, 0, 0, 0);
if (res == -1 && !(errno == EINVAL || errno == EPERM))
die_with_error ("Dropping capability %ld from bounds", cap);
}
}
}
static void
drop_cap_bounding_set (bool drop_all)
{
if (!drop_all)
prctl_caps (requested_caps, TRUE, FALSE);
else
{
uint32_t no_caps[2] = {0, 0};
prctl_caps (no_caps, TRUE, FALSE);
}
}
static void
set_ambient_capabilities (void)
{
if (is_privileged)
return;
prctl_caps (requested_caps, FALSE, TRUE);
}
/* This acquires the privileges that the bwrap will need it to work.
* If bwrap is not setuid, then this does nothing, and it relies on
* unprivileged user namespaces to be used. This case is
* "is_privileged = FALSE".
*
* If bwrap is setuid, then we do things in phases.
* The first part is run as euid 0, but with fsuid as the real user.
* The second part, inside the child, is run as the real user but with
* capabilities.
* And finally we drop all capabilities.
* The reason for the above dance is to avoid having the setup phase
* being able to read files the user can't, while at the same time
* working around various kernel issues. See below for details.
*/
static void
acquire_privs (void)
{
uid_t euid, new_fsuid;
euid = geteuid ();
/* Are we setuid ? */
if (real_uid != euid)
{
if (euid != 0)
die ("Unexpected setuid user %d, should be 0", euid);
is_privileged = TRUE;
/* We want to keep running as euid=0 until at the clone()
* operation because doing so will make the user namespace be
* owned by root, which makes it not ptrace:able by the user as
* it otherwise would be. After that we will run fully as the
* user, which is necessary e.g. to be able to read from a fuse
* mount from the user.
*
* However, we don't want to accidentally mis-use euid=0 for
* escalated filesystem access before the clone(), so we set
* fsuid to the uid.
*/
if (setfsuid (real_uid) < 0)
die_with_error ("Unable to set fsuid");
/* setfsuid can't properly report errors, check that it worked (as per manpage) */
new_fsuid = setfsuid (-1);
if (new_fsuid != real_uid)
die ("Unable to set fsuid (was %d)", (int)new_fsuid);
/* We never need capabilities after execve(), so lets drop everything from the bounding set */
drop_cap_bounding_set (TRUE);
/* Keep only the required capabilities for setup */
set_required_caps ();
}
else if (real_uid != 0 && has_caps ())
{
/* We have some capabilities in the non-setuid case, which should not happen.
Probably caused by the binary being setcap instead of setuid which we
don't support anymore */
die ("Unexpected capabilities but not setuid, old file caps config?");
}
else if (real_uid == 0)
{
/* If our uid is 0, default to inheriting all caps; the caller
* can drop them via --cap-drop. This is used by at least rpm-ostree.
* Note this needs to happen before the argument parsing of --cap-drop.
*/
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (capget (&hdr, data) < 0)
die_with_error ("capget (for uid == 0) failed");
requested_caps[0] = data[0].effective;
requested_caps[1] = data[1].effective;
}
/* Else, we try unprivileged user namespaces */
}
/* This is called once we're inside the namespace */
static void
switch_to_user_with_privs (void)
{
/* If we're in a new user namespace, we got back the bounding set, clear it again */
if (opt_unshare_user || opt_userns_fd != -1)
drop_cap_bounding_set (FALSE);
/* If we switched to a new user namespace it may allow other uids/gids, so switch to the target one */
if (opt_userns_fd != -1)
{
if (opt_sandbox_uid != real_uid && setuid (opt_sandbox_uid) < 0)
die_with_error ("unable to switch to uid %d", opt_sandbox_uid);
if (opt_sandbox_gid != real_gid && setgid (opt_sandbox_gid) < 0)
die_with_error ("unable to switch to gid %d", opt_sandbox_gid);
}
if (!is_privileged)
return;
/* Tell kernel not clear capabilities when later dropping root uid */
if (prctl (PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0)
die_with_error ("prctl(PR_SET_KEEPCAPS) failed");
if (setuid (opt_sandbox_uid) < 0)
die_with_error ("unable to drop root uid");
/* Regain effective required capabilities from permitted */
set_required_caps ();
}
/* Call setuid() and use capset() to adjust capabilities */
static void
drop_privs (bool keep_requested_caps,
bool already_changed_uid)
{
assert (!keep_requested_caps || !is_privileged);
/* Drop root uid */
if (is_privileged && !already_changed_uid &&
setuid (opt_sandbox_uid) < 0)
die_with_error ("unable to drop root uid");
drop_all_caps (keep_requested_caps);
/* We don't have any privs now, so mark us dumpable which makes /proc/self be owned by the user instead of root */
if (prctl (PR_SET_DUMPABLE, 1, 0, 0, 0) != 0)
die_with_error ("can't set dumpable");
}
static char *
get_newroot_path (const char *path)
{
while (*path == '/')
path++;
return strconcat ("/newroot/", path);
}
static char *
get_oldroot_path (const char *path)
{
while (*path == '/')
path++;
return strconcat ("/oldroot/", path);
}
static void
write_uid_gid_map (uid_t sandbox_uid,
uid_t parent_uid,
uid_t sandbox_gid,
uid_t parent_gid,
pid_t pid,
bool deny_groups,
bool map_root)
{
cleanup_free char *uid_map = NULL;
cleanup_free char *gid_map = NULL;
cleanup_free char *dir = NULL;
cleanup_fd int dir_fd = -1;
uid_t old_fsuid = -1;
if (pid == -1)
dir = xstrdup ("self");
else
dir = xasprintf ("%d", pid);
dir_fd = openat (proc_fd, dir, O_PATH);
if (dir_fd < 0)
die_with_error ("open /proc/%s failed", dir);
if (map_root && parent_uid != 0 && sandbox_uid != 0)
uid_map = xasprintf ("0 %d 1\n"
"%d %d 1\n", overflow_uid, sandbox_uid, parent_uid);
else
uid_map = xasprintf ("%d %d 1\n", sandbox_uid, parent_uid);
if (map_root && parent_gid != 0 && sandbox_gid != 0)
gid_map = xasprintf ("0 %d 1\n"
"%d %d 1\n", overflow_gid, sandbox_gid, parent_gid);
else
gid_map = xasprintf ("%d %d 1\n", sandbox_gid, parent_gid);
/* We have to be root to be allowed to write to the uid map
* for setuid apps, so temporary set fsuid to 0 */
if (is_privileged)
old_fsuid = setfsuid (0);
if (write_file_at (dir_fd, "uid_map", uid_map) != 0)
die_with_error ("setting up uid map");
if (deny_groups &&
write_file_at (dir_fd, "setgroups", "deny\n") != 0)
{
/* If /proc/[pid]/setgroups does not exist, assume we are
* running a linux kernel < 3.19, i.e. we live with the
* vulnerability known as CVE-2014-8989 in older kernels
* where setgroups does not exist.
*/
if (errno != ENOENT)
die_with_error ("error writing to setgroups");
}
if (write_file_at (dir_fd, "gid_map", gid_map) != 0)
die_with_error ("setting up gid map");
if (is_privileged)
{
setfsuid (old_fsuid);
if (setfsuid (-1) != real_uid)
die ("Unable to re-set fsuid");
}
}
static void
privileged_op (int privileged_op_socket,
uint32_t op,
uint32_t flags,
const char *arg1,
const char *arg2)
{
if (privileged_op_socket != -1)
{
uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */
PrivSepOp *op_buffer = (PrivSepOp *) buffer;
size_t buffer_size = sizeof (PrivSepOp);
uint32_t arg1_offset = 0, arg2_offset = 0;
/* We're unprivileged, send this request to the privileged part */
if (arg1 != NULL)
{
arg1_offset = buffer_size;
buffer_size += strlen (arg1) + 1;
}
if (arg2 != NULL)
{
arg2_offset = buffer_size;
buffer_size += strlen (arg2) + 1;
}
if (buffer_size >= sizeof (buffer))
die ("privilege separation operation to large");
op_buffer->op = op;
op_buffer->flags = flags;
op_buffer->arg1_offset = arg1_offset;
op_buffer->arg2_offset = arg2_offset;
if (arg1 != NULL)
strcpy ((char *) buffer + arg1_offset, arg1);
if (arg2 != NULL)
strcpy ((char *) buffer + arg2_offset, arg2);
if (write (privileged_op_socket, buffer, buffer_size) != buffer_size)
die ("Can't write to privileged_op_socket");
if (read (privileged_op_socket, buffer, 1) != 1)
die ("Can't read from privileged_op_socket");
return;
}
/*
* This runs a privileged request for the unprivileged setup
* code. Note that since the setup code is unprivileged it is not as
* trusted, so we need to verify that all requests only affect the
* child namespace as set up by the privileged parts of the setup,
* and that all the code is very careful about handling input.
*
* This means:
* * Bind mounts are safe, since we always use filesystem namespace. They
* must be recursive though, as otherwise you can use a non-recursive bind
* mount to access an otherwise over-mounted mountpoint.
* * Mounting proc, tmpfs, mqueue, devpts in the child namespace is assumed to
* be safe.
* * Remounting RO (even non-recursive) is safe because it decreases privileges.
* * sethostname() is safe only if we set up a UTS namespace
*/
switch (op)
{
case PRIV_SEP_OP_DONE:
break;
case PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE:
if (bind_mount (proc_fd, NULL, arg2, BIND_READONLY) != 0)
die_with_error ("Can't remount readonly on %s", arg2);
break;
case PRIV_SEP_OP_BIND_MOUNT:
/* We always bind directories recursively, otherwise this would let us
access files that are otherwise covered on the host */
if (bind_mount (proc_fd, arg1, arg2, BIND_RECURSIVE | flags) != 0)
die_with_error ("Can't bind mount %s on %s", arg1, arg2);
break;
case PRIV_SEP_OP_PROC_MOUNT:
if (mount ("proc", arg1, "proc", MS_NOSUID | MS_NOEXEC | MS_NODEV, NULL) != 0)
die_with_error ("Can't mount proc on %s", arg1);
break;
case PRIV_SEP_OP_TMPFS_MOUNT:
{
cleanup_free char *opt = label_mount ("mode=0755", opt_file_label);
if (mount ("tmpfs", arg1, "tmpfs", MS_NOSUID | MS_NODEV, opt) != 0)
die_with_error ("Can't mount tmpfs on %s", arg1);
break;
}
case PRIV_SEP_OP_DEVPTS_MOUNT:
if (mount ("devpts", arg1, "devpts", MS_NOSUID | MS_NOEXEC,
"newinstance,ptmxmode=0666,mode=620") != 0)
die_with_error ("Can't mount devpts on %s", arg1);
break;
case PRIV_SEP_OP_MQUEUE_MOUNT:
if (mount ("mqueue", arg1, "mqueue", 0, NULL) != 0)
die_with_error ("Can't mount mqueue on %s", arg1);
break;
case PRIV_SEP_OP_SET_HOSTNAME:
/* This is checked at the start, but lets verify it here in case
something manages to send hacked priv-sep operation requests. */
if (!opt_unshare_uts)
die ("Refusing to set hostname in original namespace");
if (sethostname (arg1, strlen(arg1)) != 0)
die_with_error ("Can't set hostname to %s", arg1);
break;
default:
die ("Unexpected privileged op %d", op);
}
}
/* This is run unprivileged in the child namespace but can request
* some privileged operations (also in the child namespace) via the
* privileged_op_socket.
*/
static void
setup_newroot (bool unshare_pid,
int privileged_op_socket)
{
SetupOp *op;
for (op = ops; op != NULL; op = op->next)
{
cleanup_free char *source = NULL;
cleanup_free char *dest = NULL;
int source_mode = 0;
int i;
if (op->source &&
op->type != SETUP_MAKE_SYMLINK)
{
source = get_oldroot_path (op->source);
source_mode = get_file_mode (source);
if (source_mode < 0)
{
if (op->flags & ALLOW_NOTEXIST && errno == ENOENT)
continue; /* Ignore and move on */
die_with_error("Can't get type of source %s", op->source);
}
}
if (op->dest &&
(op->flags & NO_CREATE_DEST) == 0)
{
dest = get_newroot_path (op->dest);
if (mkdir_with_parents (dest, 0755, FALSE) != 0)
die_with_error ("Can't mkdir parents for %s", op->dest);
}
switch (op->type)
{
case SETUP_RO_BIND_MOUNT:
case SETUP_DEV_BIND_MOUNT:
case SETUP_BIND_MOUNT:
if (source_mode == S_IFDIR)
{
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
}
else if (ensure_file (dest, 0666) != 0)
die_with_error ("Can't create file at %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT,
(op->type == SETUP_RO_BIND_MOUNT ? BIND_READONLY : 0) |
(op->type == SETUP_DEV_BIND_MOUNT ? BIND_DEVICES : 0),
source, dest);
break;
case SETUP_REMOUNT_RO_NO_RECURSIVE:
privileged_op (privileged_op_socket,
PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE, 0, NULL, dest);
break;
case SETUP_MOUNT_PROC:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
if (unshare_pid || opt_pidns_fd != -1)
{
/* Our own procfs */
privileged_op (privileged_op_socket,
PRIV_SEP_OP_PROC_MOUNT, 0,
dest, NULL);
}
else
{
/* Use system procfs, as we share pid namespace anyway */
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, 0,
"oldroot/proc", dest);
}
/* There are a bunch of weird old subdirs of /proc that could potentially be
problematic (for instance /proc/sysrq-trigger lets you shut down the machine
if you have write access). We should not have access to these as a non-privileged
user, but lets cover them anyway just to make sure */
const char *cover_proc_dirs[] = { "sys", "sysrq-trigger", "irq", "bus" };
for (i = 0; i < N_ELEMENTS (cover_proc_dirs); i++)
{
cleanup_free char *subdir = strconcat3 (dest, "/", cover_proc_dirs[i]);
if (access (subdir, W_OK) < 0)
{
/* The file is already read-only or doesn't exist. */
if (errno == EACCES || errno == ENOENT)
continue;
die_with_error ("Can't access %s", subdir);
}
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, BIND_READONLY,
subdir, subdir);
}
break;
case SETUP_MOUNT_DEV:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_TMPFS_MOUNT, 0,
dest, NULL);
static const char *const devnodes[] = { "null", "zero", "full", "random", "urandom", "tty" };
for (i = 0; i < N_ELEMENTS (devnodes); i++)
{
cleanup_free char *node_dest = strconcat3 (dest, "/", devnodes[i]);
cleanup_free char *node_src = strconcat ("/oldroot/dev/", devnodes[i]);
if (create_file (node_dest, 0666, NULL) != 0)
die_with_error ("Can't create file %s/%s", op->dest, devnodes[i]);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, BIND_DEVICES,
node_src, node_dest);
}
static const char *const stdionodes[] = { "stdin", "stdout", "stderr" };
for (i = 0; i < N_ELEMENTS (stdionodes); i++)
{
cleanup_free char *target = xasprintf ("/proc/self/fd/%d", i);
cleanup_free char *node_dest = strconcat3 (dest, "/", stdionodes[i]);
if (symlink (target, node_dest) < 0)
die_with_error ("Can't create symlink %s/%s", op->dest, stdionodes[i]);
}
/* /dev/fd and /dev/core - legacy, but both nspawn and docker do these */
{ cleanup_free char *dev_fd = strconcat (dest, "/fd");
if (symlink ("/proc/self/fd", dev_fd) < 0)
die_with_error ("Can't create symlink %s", dev_fd);
}
{ cleanup_free char *dev_core = strconcat (dest, "/core");
if (symlink ("/proc/kcore", dev_core) < 0)
die_with_error ("Can't create symlink %s", dev_core);
}
{
cleanup_free char *pts = strconcat (dest, "/pts");
cleanup_free char *ptmx = strconcat (dest, "/ptmx");
cleanup_free char *shm = strconcat (dest, "/shm");
if (mkdir (shm, 0755) == -1)
die_with_error ("Can't create %s/shm", op->dest);
if (mkdir (pts, 0755) == -1)
die_with_error ("Can't create %s/devpts", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_DEVPTS_MOUNT, 0, pts, NULL);
if (symlink ("pts/ptmx", ptmx) != 0)
die_with_error ("Can't make symlink at %s/ptmx", op->dest);
}
/* If stdout is a tty, that means the sandbox can write to the
outside-sandbox tty. In that case we also create a /dev/console
that points to this tty device. This should not cause any more
access than we already have, and it makes ttyname() work in the
sandbox. */
if (host_tty_dev != NULL && *host_tty_dev != 0)
{
cleanup_free char *src_tty_dev = strconcat ("/oldroot", host_tty_dev);
cleanup_free char *dest_console = strconcat (dest, "/console");
if (create_file (dest_console, 0666, NULL) != 0)
die_with_error ("creating %s/console", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, BIND_DEVICES,
src_tty_dev, dest_console);
}
break;
case SETUP_MOUNT_TMPFS:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_TMPFS_MOUNT, 0,
dest, NULL);
break;
case SETUP_MOUNT_MQUEUE:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_MQUEUE_MOUNT, 0,
dest, NULL);
break;
case SETUP_MAKE_DIR:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
break;
case SETUP_MAKE_FILE:
{
cleanup_fd int dest_fd = -1;
dest_fd = creat (dest, 0666);
if (dest_fd == -1)
die_with_error ("Can't create file %s", op->dest);
if (copy_file_data (op->fd, dest_fd) != 0)
die_with_error ("Can't write data to file %s", op->dest);
close (op->fd);
op->fd = -1;
}
break;
case SETUP_MAKE_BIND_FILE:
case SETUP_MAKE_RO_BIND_FILE:
{
cleanup_fd int dest_fd = -1;
char tempfile[] = "/bindfileXXXXXX";
dest_fd = mkstemp (tempfile);
if (dest_fd == -1)
die_with_error ("Can't create tmpfile for %s", op->dest);
if (copy_file_data (op->fd, dest_fd) != 0)
die_with_error ("Can't write data to file %s", op->dest);
close (op->fd);
op->fd = -1;
assert (dest != NULL);
if (ensure_file (dest, 0666) != 0)
die_with_error ("Can't create file at %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT,
(op->type == SETUP_MAKE_RO_BIND_FILE ? BIND_READONLY : 0),
tempfile, dest);
/* Remove the file so we're sure the app can't get to it in any other way.
Its outside the container chroot, so it shouldn't be possible, but lets
make it really sure. */
unlink (tempfile);
}
break;
case SETUP_MAKE_SYMLINK:
assert (op->source != NULL); /* guaranteed by the constructor */
if (symlink (op->source, dest) != 0)
die_with_error ("Can't make symlink at %s", op->dest);
break;
case SETUP_SET_HOSTNAME:
assert (op->dest != NULL); /* guaranteed by the constructor */
privileged_op (privileged_op_socket,
PRIV_SEP_OP_SET_HOSTNAME, 0,
op->dest, NULL);
break;
default:
die ("Unexpected type %d", op->type);
}
}
privileged_op (privileged_op_socket,
PRIV_SEP_OP_DONE, 0, NULL, NULL);
}
/* Do not leak file descriptors already used by setup_newroot () */
static void
close_ops_fd (void)
{
SetupOp *op;
for (op = ops; op != NULL; op = op->next)
{
if (op->fd != -1)
{
(void) close (op->fd);
op->fd = -1;
}
}
}
/* We need to resolve relative symlinks in the sandbox before we
chroot so that absolute symlinks are handled correctly. We also
need to do this after we've switched to the real uid so that
e.g. paths on fuse mounts work */
static void
resolve_symlinks_in_ops (void)
{
SetupOp *op;
for (op = ops; op != NULL; op = op->next)
{
const char *old_source;
switch (op->type)
{
case SETUP_RO_BIND_MOUNT:
case SETUP_DEV_BIND_MOUNT:
case SETUP_BIND_MOUNT:
old_source = op->source;
op->source = realpath (old_source, NULL);
if (op->source == NULL)
{
if (op->flags & ALLOW_NOTEXIST && errno == ENOENT)
op->source = old_source;
else
die_with_error("Can't find source path %s", old_source);
}
break;
default:
break;
}
}
}
static const char *
resolve_string_offset (void *buffer,
size_t buffer_size,
uint32_t offset)
{
if (offset == 0)
return NULL;
if (offset > buffer_size)
die ("Invalid string offset %d (buffer size %zd)", offset, buffer_size);
return (const char *) buffer + offset;
}
static uint32_t
read_priv_sec_op (int read_socket,
void *buffer,
size_t buffer_size,
uint32_t *flags,
const char **arg1,
const char **arg2)
{
const PrivSepOp *op = (const PrivSepOp *) buffer;
ssize_t rec_len;
do
rec_len = read (read_socket, buffer, buffer_size - 1);
while (rec_len == -1 && errno == EINTR);
if (rec_len < 0)
die_with_error ("Can't read from unprivileged helper");
if (rec_len == 0)
exit (1); /* Privileged helper died and printed error, so exit silently */
if (rec_len < sizeof (PrivSepOp))
die ("Invalid size %zd from unprivileged helper", rec_len);
/* Guarantee zero termination of any strings */
((char *) buffer)[rec_len] = 0;
*flags = op->flags;
*arg1 = resolve_string_offset (buffer, rec_len, op->arg1_offset);
*arg2 = resolve_string_offset (buffer, rec_len, op->arg2_offset);
return op->op;
}
static void __attribute__ ((noreturn))
print_version_and_exit (void)
{
printf ("%s\n", PACKAGE_STRING);
exit (0);
}
static void
parse_args_recurse (int *argcp,
const char ***argvp,
bool in_file,
int *total_parsed_argc_p)
{
SetupOp *op;
int argc = *argcp;
const char **argv = *argvp;
/* I can't imagine a case where someone wants more than this.
* If you do...you should be able to pass multiple files
* via a single tmpfs and linking them there, etc.
*
* We're adding this hardening due to precedent from
* http://googleprojectzero.blogspot.com/2014/08/the-poisoned-nul-byte-2014-edition.html
*
* I picked 9000 because the Internet told me to and it was hard to
* resist.
*/
static const uint32_t MAX_ARGS = 9000;
if (*total_parsed_argc_p > MAX_ARGS)
die ("Exceeded maximum number of arguments %u", MAX_ARGS);
while (argc > 0)
{
const char *arg = argv[0];
if (strcmp (arg, "--help") == 0)
{
usage (EXIT_SUCCESS, stdout);
}
else if (strcmp (arg, "--version") == 0)
{
print_version_and_exit ();
}
else if (strcmp (arg, "--args") == 0)
{
int the_fd;
char *endptr;
const char *p, *data_end;
size_t data_len;
cleanup_free const char **data_argv = NULL;
const char **data_argv_copy;
int data_argc;
int i;
if (in_file)
die ("--args not supported in arguments file");
if (argc < 2)
die ("--args takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
/* opt_args_data is essentially a recursive argv array, which we must
* keep allocated until exit time, since its argv entries get used
* by the other cases in parse_args_recurse() when we recurse. */
opt_args_data = load_file_data (the_fd, &data_len);
if (opt_args_data == NULL)
die_with_error ("Can't read --args data");
(void) close (the_fd);
data_end = opt_args_data + data_len;
data_argc = 0;
p = opt_args_data;
while (p != NULL && p < data_end)
{
data_argc++;
(*total_parsed_argc_p)++;
if (*total_parsed_argc_p > MAX_ARGS)
die ("Exceeded maximum number of arguments %u", MAX_ARGS);
p = memchr (p, 0, data_end - p);
if (p != NULL)
p++;
}
data_argv = xcalloc (sizeof (char *) * (data_argc + 1));
i = 0;
p = opt_args_data;
while (p != NULL && p < data_end)
{
/* Note: load_file_data always adds a nul terminator, so this is safe
* even for the last string. */
data_argv[i++] = p;
p = memchr (p, 0, data_end - p);
if (p != NULL)
p++;
}
data_argv_copy = data_argv; /* Don't change data_argv, we need to free it */
parse_args_recurse (&data_argc, &data_argv_copy, TRUE, total_parsed_argc_p);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--unshare-all") == 0)
{
/* Keep this in order with the older (legacy) --unshare arguments,
* we use the --try variants of user and cgroup, since we want
* to support systems/kernels without support for those.
*/
opt_unshare_user_try = opt_unshare_ipc = opt_unshare_pid =
opt_unshare_uts = opt_unshare_cgroup_try =
opt_unshare_net = TRUE;
}
/* Begin here the older individual --unshare variants */
else if (strcmp (arg, "--unshare-user") == 0)
{
opt_unshare_user = TRUE;
}
else if (strcmp (arg, "--unshare-user-try") == 0)
{
opt_unshare_user_try = TRUE;
}
else if (strcmp (arg, "--unshare-ipc") == 0)
{
opt_unshare_ipc = TRUE;
}
else if (strcmp (arg, "--unshare-pid") == 0)
{
opt_unshare_pid = TRUE;
}
else if (strcmp (arg, "--unshare-net") == 0)
{
opt_unshare_net = TRUE;
}
else if (strcmp (arg, "--unshare-uts") == 0)
{
opt_unshare_uts = TRUE;
}
else if (strcmp (arg, "--unshare-cgroup") == 0)
{
opt_unshare_cgroup = TRUE;
}
else if (strcmp (arg, "--unshare-cgroup-try") == 0)
{
opt_unshare_cgroup_try = TRUE;
}
/* Begin here the newer --share variants */
else if (strcmp (arg, "--share-net") == 0)
{
opt_unshare_net = FALSE;
}
/* End --share variants, other arguments begin */
else if (strcmp (arg, "--chdir") == 0)
{
if (argc < 2)
die ("--chdir takes one argument");
opt_chdir_path = argv[1];
argv++;
argc--;
}
else if (strcmp (arg, "--remount-ro") == 0)
{
if (argc < 2)
die ("--remount-ro takes one argument");
SetupOp *op = setup_op_new (SETUP_REMOUNT_RO_NO_RECURSIVE);
op->dest = argv[1];
argv++;
argc--;
}
else if (strcmp(arg, "--bind") == 0 ||
strcmp(arg, "--bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp(arg, "--ro-bind") == 0 ||
strcmp(arg, "--ro-bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_RO_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--ro-bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--dev-bind") == 0 ||
strcmp (arg, "--dev-bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_DEV_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--dev-bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--proc") == 0)
{
if (argc < 2)
die ("--proc takes an argument");
op = setup_op_new (SETUP_MOUNT_PROC);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--exec-label") == 0)
{
if (argc < 2)
die ("--exec-label takes an argument");
opt_exec_label = argv[1];
die_unless_label_valid (opt_exec_label);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--file-label") == 0)
{
if (argc < 2)
die ("--file-label takes an argument");
opt_file_label = argv[1];
die_unless_label_valid (opt_file_label);
if (label_create_file (opt_file_label))
die_with_error ("--file-label setup failed");
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--dev") == 0)
{
if (argc < 2)
die ("--dev takes an argument");
op = setup_op_new (SETUP_MOUNT_DEV);
op->dest = argv[1];
opt_needs_devpts = TRUE;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--tmpfs") == 0)
{
if (argc < 2)
die ("--tmpfs takes an argument");
op = setup_op_new (SETUP_MOUNT_TMPFS);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--mqueue") == 0)
{
if (argc < 2)
die ("--mqueue takes an argument");
op = setup_op_new (SETUP_MOUNT_MQUEUE);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--dir") == 0)
{
if (argc < 2)
die ("--dir takes an argument");
op = setup_op_new (SETUP_MAKE_DIR);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--file") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--file takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--bind-data") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--bind-data takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_BIND_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--ro-bind-data") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--ro-bind-data takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_RO_BIND_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--symlink") == 0)
{
if (argc < 3)
die ("--symlink takes two arguments");
op = setup_op_new (SETUP_MAKE_SYMLINK);
op->source = argv[1];
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--lock-file") == 0)
{
if (argc < 2)
die ("--lock-file takes an argument");
(void) lock_file_new (argv[1]);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--sync-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--sync-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_sync_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--block-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--block-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_block_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--userns-block-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--userns-block-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_userns_block_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--info-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--info-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_info_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--json-status-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--json-status-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_json_status_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--seccomp") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--seccomp takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_seccomp_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--userns") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--userns takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_userns_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--userns2") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--userns2 takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_userns2_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--pidns") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--pidns takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_pidns_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--setenv") == 0)
{
if (argc < 3)
die ("--setenv takes two arguments");
xsetenv (argv[1], argv[2], 1);
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--unsetenv") == 0)
{
if (argc < 2)
die ("--unsetenv takes an argument");
xunsetenv (argv[1]);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--uid") == 0)
{
int the_uid;
char *endptr;
if (argc < 2)
die ("--uid takes an argument");
the_uid = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_uid < 0)
die ("Invalid uid: %s", argv[1]);
opt_sandbox_uid = the_uid;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--gid") == 0)
{
int the_gid;
char *endptr;
if (argc < 2)
die ("--gid takes an argument");
the_gid = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_gid < 0)
die ("Invalid gid: %s", argv[1]);
opt_sandbox_gid = the_gid;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--hostname") == 0)
{
if (argc < 2)
die ("--hostname takes an argument");
op = setup_op_new (SETUP_SET_HOSTNAME);
op->dest = argv[1];
op->flags = NO_CREATE_DEST;
opt_sandbox_hostname = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--new-session") == 0)
{
opt_new_session = TRUE;
}
else if (strcmp (arg, "--die-with-parent") == 0)
{
opt_die_with_parent = TRUE;
}
else if (strcmp (arg, "--as-pid-1") == 0)
{
opt_as_pid_1 = TRUE;
}
else if (strcmp (arg, "--cap-add") == 0)
{
cap_value_t cap;
if (argc < 2)
die ("--cap-add takes an argument");
opt_cap_add_or_drop_used = TRUE;
if (strcasecmp (argv[1], "ALL") == 0)
{
requested_caps[0] = requested_caps[1] = 0xFFFFFFFF;
}
else
{
if (cap_from_name (argv[1], &cap) < 0)
die ("unknown cap: %s", argv[1]);
if (cap < 32)
requested_caps[0] |= CAP_TO_MASK_0 (cap);
else
requested_caps[1] |= CAP_TO_MASK_1 (cap - 32);
}
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--cap-drop") == 0)
{
cap_value_t cap;
if (argc < 2)
die ("--cap-drop takes an argument");
opt_cap_add_or_drop_used = TRUE;
if (strcasecmp (argv[1], "ALL") == 0)
{
requested_caps[0] = requested_caps[1] = 0;
}
else
{
if (cap_from_name (argv[1], &cap) < 0)
die ("unknown cap: %s", argv[1]);
if (cap < 32)
requested_caps[0] &= ~CAP_TO_MASK_0 (cap);
else
requested_caps[1] &= ~CAP_TO_MASK_1 (cap - 32);
}
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--") == 0)
{
argv += 1;
argc -= 1;
break;
}
else if (*arg == '-')
{
die ("Unknown option %s", arg);
}
else
{
break;
}
argv++;
argc--;
}
*argcp = argc;
*argvp = argv;
}
static void
parse_args (int *argcp,
const char ***argvp)
{
int total_parsed_argc = *argcp;
parse_args_recurse (argcp, argvp, FALSE, &total_parsed_argc);
}
static void
read_overflowids (void)
{
cleanup_free char *uid_data = NULL;
cleanup_free char *gid_data = NULL;
uid_data = load_file_at (AT_FDCWD, "/proc/sys/kernel/overflowuid");
if (uid_data == NULL)
die_with_error ("Can't read /proc/sys/kernel/overflowuid");
overflow_uid = strtol (uid_data, NULL, 10);
if (overflow_uid == 0)
die ("Can't parse /proc/sys/kernel/overflowuid");
gid_data = load_file_at (AT_FDCWD, "/proc/sys/kernel/overflowgid");
if (gid_data == NULL)
die_with_error ("Can't read /proc/sys/kernel/overflowgid");
overflow_gid = strtol (gid_data, NULL, 10);
if (overflow_gid == 0)
die ("Can't parse /proc/sys/kernel/overflowgid");
}
static void
namespace_ids_read (pid_t pid)
{
cleanup_free char *dir = NULL;
cleanup_fd int ns_fd = -1;
NsInfo *info;
dir = xasprintf ("%d/ns", pid);
ns_fd = openat (proc_fd, dir, O_PATH);
if (ns_fd < 0)
die_with_error ("open /proc/%s/ns failed", dir);
for (info = ns_infos; info->name; info++)
{
bool *do_unshare = info->do_unshare;
struct stat st;
int r;
/* if we don't unshare this ns, ignore it */
if (do_unshare && *do_unshare == FALSE)
continue;
r = fstatat (ns_fd, info->name, &st, 0);
/* if we can't get the information, ignore it */
if (r != 0)
continue;
info->id = st.st_ino;
}
}
static void
namespace_ids_write (int fd,
bool in_json)
{
NsInfo *info;
for (info = ns_infos; info->name; info++)
{
cleanup_free char *output = NULL;
const char *indent;
uintmax_t nsid;
nsid = (uintmax_t) info->id;
/* if we don't have the information, we don't write it */
if (nsid == 0)
continue;
indent = in_json ? " " : "\n ";
output = xasprintf (",%s\"%s-namespace\": %ju",
indent, info->name, nsid);
dump_info (fd, output, TRUE);
}
}
int
main (int argc,
char **argv)
{
mode_t old_umask;
const char *base_path = NULL;
int clone_flags;
char *old_cwd = NULL;
pid_t pid;
int event_fd = -1;
int child_wait_fd = -1;
int setup_finished_pipe[] = {-1, -1};
const char *new_cwd;
uid_t ns_uid;
gid_t ns_gid;
struct stat sbuf;
uint64_t val;
int res UNUSED;
cleanup_free char *seccomp_data = NULL;
size_t seccomp_len;
struct sock_fprog seccomp_prog;
cleanup_free char *args_data = NULL;
int intermediate_pids_sockets[2] = {-1, -1};
/* Handle --version early on before we try to acquire/drop
* any capabilities so it works in a build environment;
* right now flatpak's build runs bubblewrap --version.
* https://github.com/projectatomic/bubblewrap/issues/185
*/
if (argc == 2 && (strcmp (argv[1], "--version") == 0))
print_version_and_exit ();
real_uid = getuid ();
real_gid = getgid ();
/* Get the (optional) privileges we need */
acquire_privs ();
/* Never gain any more privs during exec */
if (prctl (PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0)
die_with_error ("prctl(PR_SET_NO_NEW_CAPS) failed");
/* The initial code is run with high permissions
(i.e. CAP_SYS_ADMIN), so take lots of care. */
read_overflowids ();
argv0 = argv[0];
if (isatty (1))
host_tty_dev = ttyname (1);
argv++;
argc--;
if (argc == 0)
usage (EXIT_FAILURE, stderr);
parse_args (&argc, (const char ***) &argv);
/* suck the args into a cleanup_free variable to control their lifecycle */
args_data = opt_args_data;
opt_args_data = NULL;
if ((requested_caps[0] || requested_caps[1]) && is_privileged)
die ("--cap-add in setuid mode can be used only by root");
if (opt_userns_block_fd != -1 && !opt_unshare_user)
die ("--userns-block-fd requires --unshare-user");
if (opt_userns_block_fd != -1 && opt_info_fd == -1)
die ("--userns-block-fd requires --info-fd");
if (opt_userns_fd != -1 && opt_unshare_user)
die ("--userns not compatible --unshare-user");
if (opt_userns_fd != -1 && opt_unshare_user_try)
die ("--userns not compatible --unshare-user-try");
/* Technically using setns() is probably safe even in the privileged
* case, because we got passed in a file descriptor to the
* namespace, and that can only be gotten if you have ptrace
* permissions against the target, and then you could do whatever to
* the namespace anyway.
*
* However, for practical reasons this isn't possible to use,
* because (as described in acquire_privs()) setuid bwrap causes
* root to own the namespaces that it creates, so you will not be
* able to access these namespaces anyway. So, best just not support
* it anway.
*/
if (opt_userns_fd != -1 && is_privileged)
die ("--userns doesn't work in setuid mode");
if (opt_userns2_fd != -1 && is_privileged)
die ("--userns2 doesn't work in setuid mode");
/* We have to do this if we weren't installed setuid (and we're not
* root), so let's just DWIM */
if (!is_privileged && getuid () != 0 && opt_userns_fd == -1)
opt_unshare_user = TRUE;
#ifdef ENABLE_REQUIRE_USERNS
/* In this build option, we require userns. */
if (is_privileged && getuid () != 0 && opt_userns_fd == -1)
opt_unshare_user = TRUE;
#endif
if (opt_unshare_user_try &&
stat ("/proc/self/ns/user", &sbuf) == 0)
{
bool disabled = FALSE;
/* RHEL7 has a kernel module parameter that lets you enable user namespaces */
if (stat ("/sys/module/user_namespace/parameters/enable", &sbuf) == 0)
{
cleanup_free char *enable = NULL;
enable = load_file_at (AT_FDCWD, "/sys/module/user_namespace/parameters/enable");
if (enable != NULL && enable[0] == 'N')
disabled = TRUE;
}
/* Check for max_user_namespaces */
if (stat ("/proc/sys/user/max_user_namespaces", &sbuf) == 0)
{
cleanup_free char *max_user_ns = NULL;
max_user_ns = load_file_at (AT_FDCWD, "/proc/sys/user/max_user_namespaces");
if (max_user_ns != NULL && strcmp(max_user_ns, "0\n") == 0)
disabled = TRUE;
}
/* Debian lets you disable *unprivileged* user namespaces. However this is not
a problem if we're privileged, and if we're not opt_unshare_user is TRUE
already, and there is not much we can do, its just a non-working setup. */
if (!disabled)
opt_unshare_user = TRUE;
}
if (argc == 0)
usage (EXIT_FAILURE, stderr);
__debug__ (("Creating root mount point\n"));
if (opt_sandbox_uid == -1)
opt_sandbox_uid = real_uid;
if (opt_sandbox_gid == -1)
opt_sandbox_gid = real_gid;
if (!opt_unshare_user && opt_userns_fd == -1 && opt_sandbox_uid != real_uid)
die ("Specifying --uid requires --unshare-user or --userns");
if (!opt_unshare_user && opt_userns_fd == -1 && opt_sandbox_gid != real_gid)
die ("Specifying --gid requires --unshare-user or --userns");
if (!opt_unshare_uts && opt_sandbox_hostname != NULL)
die ("Specifying --hostname requires --unshare-uts");
if (opt_as_pid_1 && !opt_unshare_pid)
die ("Specifying --as-pid-1 requires --unshare-pid");
if (opt_as_pid_1 && lock_files != NULL)
die ("Specifying --as-pid-1 and --lock-file is not permitted");
/* We need to read stuff from proc during the pivot_root dance, etc.
Lets keep a fd to it open */
proc_fd = open ("/proc", O_PATH);
if (proc_fd == -1)
die_with_error ("Can't open /proc");
/* We need *some* mountpoint where we can mount the root tmpfs.
* Because we use pivot_root, it won't appear to be mounted from
* the perspective of the sandboxed process, so we can use anywhere
* that is sure to exist, that is sure to not be a symlink controlled
* by someone malicious, and that we won't immediately need to
* access ourselves. */
base_path = "/tmp";
__debug__ (("creating new namespace\n"));
if (opt_unshare_pid && !opt_as_pid_1)
{
event_fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK);
if (event_fd == -1)
die_with_error ("eventfd()");
}
/* We block sigchild here so that we can use signalfd in the monitor. */
block_sigchild ();
clone_flags = SIGCHLD | CLONE_NEWNS;
if (opt_unshare_user)
clone_flags |= CLONE_NEWUSER;
if (opt_unshare_pid && opt_pidns_fd == -1)
clone_flags |= CLONE_NEWPID;
if (opt_unshare_net)
clone_flags |= CLONE_NEWNET;
if (opt_unshare_ipc)
clone_flags |= CLONE_NEWIPC;
if (opt_unshare_uts)
clone_flags |= CLONE_NEWUTS;
if (opt_unshare_cgroup)
{
if (stat ("/proc/self/ns/cgroup", &sbuf))
{
if (errno == ENOENT)
die ("Cannot create new cgroup namespace because the kernel does not support it");
else
die_with_error ("stat on /proc/self/ns/cgroup failed");
}
clone_flags |= CLONE_NEWCGROUP;
}
if (opt_unshare_cgroup_try)
{
opt_unshare_cgroup = !stat ("/proc/self/ns/cgroup", &sbuf);
if (opt_unshare_cgroup)
clone_flags |= CLONE_NEWCGROUP;
}
child_wait_fd = eventfd (0, EFD_CLOEXEC);
if (child_wait_fd == -1)
die_with_error ("eventfd()");
/* Track whether pre-exec setup finished if we're reporting process exit */
if (opt_json_status_fd != -1)
{
int ret;
ret = pipe2 (setup_finished_pipe, O_CLOEXEC);
if (ret == -1)
die_with_error ("pipe2()");
}
/* Switch to the custom user ns before the clone, gets us privs in that ns (assuming its a child of the current and thus allowed) */
if (opt_userns_fd > 0 && setns (opt_userns_fd, CLONE_NEWUSER) != 0)
{
if (errno == EINVAL)
die ("Joining the specified user namespace failed, it might not be a descendant of the current user namespace.");
die_with_error ("Joining specified user namespace failed");
}
/* Sometimes we have uninteresting intermediate pids during the setup, set up code to pass the real pid down */
if (opt_pidns_fd != -1)
{
/* Mark us as a subreaper, this way we can get exit status from grandchildren */
prctl (PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0);
create_pid_socketpair (intermediate_pids_sockets);
}
pid = raw_clone (clone_flags, NULL);
if (pid == -1)
{
if (opt_unshare_user)
{
if (errno == EINVAL)
die ("Creating new namespace failed, likely because the kernel does not support user namespaces. bwrap must be installed setuid on such systems.");
else if (errno == EPERM && !is_privileged)
die ("No permissions to creating new namespace, likely because the kernel does not allow non-privileged user namespaces. On e.g. debian this can be enabled with 'sysctl kernel.unprivileged_userns_clone=1'.");
}
die_with_error ("Creating new namespace failed");
}
ns_uid = opt_sandbox_uid;
ns_gid = opt_sandbox_gid;
if (pid != 0)
{
/* Parent, outside sandbox, privileged (initially) */
if (intermediate_pids_sockets[0] != -1)
{
close (intermediate_pids_sockets[1]);
pid = read_pid_from_socket (intermediate_pids_sockets[0]);
close (intermediate_pids_sockets[0]);
}
/* Discover namespace ids before we drop privileges */
namespace_ids_read (pid);
if (is_privileged && opt_unshare_user && opt_userns_block_fd == -1)
{
/* We're running as euid 0, but the uid we want to map is
* not 0. This means we're not allowed to write this from
* the child user namespace, so we do it from the parent.
*
* Also, we map uid/gid 0 in the namespace (to overflowuid)
* if opt_needs_devpts is true, because otherwise the mount
* of devpts fails due to root not being mapped.
*/
write_uid_gid_map (ns_uid, real_uid,
ns_gid, real_gid,
pid, TRUE, opt_needs_devpts);
}
/* Initial launched process, wait for pid 1 or exec:ed command to exit */
if (opt_userns2_fd > 0 && setns (opt_userns2_fd, CLONE_NEWUSER) != 0)
die_with_error ("Setting userns2 failed");
/* We don't need any privileges in the launcher, drop them immediately. */
drop_privs (FALSE, FALSE);
/* Optionally bind our lifecycle to that of the parent */
handle_die_with_parent ();
if (opt_info_fd != -1)
{
cleanup_free char *output = xasprintf ("{\n \"child-pid\": %i", pid);
dump_info (opt_info_fd, output, TRUE);
namespace_ids_write (opt_info_fd, FALSE);
dump_info (opt_info_fd, "\n}\n", TRUE);
close (opt_info_fd);
}
if (opt_json_status_fd != -1)
{
cleanup_free char *output = xasprintf ("{ \"child-pid\": %i", pid);
dump_info (opt_json_status_fd, output, TRUE);
namespace_ids_write (opt_json_status_fd, TRUE);
dump_info (opt_json_status_fd, " }\n", TRUE);
}
if (opt_userns_block_fd != -1)
{
char b[1];
(void) TEMP_FAILURE_RETRY (read (opt_userns_block_fd, b, 1));
close (opt_userns_block_fd);
}
/* Let child run now that the uid maps are set up */
val = 1;
res = write (child_wait_fd, &val, 8);
/* Ignore res, if e.g. the child died and closed child_wait_fd we don't want to error out here */
close (child_wait_fd);
return monitor_child (event_fd, pid, setup_finished_pipe[0]);
}
if (opt_pidns_fd > 0)
{
if (setns (opt_pidns_fd, CLONE_NEWPID) != 0)
die_with_error ("Setting pidns failed");
/* fork to get the passed in pid ns */
fork_intermediate_child ();
/* We might both have specified an --pidns *and* --unshare-pid, so set up a new child pid namespace under the specified one */
if (opt_unshare_pid)
{
if (unshare (CLONE_NEWPID))
die_with_error ("unshare pid ns");
/* fork to get the new pid ns */
fork_intermediate_child ();
}
/* We're back, either in a child or grandchild, so message the actual pid to the monitor */
close (intermediate_pids_sockets[0]);
send_pid_on_socket (intermediate_pids_sockets[1]);
close (intermediate_pids_sockets[1]);
}
/* Child, in sandbox, privileged in the parent or in the user namespace (if --unshare-user).
*
* Note that for user namespaces we run as euid 0 during clone(), so
* the child user namespace is owned by euid 0., This means that the
* regular user namespace parent (with uid != 0) doesn't have any
* capabilities in it, which is nice as we can't exploit those. In
* particular the parent user namespace doesn't have CAP_PTRACE
* which would otherwise allow the parent to hijack of the child
* after this point.
*
* Unfortunately this also means you can't ptrace the final
* sandboxed process from outside the sandbox either.
*/
if (opt_info_fd != -1)
close (opt_info_fd);
if (opt_json_status_fd != -1)
close (opt_json_status_fd);
/* Wait for the parent to init uid/gid maps and drop caps */
res = read (child_wait_fd, &val, 8);
close (child_wait_fd);
/* At this point we can completely drop root uid, but retain the
* required permitted caps. This allow us to do full setup as
* the user uid, which makes e.g. fuse access work.
*/
switch_to_user_with_privs ();
if (opt_unshare_net)
loopback_setup (); /* Will exit if unsuccessful */
ns_uid = opt_sandbox_uid;
ns_gid = opt_sandbox_gid;
if (!is_privileged && opt_unshare_user && opt_userns_block_fd == -1)
{
/* In the unprivileged case we have to write the uid/gid maps in
* the child, because we have no caps in the parent */
if (opt_needs_devpts)
{
/* This is a bit hacky, but we need to first map the real uid/gid to
0, otherwise we can't mount the devpts filesystem because root is
not mapped. Later we will create another child user namespace and
map back to the real uid */
ns_uid = 0;
ns_gid = 0;
}
write_uid_gid_map (ns_uid, real_uid,
ns_gid, real_gid,
-1, TRUE, FALSE);
}
old_umask = umask (0);
/* Need to do this before the chroot, but after we're the real uid */
resolve_symlinks_in_ops ();
/* Mark everything as slave, so that we still
* receive mounts from the real root, but don't
* propagate mounts to the real root. */
if (mount (NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0)
die_with_error ("Failed to make / slave");
/* Create a tmpfs which we will use as / in the namespace */
if (mount ("tmpfs", base_path, "tmpfs", MS_NODEV | MS_NOSUID, NULL) != 0)
die_with_error ("Failed to mount tmpfs");
old_cwd = get_current_dir_name ();
/* Chdir to the new root tmpfs mount. This will be the CWD during
the entire setup. Access old or new root via "oldroot" and "newroot". */
if (chdir (base_path) != 0)
die_with_error ("chdir base_path");
/* We create a subdir "$base_path/newroot" for the new root, that
* way we can pivot_root to base_path, and put the old root at
* "$base_path/oldroot". This avoids problems accessing the oldroot
* dir if the user requested to bind mount something over / (or
* over /tmp, now that we use that for base_path). */
if (mkdir ("newroot", 0755))
die_with_error ("Creating newroot failed");
if (mount ("newroot", "newroot", NULL, MS_MGC_VAL | MS_BIND | MS_REC, NULL) < 0)
die_with_error ("setting up newroot bind");
if (mkdir ("oldroot", 0755))
die_with_error ("Creating oldroot failed");
if (pivot_root (base_path, "oldroot"))
die_with_error ("pivot_root");
if (chdir ("/") != 0)
die_with_error ("chdir / (base path)");
if (is_privileged)
{
pid_t child;
int privsep_sockets[2];
if (socketpair (AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, privsep_sockets) != 0)
die_with_error ("Can't create privsep socket");
child = fork ();
if (child == -1)
die_with_error ("Can't fork unprivileged helper");
if (child == 0)
{
/* Unprivileged setup process */
drop_privs (FALSE, TRUE);
close (privsep_sockets[0]);
setup_newroot (opt_unshare_pid, privsep_sockets[1]);
exit (0);
}
else
{
int status;
uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */
uint32_t op, flags;
const char *arg1, *arg2;
cleanup_fd int unpriv_socket = -1;
unpriv_socket = privsep_sockets[0];
close (privsep_sockets[1]);
do
{
op = read_priv_sec_op (unpriv_socket, buffer, sizeof (buffer),
&flags, &arg1, &arg2);
privileged_op (-1, op, flags, arg1, arg2);
if (write (unpriv_socket, buffer, 1) != 1)
die ("Can't write to op_socket");
}
while (op != PRIV_SEP_OP_DONE);
waitpid (child, &status, 0);
/* Continue post setup */
}
}
else
{
setup_newroot (opt_unshare_pid, -1);
}
close_ops_fd ();
/* The old root better be rprivate or we will send unmount events to the parent namespace */
if (mount ("oldroot", "oldroot", NULL, MS_REC | MS_PRIVATE, NULL) != 0)
die_with_error ("Failed to make old root rprivate");
if (umount2 ("oldroot", MNT_DETACH))
die_with_error ("unmount old root");
/* This is our second pivot. It's like we're a Silicon Valley startup flush
* with cash but short on ideas!
*
* We're aiming to make /newroot the real root, and get rid of /oldroot. To do
* that we need a temporary place to store it before we can unmount it.
*/
{ cleanup_fd int oldrootfd = open ("/", O_DIRECTORY | O_RDONLY);
if (oldrootfd < 0)
die_with_error ("can't open /");
if (chdir ("/newroot") != 0)
die_with_error ("chdir /newroot");
/* While the documentation claims that put_old must be underneath
* new_root, it is perfectly fine to use the same directory as the
* kernel checks only if old_root is accessible from new_root.
*
* Both runc and LXC are using this "alternative" method for
* setting up the root of the container:
*
* https://github.com/opencontainers/runc/blob/master/libcontainer/rootfs_linux.go#L671
* https://github.com/lxc/lxc/blob/master/src/lxc/conf.c#L1121
*/
if (pivot_root (".", ".") != 0)
die_with_error ("pivot_root(/newroot)");
if (fchdir (oldrootfd) < 0)
die_with_error ("fchdir to oldroot");
if (umount2 (".", MNT_DETACH) < 0)
die_with_error ("umount old root");
if (chdir ("/") != 0)
die_with_error ("chdir /");
}
if (opt_userns2_fd > 0 && setns (opt_userns2_fd, CLONE_NEWUSER) != 0)
die_with_error ("Setting userns2 failed");
if (opt_unshare_user &&
(ns_uid != opt_sandbox_uid || ns_gid != opt_sandbox_gid) &&
opt_userns_block_fd == -1)
{
/* Now that devpts is mounted and we've no need for mount
permissions we can create a new userspace and map our uid
1:1 */
if (unshare (CLONE_NEWUSER))
die_with_error ("unshare user ns");
/* We're in a new user namespace, we got back the bounding set, clear it again */
drop_cap_bounding_set (FALSE);
write_uid_gid_map (opt_sandbox_uid, ns_uid,
opt_sandbox_gid, ns_gid,
-1, FALSE, FALSE);
}
/* All privileged ops are done now, so drop caps we don't need */
drop_privs (!is_privileged, TRUE);
if (opt_block_fd != -1)
{
char b[1];
(void) TEMP_FAILURE_RETRY (read (opt_block_fd, b, 1));
close (opt_block_fd);
}
if (opt_seccomp_fd != -1)
{
seccomp_data = load_file_data (opt_seccomp_fd, &seccomp_len);
if (seccomp_data == NULL)
die_with_error ("Can't read seccomp data");
if (seccomp_len % 8 != 0)
die ("Invalid seccomp data, must be multiple of 8");
seccomp_prog.len = seccomp_len / 8;
seccomp_prog.filter = (struct sock_filter *) seccomp_data;
close (opt_seccomp_fd);
}
umask (old_umask);
new_cwd = "/";
if (opt_chdir_path)
{
if (chdir (opt_chdir_path))
die_with_error ("Can't chdir to %s", opt_chdir_path);
new_cwd = opt_chdir_path;
}
else if (chdir (old_cwd) == 0)
{
/* If the old cwd is mapped in the sandbox, go there */
new_cwd = old_cwd;
}
else
{
/* If the old cwd is not mapped, go to home */
const char *home = getenv ("HOME");
if (home != NULL &&
chdir (home) == 0)
new_cwd = home;
}
xsetenv ("PWD", new_cwd, 1);
free (old_cwd);
if (opt_new_session &&
setsid () == (pid_t) -1)
die_with_error ("setsid");
if (label_exec (opt_exec_label) == -1)
die_with_error ("label_exec %s", argv[0]);
__debug__ (("forking for child\n"));
if (!opt_as_pid_1 && (opt_unshare_pid || lock_files != NULL || opt_sync_fd != -1))
{
/* We have to have a pid 1 in the pid namespace, because
* otherwise we'll get a bunch of zombies as nothing reaps
* them. Alternatively if we're using sync_fd or lock_files we
* need some process to own these.
*/
pid = fork ();
if (pid == -1)
die_with_error ("Can't fork for pid 1");
if (pid != 0)
{
drop_all_caps (FALSE);
/* Close fds in pid 1, except stdio and optionally event_fd
(for syncing pid 2 lifetime with monitor_child) and
opt_sync_fd (for syncing sandbox lifetime with outside
process).
Any other fds will been passed on to the child though. */
{
int dont_close[3];
int j = 0;
if (event_fd != -1)
dont_close[j++] = event_fd;
if (opt_sync_fd != -1)
dont_close[j++] = opt_sync_fd;
dont_close[j++] = -1;
fdwalk (proc_fd, close_extra_fds, dont_close);
}
return do_init (event_fd, pid, seccomp_data != NULL ? &seccomp_prog : NULL);
}
}
__debug__ (("launch executable %s\n", argv[0]));
if (proc_fd != -1)
close (proc_fd);
/* If we are using --as-pid-1 leak the sync fd into the sandbox.
--sync-fd will still work unless the container process doesn't close this file. */
if (!opt_as_pid_1)
{
if (opt_sync_fd != -1)
close (opt_sync_fd);
}
/* We want sigchild in the child */
unblock_sigchild ();
/* Optionally bind our lifecycle */
handle_die_with_parent ();
if (!is_privileged)
set_ambient_capabilities ();
/* Should be the last thing before execve() so that filters don't
* need to handle anything above */
if (seccomp_data != NULL &&
prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &seccomp_prog) != 0)
die_with_error ("prctl(PR_SET_SECCOMP)");
if (setup_finished_pipe[1] != -1)
{
char data = 0;
res = write_to_fd (setup_finished_pipe[1], &data, 1);
/* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0]
we don't want to error out here */
}
if (execvp (argv[0], argv) == -1)
{
if (setup_finished_pipe[1] != -1)
{
int saved_errno = errno;
char data = 0;
res = write_to_fd (setup_finished_pipe[1], &data, 1);
errno = saved_errno;
/* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0]
we don't want to error out here */
}
die_with_error ("execvp %s", argv[0]);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_2473_0 |
crossvul-cpp_data_good_4004_0 | /*
* Marvell Wireless LAN device driver: scan ioctl and command handling
*
* Copyright (C) 2011-2014, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
*/
#include "decl.h"
#include "ioctl.h"
#include "util.h"
#include "fw.h"
#include "main.h"
#include "11n.h"
#include "cfg80211.h"
/* The maximum number of channels the firmware can scan per command */
#define MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN 14
#define MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD 4
/* Memory needed to store a max sized Channel List TLV for a firmware scan */
#define CHAN_TLV_MAX_SIZE (sizeof(struct mwifiex_ie_types_header) \
+ (MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN \
*sizeof(struct mwifiex_chan_scan_param_set)))
/* Memory needed to store supported rate */
#define RATE_TLV_MAX_SIZE (sizeof(struct mwifiex_ie_types_rates_param_set) \
+ HOSTCMD_SUPPORTED_RATES)
/* Memory needed to store a max number/size WildCard SSID TLV for a firmware
scan */
#define WILDCARD_SSID_TLV_MAX_SIZE \
(MWIFIEX_MAX_SSID_LIST_LENGTH * \
(sizeof(struct mwifiex_ie_types_wildcard_ssid_params) \
+ IEEE80211_MAX_SSID_LEN))
/* Maximum memory needed for a mwifiex_scan_cmd_config with all TLVs at max */
#define MAX_SCAN_CFG_ALLOC (sizeof(struct mwifiex_scan_cmd_config) \
+ sizeof(struct mwifiex_ie_types_num_probes) \
+ sizeof(struct mwifiex_ie_types_htcap) \
+ CHAN_TLV_MAX_SIZE \
+ RATE_TLV_MAX_SIZE \
+ WILDCARD_SSID_TLV_MAX_SIZE)
union mwifiex_scan_cmd_config_tlv {
/* Scan configuration (variable length) */
struct mwifiex_scan_cmd_config config;
/* Max allocated block */
u8 config_alloc_buf[MAX_SCAN_CFG_ALLOC];
};
enum cipher_suite {
CIPHER_SUITE_TKIP,
CIPHER_SUITE_CCMP,
CIPHER_SUITE_MAX
};
static u8 mwifiex_wpa_oui[CIPHER_SUITE_MAX][4] = {
{ 0x00, 0x50, 0xf2, 0x02 }, /* TKIP */
{ 0x00, 0x50, 0xf2, 0x04 }, /* AES */
};
static u8 mwifiex_rsn_oui[CIPHER_SUITE_MAX][4] = {
{ 0x00, 0x0f, 0xac, 0x02 }, /* TKIP */
{ 0x00, 0x0f, 0xac, 0x04 }, /* AES */
};
static void
_dbg_security_flags(int log_level, const char *func, const char *desc,
struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
_mwifiex_dbg(priv->adapter, log_level,
"info: %s: %s:\twpa_ie=%#x wpa2_ie=%#x WEP=%s WPA=%s WPA2=%s\tEncMode=%#x privacy=%#x\n",
func, desc,
bss_desc->bcn_wpa_ie ?
bss_desc->bcn_wpa_ie->vend_hdr.element_id : 0,
bss_desc->bcn_rsn_ie ?
bss_desc->bcn_rsn_ie->ieee_hdr.element_id : 0,
priv->sec_info.wep_enabled ? "e" : "d",
priv->sec_info.wpa_enabled ? "e" : "d",
priv->sec_info.wpa2_enabled ? "e" : "d",
priv->sec_info.encryption_mode,
bss_desc->privacy);
}
#define dbg_security_flags(mask, desc, priv, bss_desc) \
_dbg_security_flags(MWIFIEX_DBG_##mask, desc, __func__, priv, bss_desc)
static bool
has_ieee_hdr(struct ieee_types_generic *ie, u8 key)
{
return (ie && ie->ieee_hdr.element_id == key);
}
static bool
has_vendor_hdr(struct ieee_types_vendor_specific *ie, u8 key)
{
return (ie && ie->vend_hdr.element_id == key);
}
/*
* This function parses a given IE for a given OUI.
*
* This is used to parse a WPA/RSN IE to find if it has
* a given oui in PTK.
*/
static u8
mwifiex_search_oui_in_ie(struct ie_body *iebody, u8 *oui)
{
u8 count;
count = iebody->ptk_cnt[0];
/* There could be multiple OUIs for PTK hence
1) Take the length.
2) Check all the OUIs for AES.
3) If one of them is AES then pass success. */
while (count) {
if (!memcmp(iebody->ptk_body, oui, sizeof(iebody->ptk_body)))
return MWIFIEX_OUI_PRESENT;
--count;
if (count)
iebody = (struct ie_body *) ((u8 *) iebody +
sizeof(iebody->ptk_body));
}
pr_debug("info: %s: OUI is not found in PTK\n", __func__);
return MWIFIEX_OUI_NOT_PRESENT;
}
/*
* This function checks if a given OUI is present in a RSN IE.
*
* The function first checks if a RSN IE is present or not in the
* BSS descriptor. It tries to locate the OUI only if such an IE is
* present.
*/
static u8
mwifiex_is_rsn_oui_present(struct mwifiex_bssdescriptor *bss_desc, u32 cipher)
{
u8 *oui;
struct ie_body *iebody;
u8 ret = MWIFIEX_OUI_NOT_PRESENT;
if (has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN)) {
iebody = (struct ie_body *)
(((u8 *) bss_desc->bcn_rsn_ie->data) +
RSN_GTK_OUI_OFFSET);
oui = &mwifiex_rsn_oui[cipher][0];
ret = mwifiex_search_oui_in_ie(iebody, oui);
if (ret)
return ret;
}
return ret;
}
/*
* This function checks if a given OUI is present in a WPA IE.
*
* The function first checks if a WPA IE is present or not in the
* BSS descriptor. It tries to locate the OUI only if such an IE is
* present.
*/
static u8
mwifiex_is_wpa_oui_present(struct mwifiex_bssdescriptor *bss_desc, u32 cipher)
{
u8 *oui;
struct ie_body *iebody;
u8 ret = MWIFIEX_OUI_NOT_PRESENT;
if (has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC)) {
iebody = (struct ie_body *)((u8 *)bss_desc->bcn_wpa_ie->data +
WPA_GTK_OUI_OFFSET);
oui = &mwifiex_wpa_oui[cipher][0];
ret = mwifiex_search_oui_in_ie(iebody, oui);
if (ret)
return ret;
}
return ret;
}
/*
* This function compares two SSIDs and checks if they match.
*/
s32
mwifiex_ssid_cmp(struct cfg80211_ssid *ssid1, struct cfg80211_ssid *ssid2)
{
if (!ssid1 || !ssid2 || (ssid1->ssid_len != ssid2->ssid_len))
return -1;
return memcmp(ssid1->ssid, ssid2->ssid, ssid1->ssid_len);
}
/*
* This function checks if wapi is enabled in driver and scanned network is
* compatible with it.
*/
static bool
mwifiex_is_bss_wapi(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (priv->sec_info.wapi_enabled &&
has_ieee_hdr(bss_desc->bcn_wapi_ie, WLAN_EID_BSS_AC_ACCESS_DELAY))
return true;
return false;
}
/*
* This function checks if driver is configured with no security mode and
* scanned network is compatible with it.
*/
static bool
mwifiex_is_bss_no_sec(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled &&
!priv->sec_info.wpa2_enabled &&
!has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) &&
!has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN) &&
!priv->sec_info.encryption_mode && !bss_desc->privacy) {
return true;
}
return false;
}
/*
* This function checks if static WEP is enabled in driver and scanned network
* is compatible with it.
*/
static bool
mwifiex_is_bss_static_wep(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled &&
!priv->sec_info.wpa2_enabled && bss_desc->privacy) {
return true;
}
return false;
}
/*
* This function checks if wpa is enabled in driver and scanned network is
* compatible with it.
*/
static bool
mwifiex_is_bss_wpa(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (!priv->sec_info.wep_enabled && priv->sec_info.wpa_enabled &&
!priv->sec_info.wpa2_enabled &&
has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC)
/*
* Privacy bit may NOT be set in some APs like
* LinkSys WRT54G && bss_desc->privacy
*/
) {
dbg_security_flags(INFO, "WPA", priv, bss_desc);
return true;
}
return false;
}
/*
* This function checks if wpa2 is enabled in driver and scanned network is
* compatible with it.
*/
static bool
mwifiex_is_bss_wpa2(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled &&
priv->sec_info.wpa2_enabled &&
has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN)) {
/*
* Privacy bit may NOT be set in some APs like
* LinkSys WRT54G && bss_desc->privacy
*/
dbg_security_flags(INFO, "WAP2", priv, bss_desc);
return true;
}
return false;
}
/*
* This function checks if adhoc AES is enabled in driver and scanned network is
* compatible with it.
*/
static bool
mwifiex_is_bss_adhoc_aes(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled &&
!priv->sec_info.wpa2_enabled &&
!has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) &&
!has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN) &&
!priv->sec_info.encryption_mode && bss_desc->privacy) {
return true;
}
return false;
}
/*
* This function checks if dynamic WEP is enabled in driver and scanned network
* is compatible with it.
*/
static bool
mwifiex_is_bss_dynamic_wep(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled &&
!priv->sec_info.wpa2_enabled &&
!has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) &&
!has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN) &&
priv->sec_info.encryption_mode && bss_desc->privacy) {
dbg_security_flags(INFO, "dynamic", priv, bss_desc);
return true;
}
return false;
}
/*
* This function checks if a scanned network is compatible with the driver
* settings.
*
* WEP WPA WPA2 ad-hoc encrypt Network
* enabled enabled enabled AES mode Privacy WPA WPA2 Compatible
* 0 0 0 0 NONE 0 0 0 yes No security
* 0 1 0 0 x 1x 1 x yes WPA (disable
* HT if no AES)
* 0 0 1 0 x 1x x 1 yes WPA2 (disable
* HT if no AES)
* 0 0 0 1 NONE 1 0 0 yes Ad-hoc AES
* 1 0 0 0 NONE 1 0 0 yes Static WEP
* (disable HT)
* 0 0 0 0 !=NONE 1 0 0 yes Dynamic WEP
*
* Compatibility is not matched while roaming, except for mode.
*/
static s32
mwifiex_is_network_compatible(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc, u32 mode)
{
struct mwifiex_adapter *adapter = priv->adapter;
bss_desc->disable_11n = false;
/* Don't check for compatibility if roaming */
if (priv->media_connected &&
(priv->bss_mode == NL80211_IFTYPE_STATION) &&
(bss_desc->bss_mode == NL80211_IFTYPE_STATION))
return 0;
if (priv->wps.session_enable) {
mwifiex_dbg(adapter, IOCTL,
"info: return success directly in WPS period\n");
return 0;
}
if (bss_desc->chan_sw_ie_present) {
mwifiex_dbg(adapter, INFO,
"Don't connect to AP with WLAN_EID_CHANNEL_SWITCH\n");
return -1;
}
if (mwifiex_is_bss_wapi(priv, bss_desc)) {
mwifiex_dbg(adapter, INFO,
"info: return success for WAPI AP\n");
return 0;
}
if (bss_desc->bss_mode == mode) {
if (mwifiex_is_bss_no_sec(priv, bss_desc)) {
/* No security */
return 0;
} else if (mwifiex_is_bss_static_wep(priv, bss_desc)) {
/* Static WEP enabled */
mwifiex_dbg(adapter, INFO,
"info: Disable 11n in WEP mode.\n");
bss_desc->disable_11n = true;
return 0;
} else if (mwifiex_is_bss_wpa(priv, bss_desc)) {
/* WPA enabled */
if (((priv->adapter->config_bands & BAND_GN ||
priv->adapter->config_bands & BAND_AN) &&
bss_desc->bcn_ht_cap) &&
!mwifiex_is_wpa_oui_present(bss_desc,
CIPHER_SUITE_CCMP)) {
if (mwifiex_is_wpa_oui_present
(bss_desc, CIPHER_SUITE_TKIP)) {
mwifiex_dbg(adapter, INFO,
"info: Disable 11n if AES\t"
"is not supported by AP\n");
bss_desc->disable_11n = true;
} else {
return -1;
}
}
return 0;
} else if (mwifiex_is_bss_wpa2(priv, bss_desc)) {
/* WPA2 enabled */
if (((priv->adapter->config_bands & BAND_GN ||
priv->adapter->config_bands & BAND_AN) &&
bss_desc->bcn_ht_cap) &&
!mwifiex_is_rsn_oui_present(bss_desc,
CIPHER_SUITE_CCMP)) {
if (mwifiex_is_rsn_oui_present
(bss_desc, CIPHER_SUITE_TKIP)) {
mwifiex_dbg(adapter, INFO,
"info: Disable 11n if AES\t"
"is not supported by AP\n");
bss_desc->disable_11n = true;
} else {
return -1;
}
}
return 0;
} else if (mwifiex_is_bss_adhoc_aes(priv, bss_desc)) {
/* Ad-hoc AES enabled */
return 0;
} else if (mwifiex_is_bss_dynamic_wep(priv, bss_desc)) {
/* Dynamic WEP enabled */
return 0;
}
/* Security doesn't match */
dbg_security_flags(ERROR, "failed", priv, bss_desc);
return -1;
}
/* Mode doesn't match */
return -1;
}
/*
* This function creates a channel list for the driver to scan, based
* on region/band information.
*
* This routine is used for any scan that is not provided with a
* specific channel list to scan.
*/
static int
mwifiex_scan_create_channel_list(struct mwifiex_private *priv,
const struct mwifiex_user_scan_cfg
*user_scan_in,
struct mwifiex_chan_scan_param_set
*scan_chan_list,
u8 filtered_scan)
{
enum nl80211_band band;
struct ieee80211_supported_band *sband;
struct ieee80211_channel *ch;
struct mwifiex_adapter *adapter = priv->adapter;
int chan_idx = 0, i;
for (band = 0; (band < NUM_NL80211_BANDS) ; band++) {
if (!priv->wdev.wiphy->bands[band])
continue;
sband = priv->wdev.wiphy->bands[band];
for (i = 0; (i < sband->n_channels) ; i++) {
ch = &sband->channels[i];
if (ch->flags & IEEE80211_CHAN_DISABLED)
continue;
scan_chan_list[chan_idx].radio_type = band;
if (user_scan_in &&
user_scan_in->chan_list[0].scan_time)
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16((u16) user_scan_in->
chan_list[0].scan_time);
else if ((ch->flags & IEEE80211_CHAN_NO_IR) ||
(ch->flags & IEEE80211_CHAN_RADAR))
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16(adapter->passive_scan_time);
else
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16(adapter->active_scan_time);
if (ch->flags & IEEE80211_CHAN_NO_IR)
scan_chan_list[chan_idx].chan_scan_mode_bitmap
|= (MWIFIEX_PASSIVE_SCAN |
MWIFIEX_HIDDEN_SSID_REPORT);
else
scan_chan_list[chan_idx].chan_scan_mode_bitmap
&= ~MWIFIEX_PASSIVE_SCAN;
scan_chan_list[chan_idx].chan_number =
(u32) ch->hw_value;
scan_chan_list[chan_idx].chan_scan_mode_bitmap
|= MWIFIEX_DISABLE_CHAN_FILT;
if (filtered_scan &&
!((ch->flags & IEEE80211_CHAN_NO_IR) ||
(ch->flags & IEEE80211_CHAN_RADAR)))
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16(adapter->specific_scan_time);
chan_idx++;
}
}
return chan_idx;
}
/* This function creates a channel list tlv for bgscan config, based
* on region/band information.
*/
static int
mwifiex_bgscan_create_channel_list(struct mwifiex_private *priv,
const struct mwifiex_bg_scan_cfg
*bgscan_cfg_in,
struct mwifiex_chan_scan_param_set
*scan_chan_list)
{
enum nl80211_band band;
struct ieee80211_supported_band *sband;
struct ieee80211_channel *ch;
struct mwifiex_adapter *adapter = priv->adapter;
int chan_idx = 0, i;
for (band = 0; (band < NUM_NL80211_BANDS); band++) {
if (!priv->wdev.wiphy->bands[band])
continue;
sband = priv->wdev.wiphy->bands[band];
for (i = 0; (i < sband->n_channels) ; i++) {
ch = &sband->channels[i];
if (ch->flags & IEEE80211_CHAN_DISABLED)
continue;
scan_chan_list[chan_idx].radio_type = band;
if (bgscan_cfg_in->chan_list[0].scan_time)
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16((u16)bgscan_cfg_in->
chan_list[0].scan_time);
else if (ch->flags & IEEE80211_CHAN_NO_IR)
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16(adapter->passive_scan_time);
else
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16(adapter->
specific_scan_time);
if (ch->flags & IEEE80211_CHAN_NO_IR)
scan_chan_list[chan_idx].chan_scan_mode_bitmap
|= MWIFIEX_PASSIVE_SCAN;
else
scan_chan_list[chan_idx].chan_scan_mode_bitmap
&= ~MWIFIEX_PASSIVE_SCAN;
scan_chan_list[chan_idx].chan_number =
(u32)ch->hw_value;
chan_idx++;
}
}
return chan_idx;
}
/* This function appends rate TLV to scan config command. */
static int
mwifiex_append_rate_tlv(struct mwifiex_private *priv,
struct mwifiex_scan_cmd_config *scan_cfg_out,
u8 radio)
{
struct mwifiex_ie_types_rates_param_set *rates_tlv;
u8 rates[MWIFIEX_SUPPORTED_RATES], *tlv_pos;
u32 rates_size;
memset(rates, 0, sizeof(rates));
tlv_pos = (u8 *)scan_cfg_out->tlv_buf + scan_cfg_out->tlv_buf_len;
if (priv->scan_request)
rates_size = mwifiex_get_rates_from_cfg80211(priv, rates,
radio);
else
rates_size = mwifiex_get_supported_rates(priv, rates);
mwifiex_dbg(priv->adapter, CMD,
"info: SCAN_CMD: Rates size = %d\n",
rates_size);
rates_tlv = (struct mwifiex_ie_types_rates_param_set *)tlv_pos;
rates_tlv->header.type = cpu_to_le16(WLAN_EID_SUPP_RATES);
rates_tlv->header.len = cpu_to_le16((u16) rates_size);
memcpy(rates_tlv->rates, rates, rates_size);
scan_cfg_out->tlv_buf_len += sizeof(rates_tlv->header) + rates_size;
return rates_size;
}
/*
* This function constructs and sends multiple scan config commands to
* the firmware.
*
* Previous routines in the code flow have created a scan command configuration
* with any requested TLVs. This function splits the channel TLV into maximum
* channels supported per scan lists and sends the portion of the channel TLV,
* along with the other TLVs, to the firmware.
*/
static int
mwifiex_scan_channel_list(struct mwifiex_private *priv,
u32 max_chan_per_scan, u8 filtered_scan,
struct mwifiex_scan_cmd_config *scan_cfg_out,
struct mwifiex_ie_types_chan_list_param_set
*chan_tlv_out,
struct mwifiex_chan_scan_param_set *scan_chan_list)
{
struct mwifiex_adapter *adapter = priv->adapter;
int ret = 0;
struct mwifiex_chan_scan_param_set *tmp_chan_list;
struct mwifiex_chan_scan_param_set *start_chan;
u32 tlv_idx, rates_size, cmd_no;
u32 total_scan_time;
u32 done_early;
u8 radio_type;
if (!scan_cfg_out || !chan_tlv_out || !scan_chan_list) {
mwifiex_dbg(priv->adapter, ERROR,
"info: Scan: Null detect: %p, %p, %p\n",
scan_cfg_out, chan_tlv_out, scan_chan_list);
return -1;
}
/* Check csa channel expiry before preparing scan list */
mwifiex_11h_get_csa_closed_channel(priv);
chan_tlv_out->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);
/* Set the temp channel struct pointer to the start of the desired
list */
tmp_chan_list = scan_chan_list;
/* Loop through the desired channel list, sending a new firmware scan
commands for each max_chan_per_scan channels (or for 1,6,11
individually if configured accordingly) */
while (tmp_chan_list->chan_number) {
tlv_idx = 0;
total_scan_time = 0;
radio_type = 0;
chan_tlv_out->header.len = 0;
start_chan = tmp_chan_list;
done_early = false;
/*
* Construct the Channel TLV for the scan command. Continue to
* insert channel TLVs until:
* - the tlv_idx hits the maximum configured per scan command
* - the next channel to insert is 0 (end of desired channel
* list)
* - done_early is set (controlling individual scanning of
* 1,6,11)
*/
while (tlv_idx < max_chan_per_scan &&
tmp_chan_list->chan_number && !done_early) {
if (tmp_chan_list->chan_number == priv->csa_chan) {
tmp_chan_list++;
continue;
}
radio_type = tmp_chan_list->radio_type;
mwifiex_dbg(priv->adapter, INFO,
"info: Scan: Chan(%3d), Radio(%d),\t"
"Mode(%d, %d), Dur(%d)\n",
tmp_chan_list->chan_number,
tmp_chan_list->radio_type,
tmp_chan_list->chan_scan_mode_bitmap
& MWIFIEX_PASSIVE_SCAN,
(tmp_chan_list->chan_scan_mode_bitmap
& MWIFIEX_DISABLE_CHAN_FILT) >> 1,
le16_to_cpu(tmp_chan_list->max_scan_time));
/* Copy the current channel TLV to the command being
prepared */
memcpy(chan_tlv_out->chan_scan_param + tlv_idx,
tmp_chan_list,
sizeof(chan_tlv_out->chan_scan_param));
/* Increment the TLV header length by the size
appended */
le16_unaligned_add_cpu(&chan_tlv_out->header.len,
sizeof(
chan_tlv_out->chan_scan_param));
/*
* The tlv buffer length is set to the number of bytes
* of the between the channel tlv pointer and the start
* of the tlv buffer. This compensates for any TLVs
* that were appended before the channel list.
*/
scan_cfg_out->tlv_buf_len = (u32) ((u8 *) chan_tlv_out -
scan_cfg_out->tlv_buf);
/* Add the size of the channel tlv header and the data
length */
scan_cfg_out->tlv_buf_len +=
(sizeof(chan_tlv_out->header)
+ le16_to_cpu(chan_tlv_out->header.len));
/* Increment the index to the channel tlv we are
constructing */
tlv_idx++;
/* Count the total scan time per command */
total_scan_time +=
le16_to_cpu(tmp_chan_list->max_scan_time);
done_early = false;
/* Stop the loop if the *current* channel is in the
1,6,11 set and we are not filtering on a BSSID
or SSID. */
if (!filtered_scan &&
(tmp_chan_list->chan_number == 1 ||
tmp_chan_list->chan_number == 6 ||
tmp_chan_list->chan_number == 11))
done_early = true;
/* Increment the tmp pointer to the next channel to
be scanned */
tmp_chan_list++;
/* Stop the loop if the *next* channel is in the 1,6,11
set. This will cause it to be the only channel
scanned on the next interation */
if (!filtered_scan &&
(tmp_chan_list->chan_number == 1 ||
tmp_chan_list->chan_number == 6 ||
tmp_chan_list->chan_number == 11))
done_early = true;
}
/* The total scan time should be less than scan command timeout
value */
if (total_scan_time > MWIFIEX_MAX_TOTAL_SCAN_TIME) {
mwifiex_dbg(priv->adapter, ERROR,
"total scan time %dms\t"
"is over limit (%dms), scan skipped\n",
total_scan_time,
MWIFIEX_MAX_TOTAL_SCAN_TIME);
ret = -1;
break;
}
rates_size = mwifiex_append_rate_tlv(priv, scan_cfg_out,
radio_type);
priv->adapter->scan_channels = start_chan;
/* Send the scan command to the firmware with the specified
cfg */
if (priv->adapter->ext_scan)
cmd_no = HostCmd_CMD_802_11_SCAN_EXT;
else
cmd_no = HostCmd_CMD_802_11_SCAN;
ret = mwifiex_send_cmd(priv, cmd_no, HostCmd_ACT_GEN_SET,
0, scan_cfg_out, false);
/* rate IE is updated per scan command but same starting
* pointer is used each time so that rate IE from earlier
* scan_cfg_out->buf is overwritten with new one.
*/
scan_cfg_out->tlv_buf_len -=
sizeof(struct mwifiex_ie_types_header) + rates_size;
if (ret) {
mwifiex_cancel_pending_scan_cmd(adapter);
break;
}
}
if (ret)
return -1;
return 0;
}
/*
* This function constructs a scan command configuration structure to use
* in scan commands.
*
* Application layer or other functions can invoke network scanning
* with a scan configuration supplied in a user scan configuration structure.
* This structure is used as the basis of one or many scan command configuration
* commands that are sent to the command processing module and eventually to the
* firmware.
*
* This function creates a scan command configuration structure based on the
* following user supplied parameters (if present):
* - SSID filter
* - BSSID filter
* - Number of Probes to be sent
* - Channel list
*
* If the SSID or BSSID filter is not present, the filter is disabled/cleared.
* If the number of probes is not set, adapter default setting is used.
*/
static void
mwifiex_config_scan(struct mwifiex_private *priv,
const struct mwifiex_user_scan_cfg *user_scan_in,
struct mwifiex_scan_cmd_config *scan_cfg_out,
struct mwifiex_ie_types_chan_list_param_set **chan_list_out,
struct mwifiex_chan_scan_param_set *scan_chan_list,
u8 *max_chan_per_scan, u8 *filtered_scan,
u8 *scan_current_only)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_ie_types_num_probes *num_probes_tlv;
struct mwifiex_ie_types_scan_chan_gap *chan_gap_tlv;
struct mwifiex_ie_types_random_mac *random_mac_tlv;
struct mwifiex_ie_types_wildcard_ssid_params *wildcard_ssid_tlv;
struct mwifiex_ie_types_bssid_list *bssid_tlv;
u8 *tlv_pos;
u32 num_probes;
u32 ssid_len;
u32 chan_idx;
u32 scan_type;
u16 scan_dur;
u8 channel;
u8 radio_type;
int i;
u8 ssid_filter;
struct mwifiex_ie_types_htcap *ht_cap;
struct mwifiex_ie_types_bss_mode *bss_mode;
const u8 zero_mac[6] = {0, 0, 0, 0, 0, 0};
/* The tlv_buf_len is calculated for each scan command. The TLVs added
in this routine will be preserved since the routine that sends the
command will append channelTLVs at *chan_list_out. The difference
between the *chan_list_out and the tlv_buf start will be used to
calculate the size of anything we add in this routine. */
scan_cfg_out->tlv_buf_len = 0;
/* Running tlv pointer. Assigned to chan_list_out at end of function
so later routines know where channels can be added to the command
buf */
tlv_pos = scan_cfg_out->tlv_buf;
/* Initialize the scan as un-filtered; the flag is later set to TRUE
below if a SSID or BSSID filter is sent in the command */
*filtered_scan = false;
/* Initialize the scan as not being only on the current channel. If
the channel list is customized, only contains one channel, and is
the active channel, this is set true and data flow is not halted. */
*scan_current_only = false;
if (user_scan_in) {
u8 tmpaddr[ETH_ALEN];
/* Default the ssid_filter flag to TRUE, set false under
certain wildcard conditions and qualified by the existence
of an SSID list before marking the scan as filtered */
ssid_filter = true;
/* Set the BSS type scan filter, use Adapter setting if
unset */
scan_cfg_out->bss_mode =
(u8)(user_scan_in->bss_mode ?: adapter->scan_mode);
/* Set the number of probes to send, use Adapter setting
if unset */
num_probes = user_scan_in->num_probes ?: adapter->scan_probes;
/*
* Set the BSSID filter to the incoming configuration,
* if non-zero. If not set, it will remain disabled
* (all zeros).
*/
memcpy(scan_cfg_out->specific_bssid,
user_scan_in->specific_bssid,
sizeof(scan_cfg_out->specific_bssid));
memcpy(tmpaddr, scan_cfg_out->specific_bssid, ETH_ALEN);
if (adapter->ext_scan &&
!is_zero_ether_addr(tmpaddr)) {
bssid_tlv =
(struct mwifiex_ie_types_bssid_list *)tlv_pos;
bssid_tlv->header.type = cpu_to_le16(TLV_TYPE_BSSID);
bssid_tlv->header.len = cpu_to_le16(ETH_ALEN);
memcpy(bssid_tlv->bssid, user_scan_in->specific_bssid,
ETH_ALEN);
tlv_pos += sizeof(struct mwifiex_ie_types_bssid_list);
}
for (i = 0; i < user_scan_in->num_ssids; i++) {
ssid_len = user_scan_in->ssid_list[i].ssid_len;
wildcard_ssid_tlv =
(struct mwifiex_ie_types_wildcard_ssid_params *)
tlv_pos;
wildcard_ssid_tlv->header.type =
cpu_to_le16(TLV_TYPE_WILDCARDSSID);
wildcard_ssid_tlv->header.len = cpu_to_le16(
(u16) (ssid_len + sizeof(wildcard_ssid_tlv->
max_ssid_length)));
/*
* max_ssid_length = 0 tells firmware to perform
* specific scan for the SSID filled, whereas
* max_ssid_length = IEEE80211_MAX_SSID_LEN is for
* wildcard scan.
*/
if (ssid_len)
wildcard_ssid_tlv->max_ssid_length = 0;
else
wildcard_ssid_tlv->max_ssid_length =
IEEE80211_MAX_SSID_LEN;
if (!memcmp(user_scan_in->ssid_list[i].ssid,
"DIRECT-", 7))
wildcard_ssid_tlv->max_ssid_length = 0xfe;
memcpy(wildcard_ssid_tlv->ssid,
user_scan_in->ssid_list[i].ssid, ssid_len);
tlv_pos += (sizeof(wildcard_ssid_tlv->header)
+ le16_to_cpu(wildcard_ssid_tlv->header.len));
mwifiex_dbg(adapter, INFO,
"info: scan: ssid[%d]: %s, %d\n",
i, wildcard_ssid_tlv->ssid,
wildcard_ssid_tlv->max_ssid_length);
/* Empty wildcard ssid with a maxlen will match many or
potentially all SSIDs (maxlen == 32), therefore do
not treat the scan as
filtered. */
if (!ssid_len && wildcard_ssid_tlv->max_ssid_length)
ssid_filter = false;
}
/*
* The default number of channels sent in the command is low to
* ensure the response buffer from the firmware does not
* truncate scan results. That is not an issue with an SSID
* or BSSID filter applied to the scan results in the firmware.
*/
memcpy(tmpaddr, scan_cfg_out->specific_bssid, ETH_ALEN);
if ((i && ssid_filter) ||
!is_zero_ether_addr(tmpaddr))
*filtered_scan = true;
if (user_scan_in->scan_chan_gap) {
mwifiex_dbg(adapter, INFO,
"info: scan: channel gap = %d\n",
user_scan_in->scan_chan_gap);
*max_chan_per_scan =
MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN;
chan_gap_tlv = (void *)tlv_pos;
chan_gap_tlv->header.type =
cpu_to_le16(TLV_TYPE_SCAN_CHANNEL_GAP);
chan_gap_tlv->header.len =
cpu_to_le16(sizeof(chan_gap_tlv->chan_gap));
chan_gap_tlv->chan_gap =
cpu_to_le16((user_scan_in->scan_chan_gap));
tlv_pos +=
sizeof(struct mwifiex_ie_types_scan_chan_gap);
}
if (!ether_addr_equal(user_scan_in->random_mac, zero_mac)) {
random_mac_tlv = (void *)tlv_pos;
random_mac_tlv->header.type =
cpu_to_le16(TLV_TYPE_RANDOM_MAC);
random_mac_tlv->header.len =
cpu_to_le16(sizeof(random_mac_tlv->mac));
ether_addr_copy(random_mac_tlv->mac,
user_scan_in->random_mac);
tlv_pos +=
sizeof(struct mwifiex_ie_types_random_mac);
}
} else {
scan_cfg_out->bss_mode = (u8) adapter->scan_mode;
num_probes = adapter->scan_probes;
}
/*
* If a specific BSSID or SSID is used, the number of channels in the
* scan command will be increased to the absolute maximum.
*/
if (*filtered_scan) {
*max_chan_per_scan = MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN;
} else {
if (!priv->media_connected)
*max_chan_per_scan = MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD;
else
*max_chan_per_scan =
MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD / 2;
}
if (adapter->ext_scan) {
bss_mode = (struct mwifiex_ie_types_bss_mode *)tlv_pos;
bss_mode->header.type = cpu_to_le16(TLV_TYPE_BSS_MODE);
bss_mode->header.len = cpu_to_le16(sizeof(bss_mode->bss_mode));
bss_mode->bss_mode = scan_cfg_out->bss_mode;
tlv_pos += sizeof(bss_mode->header) +
le16_to_cpu(bss_mode->header.len);
}
/* If the input config or adapter has the number of Probes set,
add tlv */
if (num_probes) {
mwifiex_dbg(adapter, INFO,
"info: scan: num_probes = %d\n",
num_probes);
num_probes_tlv = (struct mwifiex_ie_types_num_probes *) tlv_pos;
num_probes_tlv->header.type = cpu_to_le16(TLV_TYPE_NUMPROBES);
num_probes_tlv->header.len =
cpu_to_le16(sizeof(num_probes_tlv->num_probes));
num_probes_tlv->num_probes = cpu_to_le16((u16) num_probes);
tlv_pos += sizeof(num_probes_tlv->header) +
le16_to_cpu(num_probes_tlv->header.len);
}
if (ISSUPP_11NENABLED(priv->adapter->fw_cap_info) &&
(priv->adapter->config_bands & BAND_GN ||
priv->adapter->config_bands & BAND_AN)) {
ht_cap = (struct mwifiex_ie_types_htcap *) tlv_pos;
memset(ht_cap, 0, sizeof(struct mwifiex_ie_types_htcap));
ht_cap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY);
ht_cap->header.len =
cpu_to_le16(sizeof(struct ieee80211_ht_cap));
radio_type =
mwifiex_band_to_radio_type(priv->adapter->config_bands);
mwifiex_fill_cap_info(priv, radio_type, &ht_cap->ht_cap);
tlv_pos += sizeof(struct mwifiex_ie_types_htcap);
}
/* Append vendor specific IE TLV */
mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_SCAN, &tlv_pos);
/*
* Set the output for the channel TLV to the address in the tlv buffer
* past any TLVs that were added in this function (SSID, num_probes).
* Channel TLVs will be added past this for each scan command,
* preserving the TLVs that were previously added.
*/
*chan_list_out =
(struct mwifiex_ie_types_chan_list_param_set *) tlv_pos;
if (user_scan_in && user_scan_in->chan_list[0].chan_number) {
mwifiex_dbg(adapter, INFO,
"info: Scan: Using supplied channel list\n");
for (chan_idx = 0;
chan_idx < MWIFIEX_USER_SCAN_CHAN_MAX &&
user_scan_in->chan_list[chan_idx].chan_number;
chan_idx++) {
channel = user_scan_in->chan_list[chan_idx].chan_number;
scan_chan_list[chan_idx].chan_number = channel;
radio_type =
user_scan_in->chan_list[chan_idx].radio_type;
scan_chan_list[chan_idx].radio_type = radio_type;
scan_type = user_scan_in->chan_list[chan_idx].scan_type;
if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE)
scan_chan_list[chan_idx].chan_scan_mode_bitmap
|= (MWIFIEX_PASSIVE_SCAN |
MWIFIEX_HIDDEN_SSID_REPORT);
else
scan_chan_list[chan_idx].chan_scan_mode_bitmap
&= ~MWIFIEX_PASSIVE_SCAN;
scan_chan_list[chan_idx].chan_scan_mode_bitmap
|= MWIFIEX_DISABLE_CHAN_FILT;
if (user_scan_in->chan_list[chan_idx].scan_time) {
scan_dur = (u16) user_scan_in->
chan_list[chan_idx].scan_time;
} else {
if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE)
scan_dur = adapter->passive_scan_time;
else if (*filtered_scan)
scan_dur = adapter->specific_scan_time;
else
scan_dur = adapter->active_scan_time;
}
scan_chan_list[chan_idx].min_scan_time =
cpu_to_le16(scan_dur);
scan_chan_list[chan_idx].max_scan_time =
cpu_to_le16(scan_dur);
}
/* Check if we are only scanning the current channel */
if ((chan_idx == 1) &&
(user_scan_in->chan_list[0].chan_number ==
priv->curr_bss_params.bss_descriptor.channel)) {
*scan_current_only = true;
mwifiex_dbg(adapter, INFO,
"info: Scan: Scanning current channel only\n");
}
} else {
mwifiex_dbg(adapter, INFO,
"info: Scan: Creating full region channel list\n");
mwifiex_scan_create_channel_list(priv, user_scan_in,
scan_chan_list,
*filtered_scan);
}
}
/*
* This function inspects the scan response buffer for pointers to
* expected TLVs.
*
* TLVs can be included at the end of the scan response BSS information.
*
* Data in the buffer is parsed pointers to TLVs that can potentially
* be passed back in the response.
*/
static void
mwifiex_ret_802_11_scan_get_tlv_ptrs(struct mwifiex_adapter *adapter,
struct mwifiex_ie_types_data *tlv,
u32 tlv_buf_size, u32 req_tlv_type,
struct mwifiex_ie_types_data **tlv_data)
{
struct mwifiex_ie_types_data *current_tlv;
u32 tlv_buf_left;
u32 tlv_type;
u32 tlv_len;
current_tlv = tlv;
tlv_buf_left = tlv_buf_size;
*tlv_data = NULL;
mwifiex_dbg(adapter, INFO,
"info: SCAN_RESP: tlv_buf_size = %d\n",
tlv_buf_size);
while (tlv_buf_left >= sizeof(struct mwifiex_ie_types_header)) {
tlv_type = le16_to_cpu(current_tlv->header.type);
tlv_len = le16_to_cpu(current_tlv->header.len);
if (sizeof(tlv->header) + tlv_len > tlv_buf_left) {
mwifiex_dbg(adapter, ERROR,
"SCAN_RESP: TLV buffer corrupt\n");
break;
}
if (req_tlv_type == tlv_type) {
switch (tlv_type) {
case TLV_TYPE_TSFTIMESTAMP:
mwifiex_dbg(adapter, INFO,
"info: SCAN_RESP: TSF\t"
"timestamp TLV, len = %d\n",
tlv_len);
*tlv_data = current_tlv;
break;
case TLV_TYPE_CHANNELBANDLIST:
mwifiex_dbg(adapter, INFO,
"info: SCAN_RESP: channel\t"
"band list TLV, len = %d\n",
tlv_len);
*tlv_data = current_tlv;
break;
default:
mwifiex_dbg(adapter, ERROR,
"SCAN_RESP: unhandled TLV = %d\n",
tlv_type);
/* Give up, this seems corrupted */
return;
}
}
if (*tlv_data)
break;
tlv_buf_left -= (sizeof(tlv->header) + tlv_len);
current_tlv =
(struct mwifiex_ie_types_data *) (current_tlv->data +
tlv_len);
} /* while */
}
/*
* This function parses provided beacon buffer and updates
* respective fields in bss descriptor structure.
*/
int mwifiex_update_bss_desc_with_ie(struct mwifiex_adapter *adapter,
struct mwifiex_bssdescriptor *bss_entry)
{
int ret = 0;
u8 element_id;
struct ieee_types_fh_param_set *fh_param_set;
struct ieee_types_ds_param_set *ds_param_set;
struct ieee_types_cf_param_set *cf_param_set;
struct ieee_types_ibss_param_set *ibss_param_set;
u8 *current_ptr;
u8 *rate;
u8 element_len;
u16 total_ie_len;
u8 bytes_to_copy;
u8 rate_size;
u8 found_data_rate_ie;
u32 bytes_left;
struct ieee_types_vendor_specific *vendor_ie;
const u8 wpa_oui[4] = { 0x00, 0x50, 0xf2, 0x01 };
const u8 wmm_oui[4] = { 0x00, 0x50, 0xf2, 0x02 };
found_data_rate_ie = false;
rate_size = 0;
current_ptr = bss_entry->beacon_buf;
bytes_left = bss_entry->beacon_buf_size;
/* Process variable IE */
while (bytes_left >= 2) {
element_id = *current_ptr;
element_len = *(current_ptr + 1);
total_ie_len = element_len + sizeof(struct ieee_types_header);
if (bytes_left < total_ie_len) {
mwifiex_dbg(adapter, ERROR,
"err: InterpretIE: in processing\t"
"IE, bytes left < IE length\n");
return -EINVAL;
}
switch (element_id) {
case WLAN_EID_SSID:
if (element_len > IEEE80211_MAX_SSID_LEN)
return -EINVAL;
bss_entry->ssid.ssid_len = element_len;
memcpy(bss_entry->ssid.ssid, (current_ptr + 2),
element_len);
mwifiex_dbg(adapter, INFO,
"info: InterpretIE: ssid: %-32s\n",
bss_entry->ssid.ssid);
break;
case WLAN_EID_SUPP_RATES:
if (element_len > MWIFIEX_SUPPORTED_RATES)
return -EINVAL;
memcpy(bss_entry->data_rates, current_ptr + 2,
element_len);
memcpy(bss_entry->supported_rates, current_ptr + 2,
element_len);
rate_size = element_len;
found_data_rate_ie = true;
break;
case WLAN_EID_FH_PARAMS:
if (total_ie_len < sizeof(*fh_param_set))
return -EINVAL;
fh_param_set =
(struct ieee_types_fh_param_set *) current_ptr;
memcpy(&bss_entry->phy_param_set.fh_param_set,
fh_param_set,
sizeof(struct ieee_types_fh_param_set));
break;
case WLAN_EID_DS_PARAMS:
if (total_ie_len < sizeof(*ds_param_set))
return -EINVAL;
ds_param_set =
(struct ieee_types_ds_param_set *) current_ptr;
bss_entry->channel = ds_param_set->current_chan;
memcpy(&bss_entry->phy_param_set.ds_param_set,
ds_param_set,
sizeof(struct ieee_types_ds_param_set));
break;
case WLAN_EID_CF_PARAMS:
if (total_ie_len < sizeof(*cf_param_set))
return -EINVAL;
cf_param_set =
(struct ieee_types_cf_param_set *) current_ptr;
memcpy(&bss_entry->ss_param_set.cf_param_set,
cf_param_set,
sizeof(struct ieee_types_cf_param_set));
break;
case WLAN_EID_IBSS_PARAMS:
if (total_ie_len < sizeof(*ibss_param_set))
return -EINVAL;
ibss_param_set =
(struct ieee_types_ibss_param_set *)
current_ptr;
memcpy(&bss_entry->ss_param_set.ibss_param_set,
ibss_param_set,
sizeof(struct ieee_types_ibss_param_set));
break;
case WLAN_EID_ERP_INFO:
if (!element_len)
return -EINVAL;
bss_entry->erp_flags = *(current_ptr + 2);
break;
case WLAN_EID_PWR_CONSTRAINT:
if (!element_len)
return -EINVAL;
bss_entry->local_constraint = *(current_ptr + 2);
bss_entry->sensed_11h = true;
break;
case WLAN_EID_CHANNEL_SWITCH:
bss_entry->chan_sw_ie_present = true;
/* fall through */
case WLAN_EID_PWR_CAPABILITY:
case WLAN_EID_TPC_REPORT:
case WLAN_EID_QUIET:
bss_entry->sensed_11h = true;
break;
case WLAN_EID_EXT_SUPP_RATES:
/*
* Only process extended supported rate
* if data rate is already found.
* Data rate IE should come before
* extended supported rate IE
*/
if (found_data_rate_ie) {
if ((element_len + rate_size) >
MWIFIEX_SUPPORTED_RATES)
bytes_to_copy =
(MWIFIEX_SUPPORTED_RATES -
rate_size);
else
bytes_to_copy = element_len;
rate = (u8 *) bss_entry->data_rates;
rate += rate_size;
memcpy(rate, current_ptr + 2, bytes_to_copy);
rate = (u8 *) bss_entry->supported_rates;
rate += rate_size;
memcpy(rate, current_ptr + 2, bytes_to_copy);
}
break;
case WLAN_EID_VENDOR_SPECIFIC:
vendor_ie = (struct ieee_types_vendor_specific *)
current_ptr;
/* 802.11 requires at least 3-byte OUI. */
if (element_len < sizeof(vendor_ie->vend_hdr.oui.oui))
return -EINVAL;
/* Not long enough for a match? Skip it. */
if (element_len < sizeof(wpa_oui))
break;
if (!memcmp(&vendor_ie->vend_hdr.oui, wpa_oui,
sizeof(wpa_oui))) {
bss_entry->bcn_wpa_ie =
(struct ieee_types_vendor_specific *)
current_ptr;
bss_entry->wpa_offset = (u16)
(current_ptr - bss_entry->beacon_buf);
} else if (!memcmp(&vendor_ie->vend_hdr.oui, wmm_oui,
sizeof(wmm_oui))) {
if (total_ie_len ==
sizeof(struct ieee_types_wmm_parameter) ||
total_ie_len ==
sizeof(struct ieee_types_wmm_info))
/*
* Only accept and copy the WMM IE if
* it matches the size expected for the
* WMM Info IE or the WMM Parameter IE.
*/
memcpy((u8 *) &bss_entry->wmm_ie,
current_ptr, total_ie_len);
}
break;
case WLAN_EID_RSN:
bss_entry->bcn_rsn_ie =
(struct ieee_types_generic *) current_ptr;
bss_entry->rsn_offset = (u16) (current_ptr -
bss_entry->beacon_buf);
break;
case WLAN_EID_BSS_AC_ACCESS_DELAY:
bss_entry->bcn_wapi_ie =
(struct ieee_types_generic *) current_ptr;
bss_entry->wapi_offset = (u16) (current_ptr -
bss_entry->beacon_buf);
break;
case WLAN_EID_HT_CAPABILITY:
bss_entry->bcn_ht_cap = (struct ieee80211_ht_cap *)
(current_ptr +
sizeof(struct ieee_types_header));
bss_entry->ht_cap_offset = (u16) (current_ptr +
sizeof(struct ieee_types_header) -
bss_entry->beacon_buf);
break;
case WLAN_EID_HT_OPERATION:
bss_entry->bcn_ht_oper =
(struct ieee80211_ht_operation *)(current_ptr +
sizeof(struct ieee_types_header));
bss_entry->ht_info_offset = (u16) (current_ptr +
sizeof(struct ieee_types_header) -
bss_entry->beacon_buf);
break;
case WLAN_EID_VHT_CAPABILITY:
bss_entry->disable_11ac = false;
bss_entry->bcn_vht_cap =
(void *)(current_ptr +
sizeof(struct ieee_types_header));
bss_entry->vht_cap_offset =
(u16)((u8 *)bss_entry->bcn_vht_cap -
bss_entry->beacon_buf);
break;
case WLAN_EID_VHT_OPERATION:
bss_entry->bcn_vht_oper =
(void *)(current_ptr +
sizeof(struct ieee_types_header));
bss_entry->vht_info_offset =
(u16)((u8 *)bss_entry->bcn_vht_oper -
bss_entry->beacon_buf);
break;
case WLAN_EID_BSS_COEX_2040:
bss_entry->bcn_bss_co_2040 = current_ptr;
bss_entry->bss_co_2040_offset =
(u16) (current_ptr - bss_entry->beacon_buf);
break;
case WLAN_EID_EXT_CAPABILITY:
bss_entry->bcn_ext_cap = current_ptr;
bss_entry->ext_cap_offset =
(u16) (current_ptr - bss_entry->beacon_buf);
break;
case WLAN_EID_OPMODE_NOTIF:
bss_entry->oper_mode = (void *)current_ptr;
bss_entry->oper_mode_offset =
(u16)((u8 *)bss_entry->oper_mode -
bss_entry->beacon_buf);
break;
default:
break;
}
current_ptr += total_ie_len;
bytes_left -= total_ie_len;
} /* while (bytes_left > 2) */
return ret;
}
/*
* This function converts radio type scan parameter to a band configuration
* to be used in join command.
*/
static u8
mwifiex_radio_type_to_band(u8 radio_type)
{
switch (radio_type) {
case HostCmd_SCAN_RADIO_TYPE_A:
return BAND_A;
case HostCmd_SCAN_RADIO_TYPE_BG:
default:
return BAND_G;
}
}
/*
* This is an internal function used to start a scan based on an input
* configuration.
*
* This uses the input user scan configuration information when provided in
* order to send the appropriate scan commands to firmware to populate or
* update the internal driver scan table.
*/
int mwifiex_scan_networks(struct mwifiex_private *priv,
const struct mwifiex_user_scan_cfg *user_scan_in)
{
int ret;
struct mwifiex_adapter *adapter = priv->adapter;
struct cmd_ctrl_node *cmd_node;
union mwifiex_scan_cmd_config_tlv *scan_cfg_out;
struct mwifiex_ie_types_chan_list_param_set *chan_list_out;
struct mwifiex_chan_scan_param_set *scan_chan_list;
u8 filtered_scan;
u8 scan_current_chan_only;
u8 max_chan_per_scan;
if (adapter->scan_processing) {
mwifiex_dbg(adapter, WARN,
"cmd: Scan already in process...\n");
return -EBUSY;
}
if (priv->scan_block) {
mwifiex_dbg(adapter, WARN,
"cmd: Scan is blocked during association...\n");
return -EBUSY;
}
if (test_bit(MWIFIEX_SURPRISE_REMOVED, &adapter->work_flags) ||
test_bit(MWIFIEX_IS_CMD_TIMEDOUT, &adapter->work_flags)) {
mwifiex_dbg(adapter, ERROR,
"Ignore scan. Card removed or firmware in bad state\n");
return -EFAULT;
}
spin_lock_bh(&adapter->mwifiex_cmd_lock);
adapter->scan_processing = true;
spin_unlock_bh(&adapter->mwifiex_cmd_lock);
scan_cfg_out = kzalloc(sizeof(union mwifiex_scan_cmd_config_tlv),
GFP_KERNEL);
if (!scan_cfg_out) {
ret = -ENOMEM;
goto done;
}
scan_chan_list = kcalloc(MWIFIEX_USER_SCAN_CHAN_MAX,
sizeof(struct mwifiex_chan_scan_param_set),
GFP_KERNEL);
if (!scan_chan_list) {
kfree(scan_cfg_out);
ret = -ENOMEM;
goto done;
}
mwifiex_config_scan(priv, user_scan_in, &scan_cfg_out->config,
&chan_list_out, scan_chan_list, &max_chan_per_scan,
&filtered_scan, &scan_current_chan_only);
ret = mwifiex_scan_channel_list(priv, max_chan_per_scan, filtered_scan,
&scan_cfg_out->config, chan_list_out,
scan_chan_list);
/* Get scan command from scan_pending_q and put to cmd_pending_q */
if (!ret) {
spin_lock_bh(&adapter->scan_pending_q_lock);
if (!list_empty(&adapter->scan_pending_q)) {
cmd_node = list_first_entry(&adapter->scan_pending_q,
struct cmd_ctrl_node, list);
list_del(&cmd_node->list);
spin_unlock_bh(&adapter->scan_pending_q_lock);
mwifiex_insert_cmd_to_pending_q(adapter, cmd_node);
queue_work(adapter->workqueue, &adapter->main_work);
/* Perform internal scan synchronously */
if (!priv->scan_request) {
mwifiex_dbg(adapter, INFO,
"wait internal scan\n");
mwifiex_wait_queue_complete(adapter, cmd_node);
}
} else {
spin_unlock_bh(&adapter->scan_pending_q_lock);
}
}
kfree(scan_cfg_out);
kfree(scan_chan_list);
done:
if (ret) {
spin_lock_bh(&adapter->mwifiex_cmd_lock);
adapter->scan_processing = false;
spin_unlock_bh(&adapter->mwifiex_cmd_lock);
}
return ret;
}
/*
* This function prepares a scan command to be sent to the firmware.
*
* This uses the scan command configuration sent to the command processing
* module in command preparation stage to configure a scan command structure
* to send to firmware.
*
* The fixed fields specifying the BSS type and BSSID filters as well as a
* variable number/length of TLVs are sent in the command to firmware.
*
* Preparation also includes -
* - Setting command ID, and proper size
* - Ensuring correct endian-ness
*/
int mwifiex_cmd_802_11_scan(struct host_cmd_ds_command *cmd,
struct mwifiex_scan_cmd_config *scan_cfg)
{
struct host_cmd_ds_802_11_scan *scan_cmd = &cmd->params.scan;
/* Set fixed field variables in scan command */
scan_cmd->bss_mode = scan_cfg->bss_mode;
memcpy(scan_cmd->bssid, scan_cfg->specific_bssid,
sizeof(scan_cmd->bssid));
memcpy(scan_cmd->tlv_buffer, scan_cfg->tlv_buf, scan_cfg->tlv_buf_len);
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_SCAN);
/* Size is equal to the sizeof(fixed portions) + the TLV len + header */
cmd->size = cpu_to_le16((u16) (sizeof(scan_cmd->bss_mode)
+ sizeof(scan_cmd->bssid)
+ scan_cfg->tlv_buf_len + S_DS_GEN));
return 0;
}
/*
* This function checks compatibility of requested network with current
* driver settings.
*/
int mwifiex_check_network_compatibility(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
int ret = -1;
if (!bss_desc)
return -1;
if ((mwifiex_get_cfp(priv, (u8) bss_desc->bss_band,
(u16) bss_desc->channel, 0))) {
switch (priv->bss_mode) {
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_ADHOC:
ret = mwifiex_is_network_compatible(priv, bss_desc,
priv->bss_mode);
if (ret)
mwifiex_dbg(priv->adapter, ERROR,
"Incompatible network settings\n");
break;
default:
ret = 0;
}
}
return ret;
}
/* This function checks if SSID string contains all zeroes or length is zero */
static bool mwifiex_is_hidden_ssid(struct cfg80211_ssid *ssid)
{
int idx;
for (idx = 0; idx < ssid->ssid_len; idx++) {
if (ssid->ssid[idx])
return false;
}
return true;
}
/* This function checks if any hidden SSID found in passive scan channels
* and save those channels for specific SSID active scan
*/
static int mwifiex_save_hidden_ssid_channels(struct mwifiex_private *priv,
struct cfg80211_bss *bss)
{
struct mwifiex_bssdescriptor *bss_desc;
int ret;
int chid;
/* Allocate and fill new bss descriptor */
bss_desc = kzalloc(sizeof(*bss_desc), GFP_KERNEL);
if (!bss_desc)
return -ENOMEM;
ret = mwifiex_fill_new_bss_desc(priv, bss, bss_desc);
if (ret)
goto done;
if (mwifiex_is_hidden_ssid(&bss_desc->ssid)) {
mwifiex_dbg(priv->adapter, INFO, "found hidden SSID\n");
for (chid = 0 ; chid < MWIFIEX_USER_SCAN_CHAN_MAX; chid++) {
if (priv->hidden_chan[chid].chan_number ==
bss->channel->hw_value)
break;
if (!priv->hidden_chan[chid].chan_number) {
priv->hidden_chan[chid].chan_number =
bss->channel->hw_value;
priv->hidden_chan[chid].radio_type =
bss->channel->band;
priv->hidden_chan[chid].scan_type =
MWIFIEX_SCAN_TYPE_ACTIVE;
break;
}
}
}
done:
/* beacon_ie buffer was allocated in function
* mwifiex_fill_new_bss_desc(). Free it now.
*/
kfree(bss_desc->beacon_buf);
kfree(bss_desc);
return 0;
}
static int mwifiex_update_curr_bss_params(struct mwifiex_private *priv,
struct cfg80211_bss *bss)
{
struct mwifiex_bssdescriptor *bss_desc;
int ret;
/* Allocate and fill new bss descriptor */
bss_desc = kzalloc(sizeof(struct mwifiex_bssdescriptor), GFP_KERNEL);
if (!bss_desc)
return -ENOMEM;
ret = mwifiex_fill_new_bss_desc(priv, bss, bss_desc);
if (ret)
goto done;
ret = mwifiex_check_network_compatibility(priv, bss_desc);
if (ret)
goto done;
spin_lock_bh(&priv->curr_bcn_buf_lock);
/* Make a copy of current BSSID descriptor */
memcpy(&priv->curr_bss_params.bss_descriptor, bss_desc,
sizeof(priv->curr_bss_params.bss_descriptor));
/* The contents of beacon_ie will be copied to its own buffer
* in mwifiex_save_curr_bcn()
*/
mwifiex_save_curr_bcn(priv);
spin_unlock_bh(&priv->curr_bcn_buf_lock);
done:
/* beacon_ie buffer was allocated in function
* mwifiex_fill_new_bss_desc(). Free it now.
*/
kfree(bss_desc->beacon_buf);
kfree(bss_desc);
return 0;
}
static int
mwifiex_parse_single_response_buf(struct mwifiex_private *priv, u8 **bss_info,
u32 *bytes_left, u64 fw_tsf, u8 *radio_type,
bool ext_scan, s32 rssi_val)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_chan_freq_power *cfp;
struct cfg80211_bss *bss;
u8 bssid[ETH_ALEN];
s32 rssi;
const u8 *ie_buf;
size_t ie_len;
u16 channel = 0;
u16 beacon_size = 0;
u32 curr_bcn_bytes;
u32 freq;
u16 beacon_period;
u16 cap_info_bitmap;
u8 *current_ptr;
u64 timestamp;
struct mwifiex_fixed_bcn_param *bcn_param;
struct mwifiex_bss_priv *bss_priv;
if (*bytes_left >= sizeof(beacon_size)) {
/* Extract & convert beacon size from command buffer */
beacon_size = get_unaligned_le16((*bss_info));
*bytes_left -= sizeof(beacon_size);
*bss_info += sizeof(beacon_size);
}
if (!beacon_size || beacon_size > *bytes_left) {
*bss_info += *bytes_left;
*bytes_left = 0;
return -EFAULT;
}
/* Initialize the current working beacon pointer for this BSS
* iteration
*/
current_ptr = *bss_info;
/* Advance the return beacon pointer past the current beacon */
*bss_info += beacon_size;
*bytes_left -= beacon_size;
curr_bcn_bytes = beacon_size;
/* First 5 fields are bssid, RSSI(for legacy scan only),
* time stamp, beacon interval, and capability information
*/
if (curr_bcn_bytes < ETH_ALEN + sizeof(u8) +
sizeof(struct mwifiex_fixed_bcn_param)) {
mwifiex_dbg(adapter, ERROR,
"InterpretIE: not enough bytes left\n");
return -EFAULT;
}
memcpy(bssid, current_ptr, ETH_ALEN);
current_ptr += ETH_ALEN;
curr_bcn_bytes -= ETH_ALEN;
if (!ext_scan) {
rssi = (s32) *current_ptr;
rssi = (-rssi) * 100; /* Convert dBm to mBm */
current_ptr += sizeof(u8);
curr_bcn_bytes -= sizeof(u8);
mwifiex_dbg(adapter, INFO,
"info: InterpretIE: RSSI=%d\n", rssi);
} else {
rssi = rssi_val;
}
bcn_param = (struct mwifiex_fixed_bcn_param *)current_ptr;
current_ptr += sizeof(*bcn_param);
curr_bcn_bytes -= sizeof(*bcn_param);
timestamp = le64_to_cpu(bcn_param->timestamp);
beacon_period = le16_to_cpu(bcn_param->beacon_period);
cap_info_bitmap = le16_to_cpu(bcn_param->cap_info_bitmap);
mwifiex_dbg(adapter, INFO,
"info: InterpretIE: capabilities=0x%X\n",
cap_info_bitmap);
/* Rest of the current buffer are IE's */
ie_buf = current_ptr;
ie_len = curr_bcn_bytes;
mwifiex_dbg(adapter, INFO,
"info: InterpretIE: IELength for this AP = %d\n",
curr_bcn_bytes);
while (curr_bcn_bytes >= sizeof(struct ieee_types_header)) {
u8 element_id, element_len;
element_id = *current_ptr;
element_len = *(current_ptr + 1);
if (curr_bcn_bytes < element_len +
sizeof(struct ieee_types_header)) {
mwifiex_dbg(adapter, ERROR,
"%s: bytes left < IE length\n", __func__);
return -EFAULT;
}
if (element_id == WLAN_EID_DS_PARAMS) {
channel = *(current_ptr +
sizeof(struct ieee_types_header));
break;
}
current_ptr += element_len + sizeof(struct ieee_types_header);
curr_bcn_bytes -= element_len +
sizeof(struct ieee_types_header);
}
if (channel) {
struct ieee80211_channel *chan;
u8 band;
/* Skip entry if on csa closed channel */
if (channel == priv->csa_chan) {
mwifiex_dbg(adapter, WARN,
"Dropping entry on csa closed channel\n");
return 0;
}
band = BAND_G;
if (radio_type)
band = mwifiex_radio_type_to_band(*radio_type &
(BIT(0) | BIT(1)));
cfp = mwifiex_get_cfp(priv, band, channel, 0);
freq = cfp ? cfp->freq : 0;
chan = ieee80211_get_channel(priv->wdev.wiphy, freq);
if (chan && !(chan->flags & IEEE80211_CHAN_DISABLED)) {
bss = cfg80211_inform_bss(priv->wdev.wiphy,
chan, CFG80211_BSS_FTYPE_UNKNOWN,
bssid, timestamp,
cap_info_bitmap, beacon_period,
ie_buf, ie_len, rssi, GFP_KERNEL);
if (bss) {
bss_priv = (struct mwifiex_bss_priv *)bss->priv;
bss_priv->band = band;
bss_priv->fw_tsf = fw_tsf;
if (priv->media_connected &&
!memcmp(bssid, priv->curr_bss_params.
bss_descriptor.mac_address,
ETH_ALEN))
mwifiex_update_curr_bss_params(priv,
bss);
if ((chan->flags & IEEE80211_CHAN_RADAR) ||
(chan->flags & IEEE80211_CHAN_NO_IR)) {
mwifiex_dbg(adapter, INFO,
"radar or passive channel %d\n",
channel);
mwifiex_save_hidden_ssid_channels(priv,
bss);
}
cfg80211_put_bss(priv->wdev.wiphy, bss);
}
}
} else {
mwifiex_dbg(adapter, WARN, "missing BSS channel IE\n");
}
return 0;
}
static void mwifiex_complete_scan(struct mwifiex_private *priv)
{
struct mwifiex_adapter *adapter = priv->adapter;
adapter->survey_idx = 0;
if (adapter->curr_cmd->wait_q_enabled) {
adapter->cmd_wait_q.status = 0;
if (!priv->scan_request) {
mwifiex_dbg(adapter, INFO,
"complete internal scan\n");
mwifiex_complete_cmd(adapter, adapter->curr_cmd);
}
}
}
/* This function checks if any hidden SSID found in passive scan channels
* and do specific SSID active scan for those channels
*/
static int
mwifiex_active_scan_req_for_passive_chan(struct mwifiex_private *priv)
{
int ret;
struct mwifiex_adapter *adapter = priv->adapter;
u8 id = 0;
struct mwifiex_user_scan_cfg *user_scan_cfg;
if (adapter->active_scan_triggered || !priv->scan_request ||
priv->scan_aborting) {
adapter->active_scan_triggered = false;
return 0;
}
if (!priv->hidden_chan[0].chan_number) {
mwifiex_dbg(adapter, INFO, "No BSS with hidden SSID found on DFS channels\n");
return 0;
}
user_scan_cfg = kzalloc(sizeof(*user_scan_cfg), GFP_KERNEL);
if (!user_scan_cfg)
return -ENOMEM;
for (id = 0; id < MWIFIEX_USER_SCAN_CHAN_MAX; id++) {
if (!priv->hidden_chan[id].chan_number)
break;
memcpy(&user_scan_cfg->chan_list[id],
&priv->hidden_chan[id],
sizeof(struct mwifiex_user_scan_chan));
}
adapter->active_scan_triggered = true;
if (priv->scan_request->flags & NL80211_SCAN_FLAG_RANDOM_ADDR)
ether_addr_copy(user_scan_cfg->random_mac,
priv->scan_request->mac_addr);
user_scan_cfg->num_ssids = priv->scan_request->n_ssids;
user_scan_cfg->ssid_list = priv->scan_request->ssids;
ret = mwifiex_scan_networks(priv, user_scan_cfg);
kfree(user_scan_cfg);
memset(&priv->hidden_chan, 0, sizeof(priv->hidden_chan));
if (ret) {
dev_err(priv->adapter->dev, "scan failed: %d\n", ret);
return ret;
}
return 0;
}
static void mwifiex_check_next_scan_command(struct mwifiex_private *priv)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct cmd_ctrl_node *cmd_node;
spin_lock_bh(&adapter->scan_pending_q_lock);
if (list_empty(&adapter->scan_pending_q)) {
spin_unlock_bh(&adapter->scan_pending_q_lock);
spin_lock_bh(&adapter->mwifiex_cmd_lock);
adapter->scan_processing = false;
spin_unlock_bh(&adapter->mwifiex_cmd_lock);
mwifiex_active_scan_req_for_passive_chan(priv);
if (!adapter->ext_scan)
mwifiex_complete_scan(priv);
if (priv->scan_request) {
struct cfg80211_scan_info info = {
.aborted = false,
};
mwifiex_dbg(adapter, INFO,
"info: notifying scan done\n");
cfg80211_scan_done(priv->scan_request, &info);
priv->scan_request = NULL;
priv->scan_aborting = false;
} else {
priv->scan_aborting = false;
mwifiex_dbg(adapter, INFO,
"info: scan already aborted\n");
}
} else if ((priv->scan_aborting && !priv->scan_request) ||
priv->scan_block) {
spin_unlock_bh(&adapter->scan_pending_q_lock);
mwifiex_cancel_pending_scan_cmd(adapter);
spin_lock_bh(&adapter->mwifiex_cmd_lock);
adapter->scan_processing = false;
spin_unlock_bh(&adapter->mwifiex_cmd_lock);
if (!adapter->active_scan_triggered) {
if (priv->scan_request) {
struct cfg80211_scan_info info = {
.aborted = true,
};
mwifiex_dbg(adapter, INFO,
"info: aborting scan\n");
cfg80211_scan_done(priv->scan_request, &info);
priv->scan_request = NULL;
priv->scan_aborting = false;
} else {
priv->scan_aborting = false;
mwifiex_dbg(adapter, INFO,
"info: scan already aborted\n");
}
}
} else {
/* Get scan command from scan_pending_q and put to
* cmd_pending_q
*/
cmd_node = list_first_entry(&adapter->scan_pending_q,
struct cmd_ctrl_node, list);
list_del(&cmd_node->list);
spin_unlock_bh(&adapter->scan_pending_q_lock);
mwifiex_insert_cmd_to_pending_q(adapter, cmd_node);
}
return;
}
void mwifiex_cancel_scan(struct mwifiex_adapter *adapter)
{
struct mwifiex_private *priv;
int i;
mwifiex_cancel_pending_scan_cmd(adapter);
if (adapter->scan_processing) {
spin_lock_bh(&adapter->mwifiex_cmd_lock);
adapter->scan_processing = false;
spin_unlock_bh(&adapter->mwifiex_cmd_lock);
for (i = 0; i < adapter->priv_num; i++) {
priv = adapter->priv[i];
if (!priv)
continue;
if (priv->scan_request) {
struct cfg80211_scan_info info = {
.aborted = true,
};
mwifiex_dbg(adapter, INFO,
"info: aborting scan\n");
cfg80211_scan_done(priv->scan_request, &info);
priv->scan_request = NULL;
priv->scan_aborting = false;
}
}
}
}
/*
* This function handles the command response of scan.
*
* The response buffer for the scan command has the following
* memory layout:
*
* .-------------------------------------------------------------.
* | Header (4 * sizeof(t_u16)): Standard command response hdr |
* .-------------------------------------------------------------.
* | BufSize (t_u16) : sizeof the BSS Description data |
* .-------------------------------------------------------------.
* | NumOfSet (t_u8) : Number of BSS Descs returned |
* .-------------------------------------------------------------.
* | BSSDescription data (variable, size given in BufSize) |
* .-------------------------------------------------------------.
* | TLV data (variable, size calculated using Header->Size, |
* | BufSize and sizeof the fixed fields above) |
* .-------------------------------------------------------------.
*/
int mwifiex_ret_802_11_scan(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
int ret = 0;
struct mwifiex_adapter *adapter = priv->adapter;
struct host_cmd_ds_802_11_scan_rsp *scan_rsp;
struct mwifiex_ie_types_data *tlv_data;
struct mwifiex_ie_types_tsf_timestamp *tsf_tlv;
u8 *bss_info;
u32 scan_resp_size;
u32 bytes_left;
u32 idx;
u32 tlv_buf_size;
struct mwifiex_ie_types_chan_band_list_param_set *chan_band_tlv;
struct chan_band_param_set *chan_band;
u8 is_bgscan_resp;
__le64 fw_tsf = 0;
u8 *radio_type;
struct cfg80211_wowlan_nd_match *pmatch;
struct cfg80211_sched_scan_request *nd_config = NULL;
is_bgscan_resp = (le16_to_cpu(resp->command)
== HostCmd_CMD_802_11_BG_SCAN_QUERY);
if (is_bgscan_resp)
scan_rsp = &resp->params.bg_scan_query_resp.scan_resp;
else
scan_rsp = &resp->params.scan_resp;
if (scan_rsp->number_of_sets > MWIFIEX_MAX_AP) {
mwifiex_dbg(adapter, ERROR,
"SCAN_RESP: too many AP returned (%d)\n",
scan_rsp->number_of_sets);
ret = -1;
goto check_next_scan;
}
/* Check csa channel expiry before parsing scan response */
mwifiex_11h_get_csa_closed_channel(priv);
bytes_left = le16_to_cpu(scan_rsp->bss_descript_size);
mwifiex_dbg(adapter, INFO,
"info: SCAN_RESP: bss_descript_size %d\n",
bytes_left);
scan_resp_size = le16_to_cpu(resp->size);
mwifiex_dbg(adapter, INFO,
"info: SCAN_RESP: returned %d APs before parsing\n",
scan_rsp->number_of_sets);
bss_info = scan_rsp->bss_desc_and_tlv_buffer;
/*
* The size of the TLV buffer is equal to the entire command response
* size (scan_resp_size) minus the fixed fields (sizeof()'s), the
* BSS Descriptions (bss_descript_size as bytesLef) and the command
* response header (S_DS_GEN)
*/
tlv_buf_size = scan_resp_size - (bytes_left
+ sizeof(scan_rsp->bss_descript_size)
+ sizeof(scan_rsp->number_of_sets)
+ S_DS_GEN);
tlv_data = (struct mwifiex_ie_types_data *) (scan_rsp->
bss_desc_and_tlv_buffer +
bytes_left);
/* Search the TLV buffer space in the scan response for any valid
TLVs */
mwifiex_ret_802_11_scan_get_tlv_ptrs(adapter, tlv_data, tlv_buf_size,
TLV_TYPE_TSFTIMESTAMP,
(struct mwifiex_ie_types_data **)
&tsf_tlv);
/* Search the TLV buffer space in the scan response for any valid
TLVs */
mwifiex_ret_802_11_scan_get_tlv_ptrs(adapter, tlv_data, tlv_buf_size,
TLV_TYPE_CHANNELBANDLIST,
(struct mwifiex_ie_types_data **)
&chan_band_tlv);
#ifdef CONFIG_PM
if (priv->wdev.wiphy->wowlan_config)
nd_config = priv->wdev.wiphy->wowlan_config->nd_config;
#endif
if (nd_config) {
adapter->nd_info =
kzalloc(sizeof(struct cfg80211_wowlan_nd_match) +
sizeof(struct cfg80211_wowlan_nd_match *) *
scan_rsp->number_of_sets, GFP_ATOMIC);
if (adapter->nd_info)
adapter->nd_info->n_matches = scan_rsp->number_of_sets;
}
for (idx = 0; idx < scan_rsp->number_of_sets && bytes_left; idx++) {
/*
* If the TSF TLV was appended to the scan results, save this
* entry's TSF value in the fw_tsf field. It is the firmware's
* TSF value at the time the beacon or probe response was
* received.
*/
if (tsf_tlv)
memcpy(&fw_tsf, &tsf_tlv->tsf_data[idx * TSF_DATA_SIZE],
sizeof(fw_tsf));
if (chan_band_tlv) {
chan_band = &chan_band_tlv->chan_band_param[idx];
radio_type = &chan_band->radio_type;
} else {
radio_type = NULL;
}
if (chan_band_tlv && adapter->nd_info) {
adapter->nd_info->matches[idx] =
kzalloc(sizeof(*pmatch) + sizeof(u32),
GFP_ATOMIC);
pmatch = adapter->nd_info->matches[idx];
if (pmatch) {
pmatch->n_channels = 1;
pmatch->channels[0] = chan_band->chan_number;
}
}
ret = mwifiex_parse_single_response_buf(priv, &bss_info,
&bytes_left,
le64_to_cpu(fw_tsf),
radio_type, false, 0);
if (ret)
goto check_next_scan;
}
check_next_scan:
mwifiex_check_next_scan_command(priv);
return ret;
}
/*
* This function prepares an extended scan command to be sent to the firmware
*
* This uses the scan command configuration sent to the command processing
* module in command preparation stage to configure a extended scan command
* structure to send to firmware.
*/
int mwifiex_cmd_802_11_scan_ext(struct mwifiex_private *priv,
struct host_cmd_ds_command *cmd,
void *data_buf)
{
struct host_cmd_ds_802_11_scan_ext *ext_scan = &cmd->params.ext_scan;
struct mwifiex_scan_cmd_config *scan_cfg = data_buf;
memcpy(ext_scan->tlv_buffer, scan_cfg->tlv_buf, scan_cfg->tlv_buf_len);
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_SCAN_EXT);
/* Size is equal to the sizeof(fixed portions) + the TLV len + header */
cmd->size = cpu_to_le16((u16)(sizeof(ext_scan->reserved)
+ scan_cfg->tlv_buf_len + S_DS_GEN));
return 0;
}
/* This function prepares an background scan config command to be sent
* to the firmware
*/
int mwifiex_cmd_802_11_bg_scan_config(struct mwifiex_private *priv,
struct host_cmd_ds_command *cmd,
void *data_buf)
{
struct host_cmd_ds_802_11_bg_scan_config *bgscan_config =
&cmd->params.bg_scan_config;
struct mwifiex_bg_scan_cfg *bgscan_cfg_in = data_buf;
u8 *tlv_pos = bgscan_config->tlv;
u8 num_probes;
u32 ssid_len, chan_idx, scan_type, scan_dur, chan_num;
int i;
struct mwifiex_ie_types_num_probes *num_probes_tlv;
struct mwifiex_ie_types_repeat_count *repeat_count_tlv;
struct mwifiex_ie_types_min_rssi_threshold *rssi_threshold_tlv;
struct mwifiex_ie_types_bgscan_start_later *start_later_tlv;
struct mwifiex_ie_types_wildcard_ssid_params *wildcard_ssid_tlv;
struct mwifiex_ie_types_chan_list_param_set *chan_list_tlv;
struct mwifiex_chan_scan_param_set *temp_chan;
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_BG_SCAN_CONFIG);
cmd->size = cpu_to_le16(sizeof(*bgscan_config) + S_DS_GEN);
bgscan_config->action = cpu_to_le16(bgscan_cfg_in->action);
bgscan_config->enable = bgscan_cfg_in->enable;
bgscan_config->bss_type = bgscan_cfg_in->bss_type;
bgscan_config->scan_interval =
cpu_to_le32(bgscan_cfg_in->scan_interval);
bgscan_config->report_condition =
cpu_to_le32(bgscan_cfg_in->report_condition);
/* stop sched scan */
if (!bgscan_config->enable)
return 0;
bgscan_config->chan_per_scan = bgscan_cfg_in->chan_per_scan;
num_probes = (bgscan_cfg_in->num_probes ? bgscan_cfg_in->
num_probes : priv->adapter->scan_probes);
if (num_probes) {
num_probes_tlv = (struct mwifiex_ie_types_num_probes *)tlv_pos;
num_probes_tlv->header.type = cpu_to_le16(TLV_TYPE_NUMPROBES);
num_probes_tlv->header.len =
cpu_to_le16(sizeof(num_probes_tlv->num_probes));
num_probes_tlv->num_probes = cpu_to_le16((u16)num_probes);
tlv_pos += sizeof(num_probes_tlv->header) +
le16_to_cpu(num_probes_tlv->header.len);
}
if (bgscan_cfg_in->repeat_count) {
repeat_count_tlv =
(struct mwifiex_ie_types_repeat_count *)tlv_pos;
repeat_count_tlv->header.type =
cpu_to_le16(TLV_TYPE_REPEAT_COUNT);
repeat_count_tlv->header.len =
cpu_to_le16(sizeof(repeat_count_tlv->repeat_count));
repeat_count_tlv->repeat_count =
cpu_to_le16(bgscan_cfg_in->repeat_count);
tlv_pos += sizeof(repeat_count_tlv->header) +
le16_to_cpu(repeat_count_tlv->header.len);
}
if (bgscan_cfg_in->rssi_threshold) {
rssi_threshold_tlv =
(struct mwifiex_ie_types_min_rssi_threshold *)tlv_pos;
rssi_threshold_tlv->header.type =
cpu_to_le16(TLV_TYPE_RSSI_LOW);
rssi_threshold_tlv->header.len =
cpu_to_le16(sizeof(rssi_threshold_tlv->rssi_threshold));
rssi_threshold_tlv->rssi_threshold =
cpu_to_le16(bgscan_cfg_in->rssi_threshold);
tlv_pos += sizeof(rssi_threshold_tlv->header) +
le16_to_cpu(rssi_threshold_tlv->header.len);
}
for (i = 0; i < bgscan_cfg_in->num_ssids; i++) {
ssid_len = bgscan_cfg_in->ssid_list[i].ssid.ssid_len;
wildcard_ssid_tlv =
(struct mwifiex_ie_types_wildcard_ssid_params *)tlv_pos;
wildcard_ssid_tlv->header.type =
cpu_to_le16(TLV_TYPE_WILDCARDSSID);
wildcard_ssid_tlv->header.len = cpu_to_le16(
(u16)(ssid_len + sizeof(wildcard_ssid_tlv->
max_ssid_length)));
/* max_ssid_length = 0 tells firmware to perform
* specific scan for the SSID filled, whereas
* max_ssid_length = IEEE80211_MAX_SSID_LEN is for
* wildcard scan.
*/
if (ssid_len)
wildcard_ssid_tlv->max_ssid_length = 0;
else
wildcard_ssid_tlv->max_ssid_length =
IEEE80211_MAX_SSID_LEN;
memcpy(wildcard_ssid_tlv->ssid,
bgscan_cfg_in->ssid_list[i].ssid.ssid, ssid_len);
tlv_pos += (sizeof(wildcard_ssid_tlv->header)
+ le16_to_cpu(wildcard_ssid_tlv->header.len));
}
chan_list_tlv = (struct mwifiex_ie_types_chan_list_param_set *)tlv_pos;
if (bgscan_cfg_in->chan_list[0].chan_number) {
dev_dbg(priv->adapter->dev, "info: bgscan: Using supplied channel list\n");
chan_list_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);
for (chan_idx = 0;
chan_idx < MWIFIEX_BG_SCAN_CHAN_MAX &&
bgscan_cfg_in->chan_list[chan_idx].chan_number;
chan_idx++) {
temp_chan = chan_list_tlv->chan_scan_param + chan_idx;
/* Increment the TLV header length by size appended */
le16_unaligned_add_cpu(&chan_list_tlv->header.len,
sizeof(
chan_list_tlv->chan_scan_param));
temp_chan->chan_number =
bgscan_cfg_in->chan_list[chan_idx].chan_number;
temp_chan->radio_type =
bgscan_cfg_in->chan_list[chan_idx].radio_type;
scan_type =
bgscan_cfg_in->chan_list[chan_idx].scan_type;
if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE)
temp_chan->chan_scan_mode_bitmap
|= MWIFIEX_PASSIVE_SCAN;
else
temp_chan->chan_scan_mode_bitmap
&= ~MWIFIEX_PASSIVE_SCAN;
if (bgscan_cfg_in->chan_list[chan_idx].scan_time) {
scan_dur = (u16)bgscan_cfg_in->
chan_list[chan_idx].scan_time;
} else {
scan_dur = (scan_type ==
MWIFIEX_SCAN_TYPE_PASSIVE) ?
priv->adapter->passive_scan_time :
priv->adapter->specific_scan_time;
}
temp_chan->min_scan_time = cpu_to_le16(scan_dur);
temp_chan->max_scan_time = cpu_to_le16(scan_dur);
}
} else {
dev_dbg(priv->adapter->dev,
"info: bgscan: Creating full region channel list\n");
chan_num =
mwifiex_bgscan_create_channel_list(priv, bgscan_cfg_in,
chan_list_tlv->
chan_scan_param);
le16_unaligned_add_cpu(&chan_list_tlv->header.len,
chan_num *
sizeof(chan_list_tlv->chan_scan_param[0]));
}
tlv_pos += (sizeof(chan_list_tlv->header)
+ le16_to_cpu(chan_list_tlv->header.len));
if (bgscan_cfg_in->start_later) {
start_later_tlv =
(struct mwifiex_ie_types_bgscan_start_later *)tlv_pos;
start_later_tlv->header.type =
cpu_to_le16(TLV_TYPE_BGSCAN_START_LATER);
start_later_tlv->header.len =
cpu_to_le16(sizeof(start_later_tlv->start_later));
start_later_tlv->start_later =
cpu_to_le16(bgscan_cfg_in->start_later);
tlv_pos += sizeof(start_later_tlv->header) +
le16_to_cpu(start_later_tlv->header.len);
}
/* Append vendor specific IE TLV */
mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_BGSCAN, &tlv_pos);
le16_unaligned_add_cpu(&cmd->size, tlv_pos - bgscan_config->tlv);
return 0;
}
int mwifiex_stop_bg_scan(struct mwifiex_private *priv)
{
struct mwifiex_bg_scan_cfg *bgscan_cfg;
if (!priv->sched_scanning) {
dev_dbg(priv->adapter->dev, "bgscan already stopped!\n");
return 0;
}
bgscan_cfg = kzalloc(sizeof(*bgscan_cfg), GFP_KERNEL);
if (!bgscan_cfg)
return -ENOMEM;
bgscan_cfg->bss_type = MWIFIEX_BSS_MODE_INFRA;
bgscan_cfg->action = MWIFIEX_BGSCAN_ACT_SET;
bgscan_cfg->enable = false;
if (mwifiex_send_cmd(priv, HostCmd_CMD_802_11_BG_SCAN_CONFIG,
HostCmd_ACT_GEN_SET, 0, bgscan_cfg, true)) {
kfree(bgscan_cfg);
return -EFAULT;
}
kfree(bgscan_cfg);
priv->sched_scanning = false;
return 0;
}
static void
mwifiex_update_chan_statistics(struct mwifiex_private *priv,
struct mwifiex_ietypes_chanstats *tlv_stat)
{
struct mwifiex_adapter *adapter = priv->adapter;
u8 i, num_chan;
struct mwifiex_fw_chan_stats *fw_chan_stats;
struct mwifiex_chan_stats chan_stats;
fw_chan_stats = (void *)((u8 *)tlv_stat +
sizeof(struct mwifiex_ie_types_header));
num_chan = le16_to_cpu(tlv_stat->header.len) /
sizeof(struct mwifiex_chan_stats);
for (i = 0 ; i < num_chan; i++) {
if (adapter->survey_idx >= adapter->num_in_chan_stats) {
mwifiex_dbg(adapter, WARN,
"FW reported too many channel results (max %d)\n",
adapter->num_in_chan_stats);
return;
}
chan_stats.chan_num = fw_chan_stats->chan_num;
chan_stats.bandcfg = fw_chan_stats->bandcfg;
chan_stats.flags = fw_chan_stats->flags;
chan_stats.noise = fw_chan_stats->noise;
chan_stats.total_bss = le16_to_cpu(fw_chan_stats->total_bss);
chan_stats.cca_scan_dur =
le16_to_cpu(fw_chan_stats->cca_scan_dur);
chan_stats.cca_busy_dur =
le16_to_cpu(fw_chan_stats->cca_busy_dur);
mwifiex_dbg(adapter, INFO,
"chan=%d, noise=%d, total_network=%d scan_duration=%d, busy_duration=%d\n",
chan_stats.chan_num,
chan_stats.noise,
chan_stats.total_bss,
chan_stats.cca_scan_dur,
chan_stats.cca_busy_dur);
memcpy(&adapter->chan_stats[adapter->survey_idx++], &chan_stats,
sizeof(struct mwifiex_chan_stats));
fw_chan_stats++;
}
}
/* This function handles the command response of extended scan */
int mwifiex_ret_802_11_scan_ext(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct host_cmd_ds_802_11_scan_ext *ext_scan_resp;
struct mwifiex_ie_types_header *tlv;
struct mwifiex_ietypes_chanstats *tlv_stat;
u16 buf_left, type, len;
struct host_cmd_ds_command *cmd_ptr;
struct cmd_ctrl_node *cmd_node;
bool complete_scan = false;
mwifiex_dbg(adapter, INFO, "info: EXT scan returns successfully\n");
ext_scan_resp = &resp->params.ext_scan;
tlv = (void *)ext_scan_resp->tlv_buffer;
buf_left = le16_to_cpu(resp->size) - (sizeof(*ext_scan_resp) + S_DS_GEN
- 1);
while (buf_left >= sizeof(struct mwifiex_ie_types_header)) {
type = le16_to_cpu(tlv->type);
len = le16_to_cpu(tlv->len);
if (buf_left < (sizeof(struct mwifiex_ie_types_header) + len)) {
mwifiex_dbg(adapter, ERROR,
"error processing scan response TLVs");
break;
}
switch (type) {
case TLV_TYPE_CHANNEL_STATS:
tlv_stat = (void *)tlv;
mwifiex_update_chan_statistics(priv, tlv_stat);
break;
default:
break;
}
buf_left -= len + sizeof(struct mwifiex_ie_types_header);
tlv = (void *)((u8 *)tlv + len +
sizeof(struct mwifiex_ie_types_header));
}
spin_lock_bh(&adapter->cmd_pending_q_lock);
spin_lock_bh(&adapter->scan_pending_q_lock);
if (list_empty(&adapter->scan_pending_q)) {
complete_scan = true;
list_for_each_entry(cmd_node, &adapter->cmd_pending_q, list) {
cmd_ptr = (void *)cmd_node->cmd_skb->data;
if (le16_to_cpu(cmd_ptr->command) ==
HostCmd_CMD_802_11_SCAN_EXT) {
mwifiex_dbg(adapter, INFO,
"Scan pending in command pending list");
complete_scan = false;
break;
}
}
}
spin_unlock_bh(&adapter->scan_pending_q_lock);
spin_unlock_bh(&adapter->cmd_pending_q_lock);
if (complete_scan)
mwifiex_complete_scan(priv);
return 0;
}
/* This function This function handles the event extended scan report. It
* parses extended scan results and informs to cfg80211 stack.
*/
int mwifiex_handle_event_ext_scan_report(struct mwifiex_private *priv,
void *buf)
{
int ret = 0;
struct mwifiex_adapter *adapter = priv->adapter;
u8 *bss_info;
u32 bytes_left, bytes_left_for_tlv, idx;
u16 type, len;
struct mwifiex_ie_types_data *tlv;
struct mwifiex_ie_types_bss_scan_rsp *scan_rsp_tlv;
struct mwifiex_ie_types_bss_scan_info *scan_info_tlv;
u8 *radio_type;
u64 fw_tsf = 0;
s32 rssi = 0;
struct mwifiex_event_scan_result *event_scan = buf;
u8 num_of_set = event_scan->num_of_set;
u8 *scan_resp = buf + sizeof(struct mwifiex_event_scan_result);
u16 scan_resp_size = le16_to_cpu(event_scan->buf_size);
if (num_of_set > MWIFIEX_MAX_AP) {
mwifiex_dbg(adapter, ERROR,
"EXT_SCAN: Invalid number of AP returned (%d)!!\n",
num_of_set);
ret = -1;
goto check_next_scan;
}
bytes_left = scan_resp_size;
mwifiex_dbg(adapter, INFO,
"EXT_SCAN: size %d, returned %d APs...",
scan_resp_size, num_of_set);
mwifiex_dbg_dump(adapter, CMD_D, "EXT_SCAN buffer:", buf,
scan_resp_size +
sizeof(struct mwifiex_event_scan_result));
tlv = (struct mwifiex_ie_types_data *)scan_resp;
for (idx = 0; idx < num_of_set && bytes_left; idx++) {
type = le16_to_cpu(tlv->header.type);
len = le16_to_cpu(tlv->header.len);
if (bytes_left < sizeof(struct mwifiex_ie_types_header) + len) {
mwifiex_dbg(adapter, ERROR,
"EXT_SCAN: Error bytes left < TLV length\n");
break;
}
scan_rsp_tlv = NULL;
scan_info_tlv = NULL;
bytes_left_for_tlv = bytes_left;
/* BSS response TLV with beacon or probe response buffer
* at the initial position of each descriptor
*/
if (type != TLV_TYPE_BSS_SCAN_RSP)
break;
bss_info = (u8 *)tlv;
scan_rsp_tlv = (struct mwifiex_ie_types_bss_scan_rsp *)tlv;
tlv = (struct mwifiex_ie_types_data *)(tlv->data + len);
bytes_left_for_tlv -=
(len + sizeof(struct mwifiex_ie_types_header));
while (bytes_left_for_tlv >=
sizeof(struct mwifiex_ie_types_header) &&
le16_to_cpu(tlv->header.type) != TLV_TYPE_BSS_SCAN_RSP) {
type = le16_to_cpu(tlv->header.type);
len = le16_to_cpu(tlv->header.len);
if (bytes_left_for_tlv <
sizeof(struct mwifiex_ie_types_header) + len) {
mwifiex_dbg(adapter, ERROR,
"EXT_SCAN: Error in processing TLV,\t"
"bytes left < TLV length\n");
scan_rsp_tlv = NULL;
bytes_left_for_tlv = 0;
continue;
}
switch (type) {
case TLV_TYPE_BSS_SCAN_INFO:
scan_info_tlv =
(struct mwifiex_ie_types_bss_scan_info *)tlv;
if (len !=
sizeof(struct mwifiex_ie_types_bss_scan_info) -
sizeof(struct mwifiex_ie_types_header)) {
bytes_left_for_tlv = 0;
continue;
}
break;
default:
break;
}
tlv = (struct mwifiex_ie_types_data *)(tlv->data + len);
bytes_left -=
(len + sizeof(struct mwifiex_ie_types_header));
bytes_left_for_tlv -=
(len + sizeof(struct mwifiex_ie_types_header));
}
if (!scan_rsp_tlv)
break;
/* Advance pointer to the beacon buffer length and
* update the bytes count so that the function
* wlan_interpret_bss_desc_with_ie() can handle the
* scan buffer withut any change
*/
bss_info += sizeof(u16);
bytes_left -= sizeof(u16);
if (scan_info_tlv) {
rssi = (s32)(s16)(le16_to_cpu(scan_info_tlv->rssi));
rssi *= 100; /* Convert dBm to mBm */
mwifiex_dbg(adapter, INFO,
"info: InterpretIE: RSSI=%d\n", rssi);
fw_tsf = le64_to_cpu(scan_info_tlv->tsf);
radio_type = &scan_info_tlv->radio_type;
} else {
radio_type = NULL;
}
ret = mwifiex_parse_single_response_buf(priv, &bss_info,
&bytes_left, fw_tsf,
radio_type, true, rssi);
if (ret)
goto check_next_scan;
}
check_next_scan:
if (!event_scan->more_event)
mwifiex_check_next_scan_command(priv);
return ret;
}
/*
* This function prepares command for background scan query.
*
* Preparation includes -
* - Setting command ID and proper size
* - Setting background scan flush parameter
* - Ensuring correct endian-ness
*/
int mwifiex_cmd_802_11_bg_scan_query(struct host_cmd_ds_command *cmd)
{
struct host_cmd_ds_802_11_bg_scan_query *bg_query =
&cmd->params.bg_scan_query;
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_BG_SCAN_QUERY);
cmd->size = cpu_to_le16(sizeof(struct host_cmd_ds_802_11_bg_scan_query)
+ S_DS_GEN);
bg_query->flush = 1;
return 0;
}
/*
* This function inserts scan command node to the scan pending queue.
*/
void
mwifiex_queue_scan_cmd(struct mwifiex_private *priv,
struct cmd_ctrl_node *cmd_node)
{
struct mwifiex_adapter *adapter = priv->adapter;
cmd_node->wait_q_enabled = true;
cmd_node->condition = &adapter->scan_wait_q_woken;
spin_lock_bh(&adapter->scan_pending_q_lock);
list_add_tail(&cmd_node->list, &adapter->scan_pending_q);
spin_unlock_bh(&adapter->scan_pending_q_lock);
}
/*
* This function sends a scan command for all available channels to the
* firmware, filtered on a specific SSID.
*/
static int mwifiex_scan_specific_ssid(struct mwifiex_private *priv,
struct cfg80211_ssid *req_ssid)
{
struct mwifiex_adapter *adapter = priv->adapter;
int ret;
struct mwifiex_user_scan_cfg *scan_cfg;
if (adapter->scan_processing) {
mwifiex_dbg(adapter, WARN,
"cmd: Scan already in process...\n");
return -EBUSY;
}
if (priv->scan_block) {
mwifiex_dbg(adapter, WARN,
"cmd: Scan is blocked during association...\n");
return -EBUSY;
}
scan_cfg = kzalloc(sizeof(struct mwifiex_user_scan_cfg), GFP_KERNEL);
if (!scan_cfg)
return -ENOMEM;
scan_cfg->ssid_list = req_ssid;
scan_cfg->num_ssids = 1;
ret = mwifiex_scan_networks(priv, scan_cfg);
kfree(scan_cfg);
return ret;
}
/*
* Sends IOCTL request to start a scan.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*
* Scan command can be issued for both normal scan and specific SSID
* scan, depending upon whether an SSID is provided or not.
*/
int mwifiex_request_scan(struct mwifiex_private *priv,
struct cfg80211_ssid *req_ssid)
{
int ret;
if (mutex_lock_interruptible(&priv->async_mutex)) {
mwifiex_dbg(priv->adapter, ERROR,
"%s: acquire semaphore fail\n",
__func__);
return -1;
}
priv->adapter->scan_wait_q_woken = false;
if (req_ssid && req_ssid->ssid_len != 0)
/* Specific SSID scan */
ret = mwifiex_scan_specific_ssid(priv, req_ssid);
else
/* Normal scan */
ret = mwifiex_scan_networks(priv, NULL);
mutex_unlock(&priv->async_mutex);
return ret;
}
/*
* This function appends the vendor specific IE TLV to a buffer.
*/
int
mwifiex_cmd_append_vsie_tlv(struct mwifiex_private *priv,
u16 vsie_mask, u8 **buffer)
{
int id, ret_len = 0;
struct mwifiex_ie_types_vendor_param_set *vs_param_set;
if (!buffer)
return 0;
if (!(*buffer))
return 0;
/*
* Traverse through the saved vendor specific IE array and append
* the selected(scan/assoc/adhoc) IE as TLV to the command
*/
for (id = 0; id < MWIFIEX_MAX_VSIE_NUM; id++) {
if (priv->vs_ie[id].mask & vsie_mask) {
vs_param_set =
(struct mwifiex_ie_types_vendor_param_set *)
*buffer;
vs_param_set->header.type =
cpu_to_le16(TLV_TYPE_PASSTHROUGH);
vs_param_set->header.len =
cpu_to_le16((((u16) priv->vs_ie[id].ie[1])
& 0x00FF) + 2);
if (le16_to_cpu(vs_param_set->header.len) >
MWIFIEX_MAX_VSIE_LEN) {
mwifiex_dbg(priv->adapter, ERROR,
"Invalid param length!\n");
break;
}
memcpy(vs_param_set->ie, priv->vs_ie[id].ie,
le16_to_cpu(vs_param_set->header.len));
*buffer += le16_to_cpu(vs_param_set->header.len) +
sizeof(struct mwifiex_ie_types_header);
ret_len += le16_to_cpu(vs_param_set->header.len) +
sizeof(struct mwifiex_ie_types_header);
}
}
return ret_len;
}
/*
* This function saves a beacon buffer of the current BSS descriptor.
*
* The current beacon buffer is saved so that it can be restored in the
* following cases that makes the beacon buffer not to contain the current
* ssid's beacon buffer.
* - The current ssid was not found somehow in the last scan.
* - The current ssid was the last entry of the scan table and overloaded.
*/
void
mwifiex_save_curr_bcn(struct mwifiex_private *priv)
{
struct mwifiex_bssdescriptor *curr_bss =
&priv->curr_bss_params.bss_descriptor;
if (!curr_bss->beacon_buf_size)
return;
/* allocate beacon buffer at 1st time; or if it's size has changed */
if (!priv->curr_bcn_buf ||
priv->curr_bcn_size != curr_bss->beacon_buf_size) {
priv->curr_bcn_size = curr_bss->beacon_buf_size;
kfree(priv->curr_bcn_buf);
priv->curr_bcn_buf = kmalloc(curr_bss->beacon_buf_size,
GFP_ATOMIC);
if (!priv->curr_bcn_buf)
return;
}
memcpy(priv->curr_bcn_buf, curr_bss->beacon_buf,
curr_bss->beacon_buf_size);
mwifiex_dbg(priv->adapter, INFO,
"info: current beacon saved %d\n",
priv->curr_bcn_size);
curr_bss->beacon_buf = priv->curr_bcn_buf;
/* adjust the pointers in the current BSS descriptor */
if (curr_bss->bcn_wpa_ie)
curr_bss->bcn_wpa_ie =
(struct ieee_types_vendor_specific *)
(curr_bss->beacon_buf +
curr_bss->wpa_offset);
if (curr_bss->bcn_rsn_ie)
curr_bss->bcn_rsn_ie = (struct ieee_types_generic *)
(curr_bss->beacon_buf +
curr_bss->rsn_offset);
if (curr_bss->bcn_ht_cap)
curr_bss->bcn_ht_cap = (struct ieee80211_ht_cap *)
(curr_bss->beacon_buf +
curr_bss->ht_cap_offset);
if (curr_bss->bcn_ht_oper)
curr_bss->bcn_ht_oper = (struct ieee80211_ht_operation *)
(curr_bss->beacon_buf +
curr_bss->ht_info_offset);
if (curr_bss->bcn_vht_cap)
curr_bss->bcn_vht_cap = (void *)(curr_bss->beacon_buf +
curr_bss->vht_cap_offset);
if (curr_bss->bcn_vht_oper)
curr_bss->bcn_vht_oper = (void *)(curr_bss->beacon_buf +
curr_bss->vht_info_offset);
if (curr_bss->bcn_bss_co_2040)
curr_bss->bcn_bss_co_2040 =
(curr_bss->beacon_buf + curr_bss->bss_co_2040_offset);
if (curr_bss->bcn_ext_cap)
curr_bss->bcn_ext_cap = curr_bss->beacon_buf +
curr_bss->ext_cap_offset;
if (curr_bss->oper_mode)
curr_bss->oper_mode = (void *)(curr_bss->beacon_buf +
curr_bss->oper_mode_offset);
}
/*
* This function frees the current BSS descriptor beacon buffer.
*/
void
mwifiex_free_curr_bcn(struct mwifiex_private *priv)
{
kfree(priv->curr_bcn_buf);
priv->curr_bcn_buf = NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_4004_0 |
crossvul-cpp_data_good_3231_0 | /*
===========================================================================
Return to Castle Wolfenstein multiplayer GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (RTCW MP Source Code).
RTCW MP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW MP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW MP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
// console.c
#include "client.h"
int g_console_field_width = 78;
#define COLNSOLE_COLOR COLOR_WHITE //COLOR_BLACK
#define NUM_CON_TIMES 4
//#define CON_TEXTSIZE 32768
#define CON_TEXTSIZE 65536 // (SA) DM want's more console...
typedef struct {
qboolean initialized;
short text[CON_TEXTSIZE];
int current; // line where next message will be printed
int x; // offset in current line for next print
int display; // bottom of console displays this line
int linewidth; // characters across screen
int totallines; // total lines in console scrollback
float xadjust; // for wide aspect screens
float displayFrac; // aproaches finalFrac at scr_conspeed
float finalFrac; // 0.0 to 1.0 lines of console to display
int vislines; // in scanlines
int times[NUM_CON_TIMES]; // cls.realtime time the line was generated
// for transparent notify lines
vec4_t color;
} console_t;
console_t con;
cvar_t *con_debug;
cvar_t *con_conspeed;
cvar_t *con_notifytime;
// DHM - Nerve :: Must hold CTRL + SHIFT + ~ to get console
cvar_t *con_restricted;
#define DEFAULT_CONSOLE_WIDTH 78
/*
================
Con_ToggleConsole_f
================
*/
void Con_ToggleConsole_f( void ) {
// Can't toggle the console when it's the only thing available
if ( clc.state == CA_DISCONNECTED && Key_GetCatcher( ) == KEYCATCH_CONSOLE ) {
CL_StartDemoLoop();
return;
}
if ( con_restricted->integer && ( !keys[K_CTRL].down || !keys[K_SHIFT].down ) ) {
return;
}
Field_Clear( &g_consoleField );
g_consoleField.widthInChars = g_console_field_width;
Con_ClearNotify();
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_CONSOLE );
}
/*
===================
Con_ToggleMenu_f
===================
*/
void Con_ToggleMenu_f( void ) {
CL_KeyEvent( K_ESCAPE, qtrue, Sys_Milliseconds() );
CL_KeyEvent( K_ESCAPE, qfalse, Sys_Milliseconds() );
}
/*
================
Con_MessageMode_f
================
*/
void Con_MessageMode_f( void ) {
chat_playerNum = -1;
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode2_f
================
*/
void Con_MessageMode2_f( void ) {
chat_playerNum = -1;
chat_team = qtrue;
Field_Clear( &chatField );
chatField.widthInChars = 25;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode3_f
================
*/
void Con_MessageMode3_f( void ) {
chat_playerNum = VM_Call( cgvm, CG_CROSSHAIR_PLAYER );
if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) {
chat_playerNum = -1;
return;
}
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
/*
================
Con_MessageMode4_f
================
*/
void Con_MessageMode4_f( void ) {
chat_playerNum = VM_Call( cgvm, CG_LAST_ATTACKER );
if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) {
chat_playerNum = -1;
return;
}
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
// NERVE - SMF
/*
================
Con_StartLimboMode_f
================
*/
void Con_StartLimboMode_f( void ) {
chat_limbo = qtrue;
}
/*
================
Con_StopLimboMode_f
================
*/
void Con_StopLimboMode_f( void ) {
chat_limbo = qfalse;
}
// -NERVE - SMF
/*
================
Con_Clear_f
================
*/
void Con_Clear_f( void ) {
int i;
for ( i = 0 ; i < CON_TEXTSIZE ; i++ ) {
con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
}
Con_Bottom(); // go to end
}
/*
================
Con_Dump_f
Save the console contents out to a file
================
*/
void Con_Dump_f( void ) {
int l, x, i;
short *line;
fileHandle_t f;
int bufferlen;
char *buffer;
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: condump <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".txt" );
if (!COM_CompareExtension(filename, ".txt"))
{
Com_Printf("Con_Dump_f: Only the \".txt\" extension is supported by this command!\n");
return;
}
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf ("ERROR: couldn't open %s.\n", filename);
return;
}
Com_Printf ("Dumped console text to %s.\n", filename );
// skip empty lines
for ( l = con.current - con.totallines + 1 ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( x = 0 ; x < con.linewidth ; x++ )
if ( ( line[x] & 0xff ) != ' ' ) {
break;
}
if ( x != con.linewidth ) {
break;
}
}
#ifdef _WIN32
bufferlen = con.linewidth + 3 * sizeof ( char );
#else
bufferlen = con.linewidth + 2 * sizeof ( char );
#endif
buffer = Hunk_AllocateTempMemory( bufferlen );
// write the remaining lines
buffer[bufferlen-1] = 0;
for ( ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( i = 0; i < con.linewidth; i++ )
buffer[i] = line[i] & 0xff;
for ( x = con.linewidth - 1 ; x >= 0 ; x-- )
{
if ( buffer[x] == ' ' ) {
buffer[x] = 0;
} else {
break;
}
}
#ifdef _WIN32
Q_strcat(buffer, bufferlen, "\r\n");
#else
Q_strcat(buffer, bufferlen, "\n");
#endif
FS_Write( buffer, strlen( buffer ), f );
}
Hunk_FreeTempMemory( buffer );
FS_FCloseFile( f );
}
/*
================
Con_ClearNotify
================
*/
void Con_ClearNotify( void ) {
int i;
for ( i = 0 ; i < NUM_CON_TIMES ; i++ ) {
con.times[i] = 0;
}
}
/*
================
Con_CheckResize
If the line width has changed, reformat the buffer.
================
*/
void Con_CheckResize( void ) {
int i, j, width, oldwidth, oldtotallines, numlines, numchars;
short tbuf[CON_TEXTSIZE];
width = ( SCREEN_WIDTH / SMALLCHAR_WIDTH ) - 2;
if ( width == con.linewidth ) {
return;
}
if ( width < 1 ) { // video hasn't been initialized yet
width = DEFAULT_CONSOLE_WIDTH;
con.linewidth = width;
con.totallines = CON_TEXTSIZE / con.linewidth;
for ( i = 0; i < CON_TEXTSIZE; i++ )
con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
} else
{
oldwidth = con.linewidth;
con.linewidth = width;
oldtotallines = con.totallines;
con.totallines = CON_TEXTSIZE / con.linewidth;
numlines = oldtotallines;
if ( con.totallines < numlines ) {
numlines = con.totallines;
}
numchars = oldwidth;
if ( con.linewidth < numchars ) {
numchars = con.linewidth;
}
memcpy( tbuf, con.text, CON_TEXTSIZE * sizeof( short ) );
for ( i = 0; i < CON_TEXTSIZE; i++ )
con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
for ( i = 0 ; i < numlines ; i++ )
{
for ( j = 0 ; j < numchars ; j++ )
{
con.text[( con.totallines - 1 - i ) * con.linewidth + j] =
tbuf[( ( con.current - i + oldtotallines ) %
oldtotallines ) * oldwidth + j];
}
}
Con_ClearNotify();
}
con.current = con.totallines - 1;
con.display = con.current;
}
/*
==================
Cmd_CompleteTxtName
==================
*/
void Cmd_CompleteTxtName( char *args, int argNum ) {
if( argNum == 2 ) {
Field_CompleteFilename( "", "txt", qfalse, qtrue );
}
}
/*
================
Con_Init
================
*/
void Con_Init( void ) {
int i;
con_notifytime = Cvar_Get( "con_notifytime", "7", 0 ); // JPW NERVE increased per id req for obits
con_conspeed = Cvar_Get( "scr_conspeed", "3", 0 );
con_debug = Cvar_Get( "con_debug", "0", CVAR_ARCHIVE ); //----(SA) added
con_restricted = Cvar_Get( "con_restricted", "0", CVAR_INIT ); // DHM - Nerve
Field_Clear( &g_consoleField );
g_consoleField.widthInChars = g_console_field_width;
for ( i = 0 ; i < COMMAND_HISTORY ; i++ ) {
Field_Clear( &historyEditLines[i] );
historyEditLines[i].widthInChars = g_console_field_width;
}
CL_LoadConsoleHistory( );
Cmd_AddCommand( "toggleconsole", Con_ToggleConsole_f );
Cmd_AddCommand ("togglemenu", Con_ToggleMenu_f);
Cmd_AddCommand( "messagemode", Con_MessageMode_f );
Cmd_AddCommand( "messagemode2", Con_MessageMode2_f );
Cmd_AddCommand( "messagemode3", Con_MessageMode3_f );
Cmd_AddCommand( "messagemode4", Con_MessageMode4_f );
Cmd_AddCommand( "startLimboMode", Con_StartLimboMode_f ); // NERVE - SMF
Cmd_AddCommand( "stopLimboMode", Con_StopLimboMode_f ); // NERVE - SMF
Cmd_AddCommand( "clear", Con_Clear_f );
Cmd_AddCommand( "condump", Con_Dump_f );
Cmd_SetCommandCompletionFunc( "condump", Cmd_CompleteTxtName );
}
/*
================
Con_Shutdown
================
*/
void Con_Shutdown(void)
{
Cmd_RemoveCommand("toggleconsole");
Cmd_RemoveCommand("togglemenu");
Cmd_RemoveCommand("messagemode");
Cmd_RemoveCommand("messagemode2");
Cmd_RemoveCommand("messagemode3");
Cmd_RemoveCommand("messagemode4");
Cmd_RemoveCommand("startLimboMode");
Cmd_RemoveCommand("stopLimboMode");
Cmd_RemoveCommand("clear");
Cmd_RemoveCommand("condump");
}
/*
===============
Con_Linefeed
===============
*/
void Con_Linefeed( qboolean skipnotify ) {
int i;
// mark time for transparent overlay
if ( con.current >= 0 ) {
if ( skipnotify ) {
con.times[con.current % NUM_CON_TIMES] = 0;
} else {
con.times[con.current % NUM_CON_TIMES] = cls.realtime;
}
}
con.x = 0;
if ( con.display == con.current ) {
con.display++;
}
con.current++;
for ( i = 0; i < con.linewidth; i++ )
con.text[( con.current % con.totallines ) * con.linewidth + i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' ';
}
/*
================
CL_ConsolePrint
Handles cursor positioning, line wrapping, etc
All console printing must go through this in order to be logged to disk
If no console is visible, the text will appear at the top of the game window
================
*/
void CL_ConsolePrint( char *txt ) {
int y, l;
unsigned char c;
unsigned short color;
qboolean skipnotify = qfalse; // NERVE - SMF
int prev; // NERVE - SMF
// NERVE - SMF - work around for text that shows up in console but not in notify
if ( !Q_strncmp( txt, "[skipnotify]", 12 ) ) {
skipnotify = qtrue;
txt += 12;
}
// for some demos we don't want to ever show anything on the console
if ( cl_noprint && cl_noprint->integer ) {
return;
}
if ( !con.initialized ) {
con.color[0] =
con.color[1] =
con.color[2] =
con.color[3] = 1.0f;
con.linewidth = -1;
Con_CheckResize();
con.initialized = qtrue;
}
color = ColorIndex( COLNSOLE_COLOR );
while ( (c = *((unsigned char *) txt)) != 0 ) {
if ( Q_IsColorString( txt ) ) {
color = ColorIndex( *( txt + 1 ) );
txt += 2;
continue;
}
// count word length
for ( l = 0 ; l < con.linewidth ; l++ ) {
if ( txt[l] <= ' ' ) {
break;
}
}
// word wrap
if ( l != con.linewidth && ( con.x + l >= con.linewidth ) ) {
Con_Linefeed( skipnotify );
}
txt++;
switch ( c )
{
case '\n':
Con_Linefeed( skipnotify );
break;
case '\r':
con.x = 0;
break;
default: // display character and advance
y = con.current % con.totallines;
con.text[y * con.linewidth + con.x] = ( color << 8 ) | c;
con.x++;
if(con.x >= con.linewidth)
Con_Linefeed( skipnotify );
break;
}
}
// mark time for transparent overlay
if ( con.current >= 0 ) {
// NERVE - SMF
if ( skipnotify ) {
prev = con.current % NUM_CON_TIMES - 1;
if ( prev < 0 ) {
prev = NUM_CON_TIMES - 1;
}
con.times[prev] = 0;
} else {
// -NERVE - SMF
con.times[con.current % NUM_CON_TIMES] = cls.realtime;
}
}
}
/*
==============================================================================
DRAWING
==============================================================================
*/
/*
================
Con_DrawInput
Draw the editline after a ] prompt
================
*/
void Con_DrawInput( void ) {
int y;
if ( clc.state != CA_DISCONNECTED && !(Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ) {
return;
}
y = con.vislines - ( SMALLCHAR_HEIGHT * 2 );
re.SetColor( con.color );
SCR_DrawSmallChar( con.xadjust + 1 * SMALLCHAR_WIDTH, y, ']' );
Field_Draw( &g_consoleField, con.xadjust + 2 * SMALLCHAR_WIDTH, y,
SCREEN_WIDTH - 3 * SMALLCHAR_WIDTH, qtrue, qtrue );
}
/*
================
Con_DrawNotify
Draws the last few lines of output transparently over the game top
================
*/
void Con_DrawNotify( void ) {
int x, v;
short *text;
int i;
int time;
int skip;
int currentColor;
// NERVE - SMF - we dont want draw notify in limbo mode
if ( Cvar_VariableIntegerValue( "ui_limboMode" ) ) {
return;
}
currentColor = 7;
re.SetColor( g_color_table[currentColor] );
v = 0;
for ( i = con.current - NUM_CON_TIMES + 1 ; i <= con.current ; i++ )
{
if ( i < 0 ) {
continue;
}
time = con.times[i % NUM_CON_TIMES];
if ( time == 0 ) {
continue;
}
time = cls.realtime - time;
if ( time > con_notifytime->value * 1000 ) {
continue;
}
text = con.text + ( i % con.totallines ) * con.linewidth;
if (cl.snap.ps.pm_type != PM_INTERMISSION && Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME) ) {
continue;
}
for ( x = 0 ; x < con.linewidth ; x++ ) {
if ( ( text[x] & 0xff ) == ' ' ) {
continue;
}
if ( ColorIndexForNumber( text[x] >> 8 ) != currentColor ) {
currentColor = ColorIndexForNumber( text[x] >> 8 );
re.SetColor( g_color_table[currentColor] );
}
SCR_DrawSmallChar( cl_conXOffset->integer + con.xadjust + ( x + 1 ) * SMALLCHAR_WIDTH, v, text[x] & 0xff );
}
v += SMALLCHAR_HEIGHT;
}
re.SetColor( NULL );
if (Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME) ) {
return;
}
// draw the chat line
if ( Key_GetCatcher( ) & KEYCATCH_MESSAGE ) {
if ( chat_team ) {
char buf[128];
CL_TranslateString( "say_team:", buf );
SCR_DrawBigString( 8, v, buf, 1.0f, qfalse );
skip = strlen( buf ) + 2;
} else
{
char buf[128];
CL_TranslateString( "say:", buf );
SCR_DrawBigString( 8, v, buf, 1.0f, qfalse );
skip = strlen( buf ) + 1;
}
Field_BigDraw( &chatField, skip * BIGCHAR_WIDTH, v, SCREEN_WIDTH - ( skip + 1 ) * BIGCHAR_WIDTH, qtrue, qtrue );
}
}
/*
================
Con_DrawSolidConsole
Draws the console with the solid background
================
*/
void Con_DrawSolidConsole( float frac ) {
int i, x, y;
int rows;
short *text;
int row;
int lines;
int currentColor;
vec4_t color;
lines = cls.glconfig.vidHeight * frac;
if ( lines <= 0 ) {
return;
}
if ( lines > cls.glconfig.vidHeight ) {
lines = cls.glconfig.vidHeight;
}
// on wide screens, we will center the text
con.xadjust = 0;
SCR_AdjustFrom640( &con.xadjust, NULL, NULL, NULL );
// draw the background
y = frac * SCREEN_HEIGHT;
if ( y < 1 ) {
y = 0;
} else {
SCR_DrawPic( 0, 0, SCREEN_WIDTH, y, cls.consoleShader );
if ( frac >= 0.5f ) {
color[0] = color[1] = color[2] = frac * 2.0f;
color[3] = 1.0f;
re.SetColor( color );
// draw the logo
SCR_DrawPic( 192, 70, 256, 128, cls.consoleShader2 );
re.SetColor( NULL );
}
}
color[0] = 0;
color[1] = 0;
color[2] = 0;
color[3] = 0.6f;
SCR_FillRect( 0, y, SCREEN_WIDTH, 2, color );
// draw the version number
re.SetColor( g_color_table[ColorIndex( COLNSOLE_COLOR )] );
i = strlen( Q3_VERSION );
for ( x = 0 ; x < i ; x++ ) {
SCR_DrawSmallChar( cls.glconfig.vidWidth - ( i - x + 1 ) * SMALLCHAR_WIDTH, lines - SMALLCHAR_HEIGHT, Q3_VERSION[x] );
}
// draw the text
con.vislines = lines;
rows = ( lines - SMALLCHAR_HEIGHT ) / SMALLCHAR_HEIGHT; // rows of text to draw
y = lines - ( SMALLCHAR_HEIGHT * 3 );
// draw from the bottom up
if ( con.display != con.current ) {
// draw arrows to show the buffer is backscrolled
re.SetColor( g_color_table[ColorIndex( COLOR_WHITE )] );
for ( x = 0 ; x < con.linewidth ; x += 4 )
SCR_DrawSmallChar( con.xadjust + ( x + 1 ) * SMALLCHAR_WIDTH, y, '^' );
y -= SMALLCHAR_HEIGHT;
rows--;
}
row = con.display;
if ( con.x == 0 ) {
row--;
}
currentColor = 7;
re.SetColor( g_color_table[currentColor] );
for ( i = 0 ; i < rows ; i++, y -= SMALLCHAR_HEIGHT, row-- )
{
if ( row < 0 ) {
break;
}
if ( con.current - row >= con.totallines ) {
// past scrollback wrap point
continue;
}
text = con.text + ( row % con.totallines ) * con.linewidth;
for ( x = 0 ; x < con.linewidth ; x++ ) {
if ( ( text[x] & 0xff ) == ' ' ) {
continue;
}
if ( ColorIndexForNumber( text[x] >> 8 ) != currentColor ) {
currentColor = ColorIndexForNumber( text[x] >> 8 );
re.SetColor( g_color_table[currentColor] );
}
SCR_DrawSmallChar( con.xadjust + ( x + 1 ) * SMALLCHAR_WIDTH, y, text[x] & 0xff );
}
}
// draw the input prompt, user text, and cursor if desired
Con_DrawInput();
re.SetColor( NULL );
}
/*
==================
Con_DrawConsole
==================
*/
void Con_DrawConsole( void ) {
// check for console width changes from a vid mode change
Con_CheckResize();
// if disconnected, render console full screen
if ( clc.state == CA_DISCONNECTED ) {
if ( !( Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME)) ) {
Con_DrawSolidConsole( 1.0 );
return;
}
}
if ( con.displayFrac ) {
Con_DrawSolidConsole( con.displayFrac );
} else {
// draw notify lines
if ( clc.state == CA_ACTIVE ) {
Con_DrawNotify();
}
}
}
//================================================================
/*
==================
Con_RunConsole
Scroll it up or down
==================
*/
void Con_RunConsole( void ) {
// decide on the destination height of the console
if ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) {
con.finalFrac = 0.5; // half screen
} else {
con.finalFrac = 0; // none visible
}
// scroll towards the destination height
if ( con.finalFrac < con.displayFrac ) {
con.displayFrac -= con_conspeed->value * cls.realFrametime * 0.001;
if ( con.finalFrac > con.displayFrac ) {
con.displayFrac = con.finalFrac;
}
} else if ( con.finalFrac > con.displayFrac ) {
con.displayFrac += con_conspeed->value * cls.realFrametime * 0.001;
if ( con.finalFrac < con.displayFrac ) {
con.displayFrac = con.finalFrac;
}
}
}
void Con_PageUp( void ) {
con.display -= 2;
if ( con.current - con.display >= con.totallines ) {
con.display = con.current - con.totallines + 1;
}
}
void Con_PageDown( void ) {
con.display += 2;
if ( con.display > con.current ) {
con.display = con.current;
}
}
void Con_Top( void ) {
con.display = con.totallines;
if ( con.current - con.display >= con.totallines ) {
con.display = con.current - con.totallines + 1;
}
}
void Con_Bottom( void ) {
con.display = con.current;
}
void Con_Close( void ) {
if ( !com_cl_running->integer ) {
return;
}
Field_Clear( &g_consoleField );
Con_ClearNotify();
Key_SetCatcher( Key_GetCatcher( ) & ~KEYCATCH_CONSOLE );
con.finalFrac = 0; // none visible
con.displayFrac = 0;
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/good_3231_0 |
crossvul-cpp_data_bad_2887_0 | /* $OpenBSD: sftp-server.c,v 1.110 2016/09/12 01:22:38 deraadt Exp $ */
/*
* Copyright (c) 2000-2004 Markus Friedl. All rights reserved.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/mount.h>
#include <sys/statvfs.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pwd.h>
#include <time.h>
#include <unistd.h>
#include <stdarg.h>
#include "xmalloc.h"
#include "sshbuf.h"
#include "ssherr.h"
#include "log.h"
#include "misc.h"
#include "match.h"
#include "uidswap.h"
#include "sftp.h"
#include "sftp-common.h"
/* Our verbosity */
static LogLevel log_level = SYSLOG_LEVEL_ERROR;
/* Our client */
static struct passwd *pw = NULL;
static char *client_addr = NULL;
/* input and output queue */
struct sshbuf *iqueue;
struct sshbuf *oqueue;
/* Version of client */
static u_int version;
/* SSH2_FXP_INIT received */
static int init_done;
/* Disable writes */
static int readonly;
/* Requests that are allowed/denied */
static char *request_whitelist, *request_blacklist;
/* portable attributes, etc. */
typedef struct Stat Stat;
struct Stat {
char *name;
char *long_name;
Attrib attrib;
};
/* Packet handlers */
static void process_open(u_int32_t id);
static void process_close(u_int32_t id);
static void process_read(u_int32_t id);
static void process_write(u_int32_t id);
static void process_stat(u_int32_t id);
static void process_lstat(u_int32_t id);
static void process_fstat(u_int32_t id);
static void process_setstat(u_int32_t id);
static void process_fsetstat(u_int32_t id);
static void process_opendir(u_int32_t id);
static void process_readdir(u_int32_t id);
static void process_remove(u_int32_t id);
static void process_mkdir(u_int32_t id);
static void process_rmdir(u_int32_t id);
static void process_realpath(u_int32_t id);
static void process_rename(u_int32_t id);
static void process_readlink(u_int32_t id);
static void process_symlink(u_int32_t id);
static void process_extended_posix_rename(u_int32_t id);
static void process_extended_statvfs(u_int32_t id);
static void process_extended_fstatvfs(u_int32_t id);
static void process_extended_hardlink(u_int32_t id);
static void process_extended_fsync(u_int32_t id);
static void process_extended(u_int32_t id);
struct sftp_handler {
const char *name; /* user-visible name for fine-grained perms */
const char *ext_name; /* extended request name */
u_int type; /* packet type, for non extended packets */
void (*handler)(u_int32_t);
int does_write; /* if nonzero, banned for readonly mode */
};
struct sftp_handler handlers[] = {
/* NB. SSH2_FXP_OPEN does the readonly check in the handler itself */
{ "open", NULL, SSH2_FXP_OPEN, process_open, 0 },
{ "close", NULL, SSH2_FXP_CLOSE, process_close, 0 },
{ "read", NULL, SSH2_FXP_READ, process_read, 0 },
{ "write", NULL, SSH2_FXP_WRITE, process_write, 1 },
{ "lstat", NULL, SSH2_FXP_LSTAT, process_lstat, 0 },
{ "fstat", NULL, SSH2_FXP_FSTAT, process_fstat, 0 },
{ "setstat", NULL, SSH2_FXP_SETSTAT, process_setstat, 1 },
{ "fsetstat", NULL, SSH2_FXP_FSETSTAT, process_fsetstat, 1 },
{ "opendir", NULL, SSH2_FXP_OPENDIR, process_opendir, 0 },
{ "readdir", NULL, SSH2_FXP_READDIR, process_readdir, 0 },
{ "remove", NULL, SSH2_FXP_REMOVE, process_remove, 1 },
{ "mkdir", NULL, SSH2_FXP_MKDIR, process_mkdir, 1 },
{ "rmdir", NULL, SSH2_FXP_RMDIR, process_rmdir, 1 },
{ "realpath", NULL, SSH2_FXP_REALPATH, process_realpath, 0 },
{ "stat", NULL, SSH2_FXP_STAT, process_stat, 0 },
{ "rename", NULL, SSH2_FXP_RENAME, process_rename, 1 },
{ "readlink", NULL, SSH2_FXP_READLINK, process_readlink, 0 },
{ "symlink", NULL, SSH2_FXP_SYMLINK, process_symlink, 1 },
{ NULL, NULL, 0, NULL, 0 }
};
/* SSH2_FXP_EXTENDED submessages */
struct sftp_handler extended_handlers[] = {
{ "posix-rename", "posix-rename@openssh.com", 0,
process_extended_posix_rename, 1 },
{ "statvfs", "statvfs@openssh.com", 0, process_extended_statvfs, 0 },
{ "fstatvfs", "fstatvfs@openssh.com", 0, process_extended_fstatvfs, 0 },
{ "hardlink", "hardlink@openssh.com", 0, process_extended_hardlink, 1 },
{ "fsync", "fsync@openssh.com", 0, process_extended_fsync, 1 },
{ NULL, NULL, 0, NULL, 0 }
};
static int
request_permitted(struct sftp_handler *h)
{
char *result;
if (readonly && h->does_write) {
verbose("Refusing %s request in read-only mode", h->name);
return 0;
}
if (request_blacklist != NULL &&
((result = match_list(h->name, request_blacklist, NULL))) != NULL) {
free(result);
verbose("Refusing blacklisted %s request", h->name);
return 0;
}
if (request_whitelist != NULL &&
((result = match_list(h->name, request_whitelist, NULL))) != NULL) {
free(result);
debug2("Permitting whitelisted %s request", h->name);
return 1;
}
if (request_whitelist != NULL) {
verbose("Refusing non-whitelisted %s request", h->name);
return 0;
}
return 1;
}
static int
errno_to_portable(int unixerrno)
{
int ret = 0;
switch (unixerrno) {
case 0:
ret = SSH2_FX_OK;
break;
case ENOENT:
case ENOTDIR:
case EBADF:
case ELOOP:
ret = SSH2_FX_NO_SUCH_FILE;
break;
case EPERM:
case EACCES:
case EFAULT:
ret = SSH2_FX_PERMISSION_DENIED;
break;
case ENAMETOOLONG:
case EINVAL:
ret = SSH2_FX_BAD_MESSAGE;
break;
case ENOSYS:
ret = SSH2_FX_OP_UNSUPPORTED;
break;
default:
ret = SSH2_FX_FAILURE;
break;
}
return ret;
}
static int
flags_from_portable(int pflags)
{
int flags = 0;
if ((pflags & SSH2_FXF_READ) &&
(pflags & SSH2_FXF_WRITE)) {
flags = O_RDWR;
} else if (pflags & SSH2_FXF_READ) {
flags = O_RDONLY;
} else if (pflags & SSH2_FXF_WRITE) {
flags = O_WRONLY;
}
if (pflags & SSH2_FXF_APPEND)
flags |= O_APPEND;
if (pflags & SSH2_FXF_CREAT)
flags |= O_CREAT;
if (pflags & SSH2_FXF_TRUNC)
flags |= O_TRUNC;
if (pflags & SSH2_FXF_EXCL)
flags |= O_EXCL;
return flags;
}
static const char *
string_from_portable(int pflags)
{
static char ret[128];
*ret = '\0';
#define PAPPEND(str) { \
if (*ret != '\0') \
strlcat(ret, ",", sizeof(ret)); \
strlcat(ret, str, sizeof(ret)); \
}
if (pflags & SSH2_FXF_READ)
PAPPEND("READ")
if (pflags & SSH2_FXF_WRITE)
PAPPEND("WRITE")
if (pflags & SSH2_FXF_APPEND)
PAPPEND("APPEND")
if (pflags & SSH2_FXF_CREAT)
PAPPEND("CREATE")
if (pflags & SSH2_FXF_TRUNC)
PAPPEND("TRUNCATE")
if (pflags & SSH2_FXF_EXCL)
PAPPEND("EXCL")
return ret;
}
/* handle handles */
typedef struct Handle Handle;
struct Handle {
int use;
DIR *dirp;
int fd;
int flags;
char *name;
u_int64_t bytes_read, bytes_write;
int next_unused;
};
enum {
HANDLE_UNUSED,
HANDLE_DIR,
HANDLE_FILE
};
Handle *handles = NULL;
u_int num_handles = 0;
int first_unused_handle = -1;
static void handle_unused(int i)
{
handles[i].use = HANDLE_UNUSED;
handles[i].next_unused = first_unused_handle;
first_unused_handle = i;
}
static int
handle_new(int use, const char *name, int fd, int flags, DIR *dirp)
{
int i;
if (first_unused_handle == -1) {
if (num_handles + 1 <= num_handles)
return -1;
num_handles++;
handles = xreallocarray(handles, num_handles, sizeof(Handle));
handle_unused(num_handles - 1);
}
i = first_unused_handle;
first_unused_handle = handles[i].next_unused;
handles[i].use = use;
handles[i].dirp = dirp;
handles[i].fd = fd;
handles[i].flags = flags;
handles[i].name = xstrdup(name);
handles[i].bytes_read = handles[i].bytes_write = 0;
return i;
}
static int
handle_is_ok(int i, int type)
{
return i >= 0 && (u_int)i < num_handles && handles[i].use == type;
}
static int
handle_to_string(int handle, u_char **stringp, int *hlenp)
{
if (stringp == NULL || hlenp == NULL)
return -1;
*stringp = xmalloc(sizeof(int32_t));
put_u32(*stringp, handle);
*hlenp = sizeof(int32_t);
return 0;
}
static int
handle_from_string(const u_char *handle, u_int hlen)
{
int val;
if (hlen != sizeof(int32_t))
return -1;
val = get_u32(handle);
if (handle_is_ok(val, HANDLE_FILE) ||
handle_is_ok(val, HANDLE_DIR))
return val;
return -1;
}
static char *
handle_to_name(int handle)
{
if (handle_is_ok(handle, HANDLE_DIR)||
handle_is_ok(handle, HANDLE_FILE))
return handles[handle].name;
return NULL;
}
static DIR *
handle_to_dir(int handle)
{
if (handle_is_ok(handle, HANDLE_DIR))
return handles[handle].dirp;
return NULL;
}
static int
handle_to_fd(int handle)
{
if (handle_is_ok(handle, HANDLE_FILE))
return handles[handle].fd;
return -1;
}
static int
handle_to_flags(int handle)
{
if (handle_is_ok(handle, HANDLE_FILE))
return handles[handle].flags;
return 0;
}
static void
handle_update_read(int handle, ssize_t bytes)
{
if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
handles[handle].bytes_read += bytes;
}
static void
handle_update_write(int handle, ssize_t bytes)
{
if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
handles[handle].bytes_write += bytes;
}
static u_int64_t
handle_bytes_read(int handle)
{
if (handle_is_ok(handle, HANDLE_FILE))
return (handles[handle].bytes_read);
return 0;
}
static u_int64_t
handle_bytes_write(int handle)
{
if (handle_is_ok(handle, HANDLE_FILE))
return (handles[handle].bytes_write);
return 0;
}
static int
handle_close(int handle)
{
int ret = -1;
if (handle_is_ok(handle, HANDLE_FILE)) {
ret = close(handles[handle].fd);
free(handles[handle].name);
handle_unused(handle);
} else if (handle_is_ok(handle, HANDLE_DIR)) {
ret = closedir(handles[handle].dirp);
free(handles[handle].name);
handle_unused(handle);
} else {
errno = ENOENT;
}
return ret;
}
static void
handle_log_close(int handle, char *emsg)
{
if (handle_is_ok(handle, HANDLE_FILE)) {
logit("%s%sclose \"%s\" bytes read %llu written %llu",
emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
handle_to_name(handle),
(unsigned long long)handle_bytes_read(handle),
(unsigned long long)handle_bytes_write(handle));
} else {
logit("%s%sclosedir \"%s\"",
emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
handle_to_name(handle));
}
}
static void
handle_log_exit(void)
{
u_int i;
for (i = 0; i < num_handles; i++)
if (handles[i].use != HANDLE_UNUSED)
handle_log_close(i, "forced");
}
static int
get_handle(struct sshbuf *queue, int *hp)
{
u_char *handle;
int r;
size_t hlen;
*hp = -1;
if ((r = sshbuf_get_string(queue, &handle, &hlen)) != 0)
return r;
if (hlen < 256)
*hp = handle_from_string(handle, hlen);
free(handle);
return 0;
}
/* send replies */
static void
send_msg(struct sshbuf *m)
{
int r;
if ((r = sshbuf_put_stringb(oqueue, m)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
sshbuf_reset(m);
}
static const char *
status_to_message(u_int32_t status)
{
const char *status_messages[] = {
"Success", /* SSH_FX_OK */
"End of file", /* SSH_FX_EOF */
"No such file", /* SSH_FX_NO_SUCH_FILE */
"Permission denied", /* SSH_FX_PERMISSION_DENIED */
"Failure", /* SSH_FX_FAILURE */
"Bad message", /* SSH_FX_BAD_MESSAGE */
"No connection", /* SSH_FX_NO_CONNECTION */
"Connection lost", /* SSH_FX_CONNECTION_LOST */
"Operation unsupported", /* SSH_FX_OP_UNSUPPORTED */
"Unknown error" /* Others */
};
return (status_messages[MINIMUM(status,SSH2_FX_MAX)]);
}
static void
send_status(u_int32_t id, u_int32_t status)
{
struct sshbuf *msg;
int r;
debug3("request %u: sent status %u", id, status);
if (log_level > SYSLOG_LEVEL_VERBOSE ||
(status != SSH2_FX_OK && status != SSH2_FX_EOF))
logit("sent status %s", status_to_message(status));
if ((msg = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((r = sshbuf_put_u8(msg, SSH2_FXP_STATUS)) != 0 ||
(r = sshbuf_put_u32(msg, id)) != 0 ||
(r = sshbuf_put_u32(msg, status)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
if (version >= 3) {
if ((r = sshbuf_put_cstring(msg,
status_to_message(status))) != 0 ||
(r = sshbuf_put_cstring(msg, "")) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
}
send_msg(msg);
sshbuf_free(msg);
}
static void
send_data_or_handle(char type, u_int32_t id, const u_char *data, int dlen)
{
struct sshbuf *msg;
int r;
if ((msg = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((r = sshbuf_put_u8(msg, type)) != 0 ||
(r = sshbuf_put_u32(msg, id)) != 0 ||
(r = sshbuf_put_string(msg, data, dlen)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
send_msg(msg);
sshbuf_free(msg);
}
static void
send_data(u_int32_t id, const u_char *data, int dlen)
{
debug("request %u: sent data len %d", id, dlen);
send_data_or_handle(SSH2_FXP_DATA, id, data, dlen);
}
static void
send_handle(u_int32_t id, int handle)
{
u_char *string;
int hlen;
handle_to_string(handle, &string, &hlen);
debug("request %u: sent handle handle %d", id, handle);
send_data_or_handle(SSH2_FXP_HANDLE, id, string, hlen);
free(string);
}
static void
send_names(u_int32_t id, int count, const Stat *stats)
{
struct sshbuf *msg;
int i, r;
if ((msg = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((r = sshbuf_put_u8(msg, SSH2_FXP_NAME)) != 0 ||
(r = sshbuf_put_u32(msg, id)) != 0 ||
(r = sshbuf_put_u32(msg, count)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: sent names count %d", id, count);
for (i = 0; i < count; i++) {
if ((r = sshbuf_put_cstring(msg, stats[i].name)) != 0 ||
(r = sshbuf_put_cstring(msg, stats[i].long_name)) != 0 ||
(r = encode_attrib(msg, &stats[i].attrib)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
}
send_msg(msg);
sshbuf_free(msg);
}
static void
send_attrib(u_int32_t id, const Attrib *a)
{
struct sshbuf *msg;
int r;
debug("request %u: sent attrib have 0x%x", id, a->flags);
if ((msg = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((r = sshbuf_put_u8(msg, SSH2_FXP_ATTRS)) != 0 ||
(r = sshbuf_put_u32(msg, id)) != 0 ||
(r = encode_attrib(msg, a)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
send_msg(msg);
sshbuf_free(msg);
}
static void
send_statvfs(u_int32_t id, struct statvfs *st)
{
struct sshbuf *msg;
u_int64_t flag;
int r;
flag = (st->f_flag & ST_RDONLY) ? SSH2_FXE_STATVFS_ST_RDONLY : 0;
flag |= (st->f_flag & ST_NOSUID) ? SSH2_FXE_STATVFS_ST_NOSUID : 0;
if ((msg = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED_REPLY)) != 0 ||
(r = sshbuf_put_u32(msg, id)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_bsize)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_frsize)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_blocks)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_bfree)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_bavail)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_files)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_ffree)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_favail)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_fsid)) != 0 ||
(r = sshbuf_put_u64(msg, flag)) != 0 ||
(r = sshbuf_put_u64(msg, st->f_namemax)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
send_msg(msg);
sshbuf_free(msg);
}
/* parse incoming */
static void
process_init(void)
{
struct sshbuf *msg;
int r;
if ((r = sshbuf_get_u32(iqueue, &version)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
verbose("received client version %u", version);
if ((msg = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((r = sshbuf_put_u8(msg, SSH2_FXP_VERSION)) != 0 ||
(r = sshbuf_put_u32(msg, SSH2_FILEXFER_VERSION)) != 0 ||
/* POSIX rename extension */
(r = sshbuf_put_cstring(msg, "posix-rename@openssh.com")) != 0 ||
(r = sshbuf_put_cstring(msg, "1")) != 0 || /* version */
/* statvfs extension */
(r = sshbuf_put_cstring(msg, "statvfs@openssh.com")) != 0 ||
(r = sshbuf_put_cstring(msg, "2")) != 0 || /* version */
/* fstatvfs extension */
(r = sshbuf_put_cstring(msg, "fstatvfs@openssh.com")) != 0 ||
(r = sshbuf_put_cstring(msg, "2")) != 0 || /* version */
/* hardlink extension */
(r = sshbuf_put_cstring(msg, "hardlink@openssh.com")) != 0 ||
(r = sshbuf_put_cstring(msg, "1")) != 0 || /* version */
/* fsync extension */
(r = sshbuf_put_cstring(msg, "fsync@openssh.com")) != 0 ||
(r = sshbuf_put_cstring(msg, "1")) != 0) /* version */
fatal("%s: buffer error: %s", __func__, ssh_err(r));
send_msg(msg);
sshbuf_free(msg);
}
static void
process_open(u_int32_t id)
{
u_int32_t pflags;
Attrib a;
char *name;
int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE;
if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
(r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */
(r = decode_attrib(iqueue, &a)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: open flags %d", id, pflags);
flags = flags_from_portable(pflags);
mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666;
logit("open \"%s\" flags %s mode 0%o",
name, string_from_portable(pflags), mode);
if (readonly &&
((flags & O_ACCMODE) == O_WRONLY ||
(flags & O_ACCMODE) == O_RDWR)) {
verbose("Refusing open request in read-only mode");
status = SSH2_FX_PERMISSION_DENIED;
} else {
fd = open(name, flags, mode);
if (fd < 0) {
status = errno_to_portable(errno);
} else {
handle = handle_new(HANDLE_FILE, name, fd, flags, NULL);
if (handle < 0) {
close(fd);
} else {
send_handle(id, handle);
status = SSH2_FX_OK;
}
}
}
if (status != SSH2_FX_OK)
send_status(id, status);
free(name);
}
static void
process_close(u_int32_t id)
{
int r, handle, ret, status = SSH2_FX_FAILURE;
if ((r = get_handle(iqueue, &handle)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: close handle %u", id, handle);
handle_log_close(handle, NULL);
ret = handle_close(handle);
status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
}
static void
process_read(u_int32_t id)
{
u_char buf[64*1024];
u_int32_t len;
int r, handle, fd, ret, status = SSH2_FX_FAILURE;
u_int64_t off;
if ((r = get_handle(iqueue, &handle)) != 0 ||
(r = sshbuf_get_u64(iqueue, &off)) != 0 ||
(r = sshbuf_get_u32(iqueue, &len)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: read \"%s\" (handle %d) off %llu len %d",
id, handle_to_name(handle), handle, (unsigned long long)off, len);
if (len > sizeof buf) {
len = sizeof buf;
debug2("read change len %d", len);
}
fd = handle_to_fd(handle);
if (fd >= 0) {
if (lseek(fd, off, SEEK_SET) < 0) {
error("process_read: seek failed");
status = errno_to_portable(errno);
} else {
ret = read(fd, buf, len);
if (ret < 0) {
status = errno_to_portable(errno);
} else if (ret == 0) {
status = SSH2_FX_EOF;
} else {
send_data(id, buf, ret);
status = SSH2_FX_OK;
handle_update_read(handle, ret);
}
}
}
if (status != SSH2_FX_OK)
send_status(id, status);
}
static void
process_write(u_int32_t id)
{
u_int64_t off;
size_t len;
int r, handle, fd, ret, status;
u_char *data;
if ((r = get_handle(iqueue, &handle)) != 0 ||
(r = sshbuf_get_u64(iqueue, &off)) != 0 ||
(r = sshbuf_get_string(iqueue, &data, &len)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: write \"%s\" (handle %d) off %llu len %zu",
id, handle_to_name(handle), handle, (unsigned long long)off, len);
fd = handle_to_fd(handle);
if (fd < 0)
status = SSH2_FX_FAILURE;
else {
if (!(handle_to_flags(handle) & O_APPEND) &&
lseek(fd, off, SEEK_SET) < 0) {
status = errno_to_portable(errno);
error("process_write: seek failed");
} else {
/* XXX ATOMICIO ? */
ret = write(fd, data, len);
if (ret < 0) {
error("process_write: write failed");
status = errno_to_portable(errno);
} else if ((size_t)ret == len) {
status = SSH2_FX_OK;
handle_update_write(handle, ret);
} else {
debug2("nothing at all written");
status = SSH2_FX_FAILURE;
}
}
}
send_status(id, status);
free(data);
}
static void
process_do_stat(u_int32_t id, int do_lstat)
{
Attrib a;
struct stat st;
char *name;
int r, status = SSH2_FX_FAILURE;
if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: %sstat", id, do_lstat ? "l" : "");
verbose("%sstat name \"%s\"", do_lstat ? "l" : "", name);
r = do_lstat ? lstat(name, &st) : stat(name, &st);
if (r < 0) {
status = errno_to_portable(errno);
} else {
stat_to_attrib(&st, &a);
send_attrib(id, &a);
status = SSH2_FX_OK;
}
if (status != SSH2_FX_OK)
send_status(id, status);
free(name);
}
static void
process_stat(u_int32_t id)
{
process_do_stat(id, 0);
}
static void
process_lstat(u_int32_t id)
{
process_do_stat(id, 1);
}
static void
process_fstat(u_int32_t id)
{
Attrib a;
struct stat st;
int fd, r, handle, status = SSH2_FX_FAILURE;
if ((r = get_handle(iqueue, &handle)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: fstat \"%s\" (handle %u)",
id, handle_to_name(handle), handle);
fd = handle_to_fd(handle);
if (fd >= 0) {
r = fstat(fd, &st);
if (r < 0) {
status = errno_to_portable(errno);
} else {
stat_to_attrib(&st, &a);
send_attrib(id, &a);
status = SSH2_FX_OK;
}
}
if (status != SSH2_FX_OK)
send_status(id, status);
}
static struct timeval *
attrib_to_tv(const Attrib *a)
{
static struct timeval tv[2];
tv[0].tv_sec = a->atime;
tv[0].tv_usec = 0;
tv[1].tv_sec = a->mtime;
tv[1].tv_usec = 0;
return tv;
}
static void
process_setstat(u_int32_t id)
{
Attrib a;
char *name;
int r, status = SSH2_FX_OK;
if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
(r = decode_attrib(iqueue, &a)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: setstat name \"%s\"", id, name);
if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
logit("set \"%s\" size %llu",
name, (unsigned long long)a.size);
r = truncate(name, a.size);
if (r == -1)
status = errno_to_portable(errno);
}
if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
logit("set \"%s\" mode %04o", name, a.perm);
r = chmod(name, a.perm & 07777);
if (r == -1)
status = errno_to_portable(errno);
}
if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
char buf[64];
time_t t = a.mtime;
strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
localtime(&t));
logit("set \"%s\" modtime %s", name, buf);
r = utimes(name, attrib_to_tv(&a));
if (r == -1)
status = errno_to_portable(errno);
}
if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
logit("set \"%s\" owner %lu group %lu", name,
(u_long)a.uid, (u_long)a.gid);
r = chown(name, a.uid, a.gid);
if (r == -1)
status = errno_to_portable(errno);
}
send_status(id, status);
free(name);
}
static void
process_fsetstat(u_int32_t id)
{
Attrib a;
int handle, fd, r;
int status = SSH2_FX_OK;
if ((r = get_handle(iqueue, &handle)) != 0 ||
(r = decode_attrib(iqueue, &a)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: fsetstat handle %d", id, handle);
fd = handle_to_fd(handle);
if (fd < 0)
status = SSH2_FX_FAILURE;
else {
char *name = handle_to_name(handle);
if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
logit("set \"%s\" size %llu",
name, (unsigned long long)a.size);
r = ftruncate(fd, a.size);
if (r == -1)
status = errno_to_portable(errno);
}
if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
logit("set \"%s\" mode %04o", name, a.perm);
r = fchmod(fd, a.perm & 07777);
if (r == -1)
status = errno_to_portable(errno);
}
if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
char buf[64];
time_t t = a.mtime;
strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
localtime(&t));
logit("set \"%s\" modtime %s", name, buf);
r = futimes(fd, attrib_to_tv(&a));
if (r == -1)
status = errno_to_portable(errno);
}
if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
logit("set \"%s\" owner %lu group %lu", name,
(u_long)a.uid, (u_long)a.gid);
r = fchown(fd, a.uid, a.gid);
if (r == -1)
status = errno_to_portable(errno);
}
}
send_status(id, status);
}
static void
process_opendir(u_int32_t id)
{
DIR *dirp = NULL;
char *path;
int r, handle, status = SSH2_FX_FAILURE;
if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: opendir", id);
logit("opendir \"%s\"", path);
dirp = opendir(path);
if (dirp == NULL) {
status = errno_to_portable(errno);
} else {
handle = handle_new(HANDLE_DIR, path, 0, 0, dirp);
if (handle < 0) {
closedir(dirp);
} else {
send_handle(id, handle);
status = SSH2_FX_OK;
}
}
if (status != SSH2_FX_OK)
send_status(id, status);
free(path);
}
static void
process_readdir(u_int32_t id)
{
DIR *dirp;
struct dirent *dp;
char *path;
int r, handle;
if ((r = get_handle(iqueue, &handle)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: readdir \"%s\" (handle %d)", id,
handle_to_name(handle), handle);
dirp = handle_to_dir(handle);
path = handle_to_name(handle);
if (dirp == NULL || path == NULL) {
send_status(id, SSH2_FX_FAILURE);
} else {
struct stat st;
char pathname[PATH_MAX];
Stat *stats;
int nstats = 10, count = 0, i;
stats = xcalloc(nstats, sizeof(Stat));
while ((dp = readdir(dirp)) != NULL) {
if (count >= nstats) {
nstats *= 2;
stats = xreallocarray(stats, nstats, sizeof(Stat));
}
/* XXX OVERFLOW ? */
snprintf(pathname, sizeof pathname, "%s%s%s", path,
strcmp(path, "/") ? "/" : "", dp->d_name);
if (lstat(pathname, &st) < 0)
continue;
stat_to_attrib(&st, &(stats[count].attrib));
stats[count].name = xstrdup(dp->d_name);
stats[count].long_name = ls_file(dp->d_name, &st, 0, 0);
count++;
/* send up to 100 entries in one message */
/* XXX check packet size instead */
if (count == 100)
break;
}
if (count > 0) {
send_names(id, count, stats);
for (i = 0; i < count; i++) {
free(stats[i].name);
free(stats[i].long_name);
}
} else {
send_status(id, SSH2_FX_EOF);
}
free(stats);
}
}
static void
process_remove(u_int32_t id)
{
char *name;
int r, status = SSH2_FX_FAILURE;
if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: remove", id);
logit("remove name \"%s\"", name);
r = unlink(name);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
free(name);
}
static void
process_mkdir(u_int32_t id)
{
Attrib a;
char *name;
int r, mode, status = SSH2_FX_FAILURE;
if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
(r = decode_attrib(iqueue, &a)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ?
a.perm & 07777 : 0777;
debug3("request %u: mkdir", id);
logit("mkdir name \"%s\" mode 0%o", name, mode);
r = mkdir(name, mode);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
free(name);
}
static void
process_rmdir(u_int32_t id)
{
char *name;
int r, status;
if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: rmdir", id);
logit("rmdir name \"%s\"", name);
r = rmdir(name);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
free(name);
}
static void
process_realpath(u_int32_t id)
{
char resolvedname[PATH_MAX];
char *path;
int r;
if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
if (path[0] == '\0') {
free(path);
path = xstrdup(".");
}
debug3("request %u: realpath", id);
verbose("realpath \"%s\"", path);
if (realpath(path, resolvedname) == NULL) {
send_status(id, errno_to_portable(errno));
} else {
Stat s;
attrib_clear(&s.attrib);
s.name = s.long_name = resolvedname;
send_names(id, 1, &s);
}
free(path);
}
static void
process_rename(u_int32_t id)
{
char *oldpath, *newpath;
int r, status;
struct stat sb;
if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
(r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: rename", id);
logit("rename old \"%s\" new \"%s\"", oldpath, newpath);
status = SSH2_FX_FAILURE;
if (lstat(oldpath, &sb) == -1)
status = errno_to_portable(errno);
else if (S_ISREG(sb.st_mode)) {
/* Race-free rename of regular files */
if (link(oldpath, newpath) == -1) {
if (errno == EOPNOTSUPP) {
struct stat st;
/*
* fs doesn't support links, so fall back to
* stat+rename. This is racy.
*/
if (stat(newpath, &st) == -1) {
if (rename(oldpath, newpath) == -1)
status =
errno_to_portable(errno);
else
status = SSH2_FX_OK;
}
} else {
status = errno_to_portable(errno);
}
} else if (unlink(oldpath) == -1) {
status = errno_to_portable(errno);
/* clean spare link */
unlink(newpath);
} else
status = SSH2_FX_OK;
} else if (stat(newpath, &sb) == -1) {
if (rename(oldpath, newpath) == -1)
status = errno_to_portable(errno);
else
status = SSH2_FX_OK;
}
send_status(id, status);
free(oldpath);
free(newpath);
}
static void
process_readlink(u_int32_t id)
{
int r, len;
char buf[PATH_MAX];
char *path;
if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: readlink", id);
verbose("readlink \"%s\"", path);
if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1)
send_status(id, errno_to_portable(errno));
else {
Stat s;
buf[len] = '\0';
attrib_clear(&s.attrib);
s.name = s.long_name = buf;
send_names(id, 1, &s);
}
free(path);
}
static void
process_symlink(u_int32_t id)
{
char *oldpath, *newpath;
int r, status;
if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
(r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: symlink", id);
logit("symlink old \"%s\" new \"%s\"", oldpath, newpath);
/* this will fail if 'newpath' exists */
r = symlink(oldpath, newpath);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
free(oldpath);
free(newpath);
}
static void
process_extended_posix_rename(u_int32_t id)
{
char *oldpath, *newpath;
int r, status;
if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
(r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: posix-rename", id);
logit("posix-rename old \"%s\" new \"%s\"", oldpath, newpath);
r = rename(oldpath, newpath);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
free(oldpath);
free(newpath);
}
static void
process_extended_statvfs(u_int32_t id)
{
char *path;
struct statvfs st;
int r;
if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: statvfs", id);
logit("statvfs \"%s\"", path);
if (statvfs(path, &st) != 0)
send_status(id, errno_to_portable(errno));
else
send_statvfs(id, &st);
free(path);
}
static void
process_extended_fstatvfs(u_int32_t id)
{
int r, handle, fd;
struct statvfs st;
if ((r = get_handle(iqueue, &handle)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug("request %u: fstatvfs \"%s\" (handle %u)",
id, handle_to_name(handle), handle);
if ((fd = handle_to_fd(handle)) < 0) {
send_status(id, SSH2_FX_FAILURE);
return;
}
if (fstatvfs(fd, &st) != 0)
send_status(id, errno_to_portable(errno));
else
send_statvfs(id, &st);
}
static void
process_extended_hardlink(u_int32_t id)
{
char *oldpath, *newpath;
int r, status;
if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
(r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: hardlink", id);
logit("hardlink old \"%s\" new \"%s\"", oldpath, newpath);
r = link(oldpath, newpath);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
send_status(id, status);
free(oldpath);
free(newpath);
}
static void
process_extended_fsync(u_int32_t id)
{
int handle, fd, r, status = SSH2_FX_OP_UNSUPPORTED;
if ((r = get_handle(iqueue, &handle)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: fsync (handle %u)", id, handle);
verbose("fsync \"%s\"", handle_to_name(handle));
if ((fd = handle_to_fd(handle)) < 0)
status = SSH2_FX_NO_SUCH_FILE;
else if (handle_is_ok(handle, HANDLE_FILE)) {
r = fsync(fd);
status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
}
send_status(id, status);
}
static void
process_extended(u_int32_t id)
{
char *request;
int i, r;
if ((r = sshbuf_get_cstring(iqueue, &request, NULL)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
for (i = 0; extended_handlers[i].handler != NULL; i++) {
if (strcmp(request, extended_handlers[i].ext_name) == 0) {
if (!request_permitted(&extended_handlers[i]))
send_status(id, SSH2_FX_PERMISSION_DENIED);
else
extended_handlers[i].handler(id);
break;
}
}
if (extended_handlers[i].handler == NULL) {
error("Unknown extended request \"%.100s\"", request);
send_status(id, SSH2_FX_OP_UNSUPPORTED); /* MUST */
}
free(request);
}
/* stolen from ssh-agent */
static void
process(void)
{
u_int msg_len;
u_int buf_len;
u_int consumed;
u_char type;
const u_char *cp;
int i, r;
u_int32_t id;
buf_len = sshbuf_len(iqueue);
if (buf_len < 5)
return; /* Incomplete message. */
cp = sshbuf_ptr(iqueue);
msg_len = get_u32(cp);
if (msg_len > SFTP_MAX_MSG_LENGTH) {
error("bad message from %s local user %s",
client_addr, pw->pw_name);
sftp_server_cleanup_exit(11);
}
if (buf_len < msg_len + 4)
return;
if ((r = sshbuf_consume(iqueue, 4)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
buf_len -= 4;
if ((r = sshbuf_get_u8(iqueue, &type)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
switch (type) {
case SSH2_FXP_INIT:
process_init();
init_done = 1;
break;
case SSH2_FXP_EXTENDED:
if (!init_done)
fatal("Received extended request before init");
if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
process_extended(id);
break;
default:
if (!init_done)
fatal("Received %u request before init", type);
if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
for (i = 0; handlers[i].handler != NULL; i++) {
if (type == handlers[i].type) {
if (!request_permitted(&handlers[i])) {
send_status(id,
SSH2_FX_PERMISSION_DENIED);
} else {
handlers[i].handler(id);
}
break;
}
}
if (handlers[i].handler == NULL)
error("Unknown message %u", type);
}
/* discard the remaining bytes from the current packet */
if (buf_len < sshbuf_len(iqueue)) {
error("iqueue grew unexpectedly");
sftp_server_cleanup_exit(255);
}
consumed = buf_len - sshbuf_len(iqueue);
if (msg_len < consumed) {
error("msg_len %u < consumed %u", msg_len, consumed);
sftp_server_cleanup_exit(255);
}
if (msg_len > consumed &&
(r = sshbuf_consume(iqueue, msg_len - consumed)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
}
/* Cleanup handler that logs active handles upon normal exit */
void
sftp_server_cleanup_exit(int i)
{
if (pw != NULL && client_addr != NULL) {
handle_log_exit();
logit("session closed for local user %s from [%s]",
pw->pw_name, client_addr);
}
_exit(i);
}
static void
sftp_server_usage(void)
{
extern char *__progname;
fprintf(stderr,
"usage: %s [-ehR] [-d start_directory] [-f log_facility] "
"[-l log_level]\n\t[-P blacklisted_requests] "
"[-p whitelisted_requests] [-u umask]\n"
" %s -Q protocol_feature\n",
__progname, __progname);
exit(1);
}
int
sftp_server_main(int argc, char **argv, struct passwd *user_pw)
{
fd_set *rset, *wset;
int i, r, in, out, max, ch, skipargs = 0, log_stderr = 0;
ssize_t len, olen, set_size;
SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
char *cp, *homedir = NULL, buf[4*4096];
long mask;
extern char *optarg;
extern char *__progname;
ssh_malloc_init(); /* must be called before any mallocs */
log_init(__progname, log_level, log_facility, log_stderr);
pw = pwcopy(user_pw);
while (!skipargs && (ch = getopt(argc, argv,
"d:f:l:P:p:Q:u:cehR")) != -1) {
switch (ch) {
case 'Q':
if (strcasecmp(optarg, "requests") != 0) {
fprintf(stderr, "Invalid query type\n");
exit(1);
}
for (i = 0; handlers[i].handler != NULL; i++)
printf("%s\n", handlers[i].name);
for (i = 0; extended_handlers[i].handler != NULL; i++)
printf("%s\n", extended_handlers[i].name);
exit(0);
break;
case 'R':
readonly = 1;
break;
case 'c':
/*
* Ignore all arguments if we are invoked as a
* shell using "sftp-server -c command"
*/
skipargs = 1;
break;
case 'e':
log_stderr = 1;
break;
case 'l':
log_level = log_level_number(optarg);
if (log_level == SYSLOG_LEVEL_NOT_SET)
error("Invalid log level \"%s\"", optarg);
break;
case 'f':
log_facility = log_facility_number(optarg);
if (log_facility == SYSLOG_FACILITY_NOT_SET)
error("Invalid log facility \"%s\"", optarg);
break;
case 'd':
cp = tilde_expand_filename(optarg, user_pw->pw_uid);
homedir = percent_expand(cp, "d", user_pw->pw_dir,
"u", user_pw->pw_name, (char *)NULL);
free(cp);
break;
case 'p':
if (request_whitelist != NULL)
fatal("Permitted requests already set");
request_whitelist = xstrdup(optarg);
break;
case 'P':
if (request_blacklist != NULL)
fatal("Refused requests already set");
request_blacklist = xstrdup(optarg);
break;
case 'u':
errno = 0;
mask = strtol(optarg, &cp, 8);
if (mask < 0 || mask > 0777 || *cp != '\0' ||
cp == optarg || (mask == 0 && errno != 0))
fatal("Invalid umask \"%s\"", optarg);
(void)umask((mode_t)mask);
break;
case 'h':
default:
sftp_server_usage();
}
}
log_init(__progname, log_level, log_facility, log_stderr);
if ((cp = getenv("SSH_CONNECTION")) != NULL) {
client_addr = xstrdup(cp);
if ((cp = strchr(client_addr, ' ')) == NULL) {
error("Malformed SSH_CONNECTION variable: \"%s\"",
getenv("SSH_CONNECTION"));
sftp_server_cleanup_exit(255);
}
*cp = '\0';
} else
client_addr = xstrdup("UNKNOWN");
logit("session opened for local user %s from [%s]",
pw->pw_name, client_addr);
in = STDIN_FILENO;
out = STDOUT_FILENO;
max = 0;
if (in > max)
max = in;
if (out > max)
max = out;
if ((iqueue = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((oqueue = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
rset = xcalloc(howmany(max + 1, NFDBITS), sizeof(fd_mask));
wset = xcalloc(howmany(max + 1, NFDBITS), sizeof(fd_mask));
if (homedir != NULL) {
if (chdir(homedir) != 0) {
error("chdir to \"%s\" failed: %s", homedir,
strerror(errno));
}
}
set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask);
for (;;) {
memset(rset, 0, set_size);
memset(wset, 0, set_size);
/*
* Ensure that we can read a full buffer and handle
* the worst-case length packet it can generate,
* otherwise apply backpressure by stopping reads.
*/
if ((r = sshbuf_check_reserve(iqueue, sizeof(buf))) == 0 &&
(r = sshbuf_check_reserve(oqueue,
SFTP_MAX_MSG_LENGTH)) == 0)
FD_SET(in, rset);
else if (r != SSH_ERR_NO_BUFFER_SPACE)
fatal("%s: sshbuf_check_reserve failed: %s",
__func__, ssh_err(r));
olen = sshbuf_len(oqueue);
if (olen > 0)
FD_SET(out, wset);
if (select(max+1, rset, wset, NULL, NULL) < 0) {
if (errno == EINTR)
continue;
error("select: %s", strerror(errno));
sftp_server_cleanup_exit(2);
}
/* copy stdin to iqueue */
if (FD_ISSET(in, rset)) {
len = read(in, buf, sizeof buf);
if (len == 0) {
debug("read eof");
sftp_server_cleanup_exit(0);
} else if (len < 0) {
error("read: %s", strerror(errno));
sftp_server_cleanup_exit(1);
} else if ((r = sshbuf_put(iqueue, buf, len)) != 0) {
fatal("%s: buffer error: %s",
__func__, ssh_err(r));
}
}
/* send oqueue to stdout */
if (FD_ISSET(out, wset)) {
len = write(out, sshbuf_ptr(oqueue), olen);
if (len < 0) {
error("write: %s", strerror(errno));
sftp_server_cleanup_exit(1);
} else if ((r = sshbuf_consume(oqueue, len)) != 0) {
fatal("%s: buffer error: %s",
__func__, ssh_err(r));
}
}
/*
* Process requests from client if we can fit the results
* into the output buffer, otherwise stop processing input
* and let the output queue drain.
*/
r = sshbuf_check_reserve(oqueue, SFTP_MAX_MSG_LENGTH);
if (r == 0)
process();
else if (r != SSH_ERR_NO_BUFFER_SPACE)
fatal("%s: sshbuf_check_reserve: %s",
__func__, ssh_err(r));
}
}
| ./CrossVul/dataset_final_sorted/CWE-269/c/bad_2887_0 |
crossvul-cpp_data_bad_764_0 | #include "stdafx.h"
#include "Helper.h"
#include "Logger.h"
#ifdef WIN32
#include "dirent_windows.h"
#include <direct.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif
#if !defined(WIN32)
#include <sys/ptrace.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <fstream>
#include <math.h>
#include <algorithm>
#include "../main/localtime_r.h"
#include <sstream>
#include <openssl/md5.h>
#include <chrono>
#include <limits.h>
#include <cstring>
#if defined WIN32
#include "../msbuild/WindowsHelper.h"
#endif
#include "RFXtrx.h"
#include "../hardware/hardwaretypes.h"
// Includes for SystemUptime()
#if defined(__linux__) || defined(__linux) || defined(linux)
#include <sys/sysinfo.h>
#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
#include <time.h>
#include <errno.h>
#include <sys/sysctl.h>
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
#include <time.h>
#endif
#if defined(__FreeBSD__)
// Check if OpenBSD or DragonFly need that at well?
#include <pthread_np.h>
#ifndef PTHREAD_MAX_MAMELEN_NP
#define PTHREAD_MAX_NAMELEN_NP 32 // Arbitrary
#endif
#endif
void StringSplit(std::string str, const std::string &delim, std::vector<std::string> &results)
{
results.clear();
size_t cutAt;
while( (cutAt = str.find(delim)) != std::string::npos )
{
results.push_back(str.substr(0,cutAt));
str = str.substr(cutAt+ delim.size());
}
if (!str.empty())
{
results.push_back(str);
}
}
uint64_t hexstrtoui64(const std::string &str)
{
uint64_t ul;
std::stringstream ss;
ss << std::hex << str;
ss >> ul;
return ul;
}
void stdreplace(
std::string &inoutstring,
const std::string& replaceWhat,
const std::string& replaceWithWhat)
{
int pos = 0;
while (std::string::npos != (pos = inoutstring.find(replaceWhat, pos)))
{
inoutstring.replace(pos, replaceWhat.size(), replaceWithWhat);
pos += replaceWithWhat.size();
}
}
void stdupper(std::string &inoutstring)
{
for (size_t i = 0; i < inoutstring.size(); ++i)
inoutstring[i] = toupper(inoutstring[i]);
}
void stdlower(std::string &inoutstring)
{
std::transform(inoutstring.begin(), inoutstring.end(), inoutstring.begin(), ::tolower);
}
std::vector<std::string> GetSerialPorts(bool &bUseDirectPath)
{
bUseDirectPath=false;
std::vector<std::string> ret;
#if defined WIN32
//windows
std::vector<int> ports;
std::vector<std::string> friendlyNames;
char szPortName[40];
EnumSerialFromWMI(ports, friendlyNames);
bool bFoundPort = false;
if (!ports.empty())
{
bFoundPort = true;
for (const auto & itt : ports)
{
sprintf(szPortName, "COM%d", itt);
ret.push_back(szPortName);
}
}
if (bFoundPort)
return ret;
//Scan old fashion way (SLOW!)
COMMCONFIG cc;
DWORD dwSize = sizeof(COMMCONFIG);
for (int ii = 0; ii < 256; ii++)
{
sprintf(szPortName, "COM%d", ii);
if (GetDefaultCommConfig(szPortName, &cc, &dwSize))
{
bFoundPort = true;
sprintf(szPortName, "COM%d", ii);
//Check if we did not already have it
bool bFound = false;
for (const auto & itt : ret)
{
if (itt == szPortName)
{
bFound = true;
break;
}
}
if (!bFound)
ret.push_back(szPortName); // add port
}
}
// Method 2: CreateFile, slow
// ---------
if (!bFoundPort) {
for (int ii = 0; ii < 256; ii++)
{
sprintf(szPortName, "\\\\.\\COM%d", ii);
bool bSuccess = false;
HANDLE hPort = ::CreateFile(szPortName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
if (hPort == INVALID_HANDLE_VALUE) {
DWORD dwError = GetLastError();
//Check to see if the error was because some other app had the port open
if (dwError == ERROR_ACCESS_DENIED)
bSuccess = TRUE;
}
else {
//The port was opened successfully
bSuccess = TRUE;
//Don't forget to close the port, since we are going to do nothing with it anyway
CloseHandle(hPort);
}
if (bSuccess) {
bFoundPort = true;
sprintf(szPortName, "COM%d", ii);
ret.push_back(szPortName); // add port
}
// --------------
}
}
// Method 3: EnumSerialPortsWindows, often fails
// ---------
if (!bFoundPort) {
std::vector<SerialPortInfo> serialports;
EnumSerialPortsWindows(serialports);
if (!serialports.empty())
{
for (const auto & itt : serialports)
{
ret.push_back(itt.szPortName); // add port
}
}
}
#else
//scan /dev for /dev/ttyUSB* or /dev/ttyS* or /dev/tty.usbserial* or /dev/ttyAMA* or /dev/ttySAC*
//also scan /dev/serial/by-id/* on Linux
bool bHaveTtyAMAfree=false;
std::string sLine = "";
std::ifstream infile;
infile.open("/boot/cmdline.txt");
if (infile.is_open())
{
if (!infile.eof())
{
getline(infile, sLine);
bHaveTtyAMAfree=(sLine.find("ttyAMA0")==std::string::npos);
}
}
DIR *d=NULL;
d=opendir("/dev");
if (d != NULL)
{
struct dirent *de=NULL;
// Loop while not NULL
while ((de = readdir(d)))
{
// Only consider character devices and symbolic links
if ((de->d_type == DT_CHR) || (de->d_type == DT_LNK))
{
std::string fname = de->d_name;
if (fname.find("ttyUSB")!=std::string::npos)
{
ret.push_back("/dev/" + fname);
}
else if (fname.find("tty.usbserial")!=std::string::npos)
{
bUseDirectPath=true;
ret.push_back("/dev/" + fname);
}
else if (fname.find("ttyACM")!=std::string::npos)
{
bUseDirectPath=true;
ret.push_back("/dev/" + fname);
}
else if (fname.find("ttySAC") != std::string::npos)
{
bUseDirectPath = true;
ret.push_back("/dev/" + fname);
}
#if defined (__FreeBSD__) || defined (__OpenBSD__) || defined (__NetBSD__)
else if (fname.find("ttyU")!=std::string::npos)
{
bUseDirectPath=true;
ret.push_back("/dev/" + fname);
}
else if (fname.find("cuaU")!=std::string::npos)
{
bUseDirectPath=true;
ret.push_back("/dev/" + fname);
}
#endif
#ifdef __APPLE__
else if (fname.find("cu.")!=std::string::npos)
{
bUseDirectPath=true;
ret.push_back("/dev/" + fname);
}
#endif
if (bHaveTtyAMAfree)
{
if (fname.find("ttyAMA0")!=std::string::npos)
{
ret.push_back("/dev/" + fname);
bUseDirectPath=true;
}
// By default, this is the "small UART" on Rasberry 3 boards
if (fname.find("ttyS0")!=std::string::npos)
{
ret.push_back("/dev/" + fname);
bUseDirectPath=true;
}
// serial0 and serial1 are new with Rasbian Jessie
// Avoids confusion between Raspberry 2 and 3 boards
// More info at http://spellfoundry.com/2016/05/29/configuring-gpio-serial-port-raspbian-jessie-including-pi-3/
if (fname.find("serial")!=std::string::npos)
{
ret.push_back("/dev/" + fname);
bUseDirectPath=true;
}
}
}
}
closedir(d);
}
//also scan in /dev/usb
d=opendir("/dev/usb");
if (d != NULL)
{
struct dirent *de=NULL;
// Loop while not NULL
while ((de = readdir(d)))
{
std::string fname = de->d_name;
if (fname.find("ttyUSB")!=std::string::npos)
{
bUseDirectPath=true;
ret.push_back("/dev/usb/" + fname);
}
}
closedir(d);
}
#if defined(__linux__) || defined(__linux) || defined(linux)
d=opendir("/dev/serial/by-id");
if (d != NULL)
{
struct dirent *de=NULL;
// Loop while not NULL
while ((de = readdir(d)))
{
// Only consider symbolic links
if (de->d_type == DT_LNK)
{
std::string fname = de->d_name;
ret.push_back("/dev/serial/by-id/" + fname);
}
}
closedir(d);
}
#endif
#endif
return ret;
}
bool file_exist (const char *filename)
{
struct stat sbuffer;
return (stat(filename, &sbuffer) == 0);
}
double CalculateAltitudeFromPressure(double pressure)
{
double seaLevelPressure=101325.0;
double altitude = 44330.0 * (1.0 - pow( (pressure / seaLevelPressure), 0.1903));
return altitude;
}
/**************************************************************************/
/*!
Calculates the altitude (in meters) from the specified atmospheric
pressure (in hPa), sea-level pressure (in hPa), and temperature (in °C)
@param seaLevel Sea-level pressure in hPa
@param atmospheric Atmospheric pressure in hPa
@param temp Temperature in degrees Celsius
*/
/**************************************************************************/
float pressureToAltitude(float seaLevel, float atmospheric, float temp)
{
/* Hyposometric formula: */
/* */
/* ((P0/P)^(1/5.257) - 1) * (T + 273.15) */
/* h = ------------------------------------- */
/* 0.0065 */
/* */
/* where: h = height (in meters) */
/* P0 = sea-level pressure (in hPa) */
/* P = atmospheric pressure (in hPa) */
/* T = temperature (in °C) */
return (((float)pow((seaLevel / atmospheric), 0.190223F) - 1.0F)
* (temp + 273.15F)) / 0.0065F;
}
/**************************************************************************/
/*!
Calculates the sea-level pressure (in hPa) based on the current
altitude (in meters), atmospheric pressure (in hPa), and temperature
(in °C)
@param altitude altitude in meters
@param atmospheric Atmospheric pressure in hPa
@param temp Temperature in degrees Celsius
*/
/**************************************************************************/
float pressureSeaLevelFromAltitude(float altitude, float atmospheric, float temp)
{
/* Sea-level pressure: */
/* */
/* 0.0065*h */
/* P0 = P * (1 - ----------------- ) ^ -5.257 */
/* T+0.0065*h+273.15 */
/* */
/* where: P0 = sea-level pressure (in hPa) */
/* P = atmospheric pressure (in hPa) */
/* h = altitude (in meters) */
/* T = Temperature (in °C) */
return atmospheric * (float)pow((1.0F - (0.0065F * altitude) /
(temp + 0.0065F * altitude + 273.15F)), -5.257F);
}
std::string &stdstring_ltrim(std::string &s)
{
while (!s.empty())
{
if (s[0] != ' ')
return s;
s = s.substr(1);
}
// s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
std::string &stdstring_rtrim(std::string &s)
{
while (!s.empty())
{
if (s[s.size() - 1] != ' ')
return s;
s = s.substr(0, s.size() - 1);
}
//s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
std::string &stdstring_trim(std::string &s)
{
return stdstring_ltrim(stdstring_rtrim(s));
}
double CalculateDewPoint(double temp, int humidity)
{
if (humidity==0)
return temp;
double dew_numer = 243.04*(log(double(humidity)/100.0)+((17.625*temp)/(temp+243.04)));
double dew_denom = 17.625-log(double(humidity)/100.0)-((17.625*temp)/(temp+243.04));
if (dew_numer==0)
dew_numer=1;
return dew_numer/dew_denom;
}
uint32_t IPToUInt(const std::string &ip)
{
int a, b, c, d;
uint32_t addr = 0;
if (sscanf(ip.c_str(), "%d.%d.%d.%d", &a, &b, &c, &d) != 4)
return 0;
addr = a << 24;
addr |= b << 16;
addr |= c << 8;
addr |= d;
return addr;
}
bool isInt(const std::string &s)
{
for(size_t i = 0; i < s.length(); i++){
if(!isdigit(s[i]))
return false;
}
return true;
}
void sleep_seconds(const long seconds)
{
std::this_thread::sleep_for(std::chrono::seconds(seconds));
}
void sleep_milliseconds(const long milliseconds)
{
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
}
int createdir(const char *szDirName, int secattr)
{
int ret = 0;
#ifdef WIN32
ret = _mkdir(szDirName);
#else
ret = mkdir(szDirName, secattr);
#endif
return ret;
}
int mkdir_deep(const char *szDirName, int secattr)
{
char DirName[260];
DirName[0] = 0;
const char* p = szDirName;
char* q = DirName;
int ret = 0;
while(*p)
{
if (('\\' == *p) || ('/' == *p))
{
if (':' != *(p-1))
{
ret = createdir(DirName, secattr);
}
}
*q++ = *p++;
*q = '\0';
}
if (DirName[0])
{
ret = createdir(DirName, secattr);
}
return ret;
}
int RemoveDir(const std::string &dirnames, std::string &errorPath)
{
std::vector<std::string> splitresults;
StringSplit(dirnames, "|", splitresults);
int returncode = 0;
if (!splitresults.empty())
{
#ifdef WIN32
for (size_t i = 0; i < splitresults.size(); i++)
{
if (!file_exist(splitresults[i].c_str()))
continue;
size_t s_szLen = strlen(splitresults[i].c_str());
if (s_szLen < MAX_PATH)
{
char deletePath[MAX_PATH + 1];
strcpy_s(deletePath, splitresults[i].c_str());
deletePath[s_szLen + 1] = '\0'; // SHFILEOPSTRUCT needs an additional null char
SHFILEOPSTRUCT shfo = { NULL, FO_DELETE, deletePath, NULL, FOF_SILENT | FOF_NOERRORUI | FOF_NOCONFIRMATION, FALSE, NULL, NULL };
if (returncode = SHFileOperation(&shfo))
{
errorPath = splitresults[i];
break;
}
}
}
#else
for (size_t i = 0; i < splitresults.size(); i++)
{
if (!file_exist(splitresults[i].c_str()))
continue;
ExecuteCommandAndReturn("rm -rf \"" + splitresults[i] + "\"", returncode);
if (returncode)
{
errorPath = splitresults[i];
break;
}
}
#endif
}
return returncode;
}
double ConvertToCelsius(const double Fahrenheit)
{
return (Fahrenheit-32.0) * 0.5556;
}
double ConvertToFahrenheit(const double Celsius)
{
return (Celsius*1.8)+32.0;
}
double RoundDouble(const long double invalue, const short numberOfPrecisions)
{
long long p = (long long) pow(10.0L, numberOfPrecisions);
double ret= (long long)(invalue * p + 0.5L) / (double)p;
return ret;
}
double ConvertTemperature(const double tValue, const unsigned char tSign)
{
if (tSign=='C')
return tValue;
return RoundDouble(ConvertToFahrenheit(tValue),1);
}
std::vector<std::string> ExecuteCommandAndReturn(const std::string &szCommand, int &returncode)
{
std::vector<std::string> ret;
try
{
FILE *fp;
/* Open the command for reading. */
#ifdef WIN32
fp = _popen(szCommand.c_str(), "r");
#else
fp = popen(szCommand.c_str(), "r");
#endif
if (fp != NULL)
{
char path[1035];
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path) - 1, fp) != NULL)
{
ret.push_back(path);
}
/* close */
#ifdef WIN32
returncode = _pclose(fp);
#else
returncode = pclose(fp);
#endif
}
}
catch (...)
{
}
return ret;
}
std::string TimeToString(const time_t *ltime, const _eTimeFormat format)
{
struct tm timeinfo;
struct timeval tv;
std::stringstream sstr;
if (ltime == NULL) // current time
{
#ifdef CLOCK_REALTIME
struct timespec ts;
if (!clock_gettime(CLOCK_REALTIME, &ts))
{
tv.tv_sec = ts.tv_sec;
tv.tv_usec = ts.tv_nsec / 1000;
}
else
#endif
gettimeofday(&tv, NULL);
#ifdef WIN32
time_t tv_sec = tv.tv_sec;
localtime_r(&tv_sec, &timeinfo);
#else
localtime_r(&tv.tv_sec, &timeinfo);
#endif
}
else
localtime_r(ltime, &timeinfo);
if (format > TF_Time)
{
//Date
sstr << (timeinfo.tm_year + 1900) << "-"
<< std::setw(2) << std::setfill('0') << (timeinfo.tm_mon + 1) << "-"
<< std::setw(2) << std::setfill('0') << timeinfo.tm_mday;
}
if (format != TF_Date)
{
//Time
if (format > TF_Time)
sstr << " ";
sstr
<< std::setw(2) << std::setfill('0') << timeinfo.tm_hour << ":"
<< std::setw(2) << std::setfill('0') << timeinfo.tm_min << ":"
<< std::setw(2) << std::setfill('0') << timeinfo.tm_sec;
}
if (format > TF_DateTime && ltime == NULL)
sstr << "." << std::setw(3) << std::setfill('0') << ((int)tv.tv_usec / 1000);
return sstr.str();
}
std::string GenerateMD5Hash(const std::string &InputString, const std::string &Salt)
{
std::string cstring = InputString + Salt;
unsigned char digest[MD5_DIGEST_LENGTH + 1];
digest[MD5_DIGEST_LENGTH] = 0;
MD5((const unsigned char*)cstring.c_str(), cstring.size(), (unsigned char*)&digest);
char mdString[(MD5_DIGEST_LENGTH * 2) + 1];
mdString[MD5_DIGEST_LENGTH * 2] = 0;
for (int i = 0; i < 16; i++)
sprintf(&mdString[i * 2], "%02x", (unsigned int)digest[i]);
return mdString;
}
void hsb2rgb(const float hue, const float saturation, const float vlue, int &outR, int &outG, int &outB, const double maxValue/* = 100.0 */)
{
double hh, p, q, t, ff;
long i;
if(saturation <= 0.0) {
outR = int(vlue*maxValue);
outG = int(vlue*maxValue);
outB = int(vlue*maxValue);
}
hh = hue;
if (hh >= 360.0) hh = 0.0;
hh /= 60.0;
i = (long)hh;
ff = hh - i;
p = vlue * (1.0 - saturation);
q = vlue * (1.0 - (saturation * ff));
t = vlue * (1.0 - (saturation * (1.0 - ff)));
switch (i) {
case 0:
outR = int(vlue*maxValue);
outG = int(t*maxValue);
outB = int(p*maxValue);
break;
case 1:
outR = int(q*maxValue);
outG = int(vlue*maxValue);
outB = int(p*maxValue);
break;
case 2:
outR = int(p*maxValue);
outG = int(vlue*maxValue);
outB = int(t*maxValue);
break;
case 3:
outR = int(p*maxValue);
outG = int(q*maxValue);
outB = int(vlue*maxValue);
break;
case 4:
outR = int(t*maxValue);
outG = int(p*maxValue);
outB = int(vlue*maxValue);
break;
case 5:
default:
outR = int(vlue*maxValue);
outG = int(p*maxValue);
outB = int(q*maxValue);
break;
}
}
void rgb2hsb(const int r, const int g, const int b, float hsbvals[3])
{
float hue, saturation, brightness;
if (hsbvals == NULL)
return;
int cmax = (r > g) ? r : g;
if (b > cmax) cmax = b;
int cmin = (r < g) ? r : g;
if (b < cmin) cmin = b;
brightness = ((float)cmax) / 255.0f;
if (cmax != 0)
saturation = ((float)(cmax - cmin)) / ((float)cmax);
else
saturation = 0;
if (saturation == 0)
hue = 0;
else {
float redc = ((float)(cmax - r)) / ((float)(cmax - cmin));
float greenc = ((float)(cmax - g)) / ((float)(cmax - cmin));
float bluec = ((float)(cmax - b)) / ((float)(cmax - cmin));
if (r == cmax)
hue = bluec - greenc;
else if (g == cmax)
hue = 2.0f + redc - bluec;
else
hue = 4.0f + greenc - redc;
hue = hue / 6.0f;
if (hue < 0)
hue = hue + 1.0f;
}
hsbvals[0] = hue;
hsbvals[1] = saturation;
hsbvals[2] = brightness;
}
bool is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && (isdigit(*it) || (*it == '.') || (*it == '-') || (*it == ' ') || (*it == 0x00))) ++it;
return !s.empty() && it == s.end();
}
void padLeft(std::string &str, const size_t num, const char paddingChar)
{
if (num > str.size())
str.insert(0, num - str.size(), paddingChar);
}
bool IsLightOrSwitch(const int devType, const int subType)
{
bool bIsLightSwitch = false;
switch (devType)
{
case pTypeLighting1:
case pTypeLighting2:
case pTypeLighting3:
case pTypeLighting4:
case pTypeLighting5:
case pTypeLighting6:
case pTypeFan:
case pTypeColorSwitch:
case pTypeSecurity1:
case pTypeSecurity2:
case pTypeCurtain:
case pTypeBlinds:
case pTypeRFY:
case pTypeThermostat2:
case pTypeThermostat3:
case pTypeThermostat4:
case pTypeRemote:
case pTypeGeneralSwitch:
case pTypeHomeConfort:
case pTypeFS20:
bIsLightSwitch = true;
break;
case pTypeRadiator1:
bIsLightSwitch = (subType == sTypeSmartwaresSwitchRadiator);
break;
}
return bIsLightSwitch;
}
int MStoBeaufort(const float ms)
{
if (ms < 0.3f)
return 0;
if (ms < 1.5f)
return 1;
if (ms < 3.3f)
return 2;
if (ms < 5.5f)
return 3;
if (ms < 8.0f)
return 4;
if (ms < 10.8f)
return 5;
if (ms < 13.9f)
return 6;
if (ms < 17.2f)
return 7;
if (ms < 20.7f)
return 8;
if (ms < 24.5f)
return 9;
if (ms < 28.4f)
return 10;
if (ms < 32.6f)
return 11;
return 12;
}
void FixFolderEnding(std::string &folder)
{
#if defined(WIN32)
if (folder.at(folder.length() - 1) != '\\')
folder += "\\";
#else
if (folder.at(folder.length() - 1) != '/')
folder += "/";
#endif
}
bool dirent_is_directory(const std::string &dir, struct dirent *ent)
{
if (ent->d_type == DT_DIR)
return true;
#ifndef WIN32
if (ent->d_type == DT_LNK)
return true;
if (ent->d_type == DT_UNKNOWN) {
std::string fname = dir + "/" + ent->d_name;
struct stat st;
if (!lstat(fname.c_str(), &st))
return S_ISDIR(st.st_mode);
}
#endif
return false;
}
bool dirent_is_file(const std::string &dir, struct dirent *ent)
{
if (ent->d_type == DT_REG)
return true;
#ifndef WIN32
if (ent->d_type == DT_UNKNOWN) {
std::string fname = dir + "/" + ent->d_name;
struct stat st;
if (!lstat(fname.c_str(), &st))
return S_ISREG(st.st_mode);
}
#endif
return false;
}
/*!
* List entries of a directory.
* @param entries A string vector containing the result
* @param dir Target directory for listing
* @param bInclDirs Boolean flag to include directories in the result
* @param bInclFiles Boolean flag to include regular files in the result
*/
void DirectoryListing(std::vector<std::string>& entries, const std::string &dir, bool bInclDirs, bool bInclFiles)
{
DIR *d = NULL;
struct dirent *ent;
if ((d = opendir(dir.c_str())) != NULL)
{
while ((ent = readdir(d)) != NULL) {
std::string name = ent->d_name;
if (bInclDirs && dirent_is_directory(dir, ent) && name != "." && name != "..") {
entries.push_back(name);
continue;
}
if (bInclFiles && dirent_is_file(dir, ent)) {
entries.push_back(name);
continue;
}
}
closedir(d);
}
return;
}
std::string GenerateUserAgent()
{
srand((unsigned int)time(NULL));
int cversion = rand() % 0xFFFF;
int mversion = rand() % 3;
int sversion = rand() % 3;
std::stringstream sstr;
sstr << "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/" << (601 + sversion) << "." << (36+mversion) << " (KHTML, like Gecko) Chrome/" << (53 + mversion) << ".0." << cversion << ".0 Safari/" << (601 + sversion) << "." << (36+sversion);
return sstr.str();
}
std::string MakeHtml(const std::string &txt)
{
std::string sRet = txt;
stdreplace(sRet, "&", "&");
stdreplace(sRet, "\"", """);
stdreplace(sRet, "'", "'");
stdreplace(sRet, "<", "<");
stdreplace(sRet, ">", ">");
stdreplace(sRet, "\r\n", "<br/>");
return sRet;
}
//Prevent against XSS (Cross Site Scripting)
std::string SafeHtml(const std::string &txt)
{
std::string sRet = txt;
stdreplace(sRet, "\"", """);
stdreplace(sRet, "'", "'");
stdreplace(sRet, "<", "<");
stdreplace(sRet, ">", ">");
return sRet;
}
#if defined WIN32
//FILETIME of Jan 1 1970 00:00:00
static const uint64_t epoch = (const uint64_t)(116444736000000000);
int gettimeofday( timeval * tp, void * tzp)
{
FILETIME file_time;
SYSTEMTIME system_time;
ULARGE_INTEGER ularge;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
ularge.LowPart = file_time.dwLowDateTime;
ularge.HighPart = file_time.dwHighDateTime;
tp->tv_sec = (long)((ularge.QuadPart - epoch) / 10000000L);
tp->tv_usec = (long)(system_time.wMilliseconds * 1000);
return 0;
}
#endif
int getclock(struct timeval *tv) {
#ifdef CLOCK_MONOTONIC
struct timespec ts;
if (!clock_gettime(CLOCK_MONOTONIC, &ts)) {
tv->tv_sec = ts.tv_sec;
tv->tv_usec = ts.tv_nsec / 1000;
return 0;
}
#endif
return gettimeofday(tv, NULL);
}
int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y) {
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
const char *szInsecureArgumentOptions[] = {
"import",
"socket",
"process",
"os",
"|",
";",
"&",
"$",
"<",
">",
NULL
};
bool IsArgumentSecure(const std::string &arg)
{
std::string larg(arg);
std::transform(larg.begin(), larg.end(), larg.begin(), ::tolower);
int ii = 0;
while (szInsecureArgumentOptions[ii] != NULL)
{
if (larg.find(szInsecureArgumentOptions[ii]) != std::string::npos)
return false;
ii++;
}
return true;
}
uint32_t SystemUptime()
{
#if defined(WIN32)
return static_cast<uint32_t>(GetTickCount64() / 1000u);
#elif defined(__linux__) || defined(__linux) || defined(linux)
struct sysinfo info;
if (sysinfo(&info) != 0)
return -1;
return info.uptime;
#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
struct timeval boottime;
std::size_t len = sizeof(boottime);
int mib[2] = { CTL_KERN, KERN_BOOTTIME };
if (sysctl(mib, 2, &boottime, &len, NULL, 0) < 0)
return -1;
return time(NULL) - boottime.tv_sec;
#elif (defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) && defined(CLOCK_UPTIME)
struct timespec ts;
if (clock_gettime(CLOCK_UPTIME, &ts) != 0)
return -1;
return ts.tv_sec;
#else
return 0;
#endif
}
// True random number generator (source: http://www.azillionmonkeys.com/qed/random.html)
static struct
{
int which;
time_t t;
clock_t c;
int counter;
} entropy = { 0, (time_t) 0, (clock_t) 0, 0 };
static unsigned char * p = (unsigned char *) (&entropy + 1);
static int accSeed = 0;
int GenerateRandomNumber(const int range)
{
if (p == ((unsigned char *) (&entropy + 1)))
{
switch (entropy.which)
{
case 0:
entropy.t += time (NULL);
accSeed ^= entropy.t;
break;
case 1:
entropy.c += clock();
break;
case 2:
entropy.counter++;
break;
}
entropy.which = (entropy.which + 1) % 3;
p = (unsigned char *) &entropy.t;
}
accSeed = ((accSeed * (UCHAR_MAX + 2U)) | 1) + (int) *p;
p++;
srand (accSeed);
return (rand() / (RAND_MAX / range));
}
int GetDirFilesRecursive(const std::string &DirPath, std::map<std::string, int> &_Files)
{
DIR* dir;
if ((dir = opendir(DirPath.c_str())) != NULL)
{
struct dirent *ent;
while ((ent = readdir(dir)) != NULL)
{
if (dirent_is_directory(DirPath, ent))
{
if ((strcmp(ent->d_name, ".") != 0) && (strcmp(ent->d_name, "..") != 0) && (strcmp(ent->d_name, ".svn") != 0))
{
std::string nextdir = DirPath + ent->d_name + "/";
if (GetDirFilesRecursive(nextdir.c_str(), _Files))
{
closedir(dir);
return 1;
}
}
}
else
{
std::string fname = DirPath + ent->d_name;
_Files[fname] = 1;
}
}
}
closedir(dir);
return 0;
}
#ifdef WIN32
// From https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
const DWORD MS_VC_EXCEPTION = 0x406D1388;
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
int SetThreadName(const std::thread::native_handle_type &thread, const char* threadName) {
DWORD dwThreadID = ::GetThreadId( static_cast<HANDLE>( thread ) );
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
#pragma warning(push)
#pragma warning(disable: 6320 6322)
__try{
RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
}
__except (EXCEPTION_EXECUTE_HANDLER){
}
#pragma warning(pop)
return 0;
}
#else
// Based on https://stackoverflow.com/questions/2369738/how-to-set-the-name-of-a-thread-in-linux-pthreads
int SetThreadName(const std::thread::native_handle_type &thread, const char *name)
{
#if defined(__linux__) || defined(__linux) || defined(linux)
char name_trunc[16];
strncpy(name_trunc, name, sizeof(name_trunc));
name_trunc[sizeof(name_trunc)-1] = '\0';
return pthread_setname_np(thread, name_trunc);
#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
// Not possible to set name of other thread: https://stackoverflow.com/questions/2369738/how-to-set-the-name-of-a-thread-in-linux-pthreads
return 0;
#elif defined(__NetBSD__)
char name_trunc[PTHREAD_MAX_NAMELEN_NP];
strncpy(name_trunc, name, sizeof(name_trunc));
name_trunc[sizeof(name_trunc)-1] = '\0';
return pthread_setname_np(thread, "%s", (void *)name_trunc);
#elif defined(__OpenBSD__) || defined(__DragonFly__)
char name_trunc[PTHREAD_MAX_NAMELEN_NP];
strncpy(name_trunc, name, sizeof(name_trunc));
name_trunc[sizeof(name_trunc)-1] = '\0';
pthread_setname_np(thread, name_trunc);
return 0;
#elif defined(__FreeBSD__)
char name_trunc[PTHREAD_MAX_NAMELEN_NP];
strncpy(name_trunc, name, sizeof(name_trunc));
name_trunc[sizeof(name_trunc)-1] = '\0';
pthread_set_name_np(thread, name_trunc);
return 0;
#endif
}
#endif
#if !defined(WIN32)
bool IsDebuggerPresent(void)
{
#if defined(__linux__)
// Linux implementation: Search for 'TracerPid:' in /proc/self/status
char buf[4096];
const int status_fd = ::open("/proc/self/status", O_RDONLY);
if (status_fd == -1)
return false;
const ssize_t num_read = ::read(status_fd, buf, sizeof(buf) - 1);
if (num_read <= 0)
return false;
buf[num_read] = '\0';
constexpr char tracerPidString[] = "TracerPid:";
const auto tracer_pid_ptr = ::strstr(buf, tracerPidString);
if (!tracer_pid_ptr)
return false;
for (const char* characterPtr = tracer_pid_ptr + sizeof(tracerPidString) - 1; characterPtr <= buf + num_read; ++characterPtr)
{
if (::isspace(*characterPtr))
continue;
else
return ::isdigit(*characterPtr) != 0 && *characterPtr != '0';
}
return false;
#else
// MacOS X / BSD: TODO
# ifdef _DEBUG
return true;
# else
return false;
# endif
#endif
}
#endif
#if defined(__linux__)
bool IsWSL(void)
{
// Detect WSL according to https://github.com/Microsoft/WSL/issues/423#issuecomment-221627364
bool is_wsl = false;
char buf[1024];
int status_fd = open("/proc/sys/kernel/osrelease", O_RDONLY);
if (status_fd == -1)
return is_wsl;
ssize_t num_read = read(status_fd, buf, sizeof(buf) - 1);
if (num_read > 0)
{
buf[num_read] = 0;
is_wsl |= (strstr(buf, "Microsoft") != NULL);
is_wsl |= (strstr(buf, "WSL") != NULL);
}
status_fd = open("/proc/version", O_RDONLY);
if (status_fd == -1)
return is_wsl;
num_read = read(status_fd, buf, sizeof(buf) - 1);
if (num_read > 0)
{
buf[num_read] = 0;
is_wsl |= (strstr(buf, "Microsoft") != NULL);
is_wsl |= (strstr(buf, "WSL") != NULL);
}
return is_wsl;
}
#endif
const std::string hexCHARS = "0123456789abcdef";
std::string GenerateUUID() // DCE/RFC 4122
{
std::srand((unsigned int)std::time(nullptr));
std::string uuid = std::string(36, ' ');
uuid[8] = '-';
uuid[13] = '-';
uuid[14] = '4'; //M
uuid[18] = '-';
//uuid[19] = ' '; //N Variant 1 UUIDs (10xx N=8..b, 2 bits)
uuid[23] = '-';
for (size_t ii = 0; ii < uuid.size(); ii++)
{
if (uuid[ii] == ' ')
{
uuid[ii] = hexCHARS[(ii == 19) ? (8 + (std::rand() & 0x03)) : std::rand() & 0x0F];
}
}
return uuid;
}
| ./CrossVul/dataset_final_sorted/CWE-93/cpp/bad_764_0 |
crossvul-cpp_data_good_764_0 | #include "stdafx.h"
#include "Helper.h"
#include "Logger.h"
#ifdef WIN32
#include "dirent_windows.h"
#include <direct.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif
#if !defined(WIN32)
#include <sys/ptrace.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <fstream>
#include <math.h>
#include <algorithm>
#include "../main/localtime_r.h"
#include <sstream>
#include <openssl/md5.h>
#include <chrono>
#include <limits.h>
#include <cstring>
#if defined WIN32
#include "../msbuild/WindowsHelper.h"
#endif
#include "RFXtrx.h"
#include "../hardware/hardwaretypes.h"
// Includes for SystemUptime()
#if defined(__linux__) || defined(__linux) || defined(linux)
#include <sys/sysinfo.h>
#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
#include <time.h>
#include <errno.h>
#include <sys/sysctl.h>
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
#include <time.h>
#endif
#if defined(__FreeBSD__)
// Check if OpenBSD or DragonFly need that at well?
#include <pthread_np.h>
#ifndef PTHREAD_MAX_MAMELEN_NP
#define PTHREAD_MAX_NAMELEN_NP 32 // Arbitrary
#endif
#endif
void StringSplit(std::string str, const std::string &delim, std::vector<std::string> &results)
{
results.clear();
size_t cutAt;
while( (cutAt = str.find(delim)) != std::string::npos )
{
results.push_back(str.substr(0,cutAt));
str = str.substr(cutAt+ delim.size());
}
if (!str.empty())
{
results.push_back(str);
}
}
uint64_t hexstrtoui64(const std::string &str)
{
uint64_t ul;
std::stringstream ss;
ss << std::hex << str;
ss >> ul;
return ul;
}
void stdreplace(
std::string &inoutstring,
const std::string& replaceWhat,
const std::string& replaceWithWhat)
{
int pos = 0;
while (std::string::npos != (pos = inoutstring.find(replaceWhat, pos)))
{
inoutstring.replace(pos, replaceWhat.size(), replaceWithWhat);
pos += replaceWithWhat.size();
}
}
void stdupper(std::string &inoutstring)
{
for (size_t i = 0; i < inoutstring.size(); ++i)
inoutstring[i] = toupper(inoutstring[i]);
}
void stdlower(std::string &inoutstring)
{
std::transform(inoutstring.begin(), inoutstring.end(), inoutstring.begin(), ::tolower);
}
std::vector<std::string> GetSerialPorts(bool &bUseDirectPath)
{
bUseDirectPath=false;
std::vector<std::string> ret;
#if defined WIN32
//windows
std::vector<int> ports;
std::vector<std::string> friendlyNames;
char szPortName[40];
EnumSerialFromWMI(ports, friendlyNames);
bool bFoundPort = false;
if (!ports.empty())
{
bFoundPort = true;
for (const auto & itt : ports)
{
sprintf(szPortName, "COM%d", itt);
ret.push_back(szPortName);
}
}
if (bFoundPort)
return ret;
//Scan old fashion way (SLOW!)
COMMCONFIG cc;
DWORD dwSize = sizeof(COMMCONFIG);
for (int ii = 0; ii < 256; ii++)
{
sprintf(szPortName, "COM%d", ii);
if (GetDefaultCommConfig(szPortName, &cc, &dwSize))
{
bFoundPort = true;
sprintf(szPortName, "COM%d", ii);
//Check if we did not already have it
bool bFound = false;
for (const auto & itt : ret)
{
if (itt == szPortName)
{
bFound = true;
break;
}
}
if (!bFound)
ret.push_back(szPortName); // add port
}
}
// Method 2: CreateFile, slow
// ---------
if (!bFoundPort) {
for (int ii = 0; ii < 256; ii++)
{
sprintf(szPortName, "\\\\.\\COM%d", ii);
bool bSuccess = false;
HANDLE hPort = ::CreateFile(szPortName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
if (hPort == INVALID_HANDLE_VALUE) {
DWORD dwError = GetLastError();
//Check to see if the error was because some other app had the port open
if (dwError == ERROR_ACCESS_DENIED)
bSuccess = TRUE;
}
else {
//The port was opened successfully
bSuccess = TRUE;
//Don't forget to close the port, since we are going to do nothing with it anyway
CloseHandle(hPort);
}
if (bSuccess) {
bFoundPort = true;
sprintf(szPortName, "COM%d", ii);
ret.push_back(szPortName); // add port
}
// --------------
}
}
// Method 3: EnumSerialPortsWindows, often fails
// ---------
if (!bFoundPort) {
std::vector<SerialPortInfo> serialports;
EnumSerialPortsWindows(serialports);
if (!serialports.empty())
{
for (const auto & itt : serialports)
{
ret.push_back(itt.szPortName); // add port
}
}
}
#else
//scan /dev for /dev/ttyUSB* or /dev/ttyS* or /dev/tty.usbserial* or /dev/ttyAMA* or /dev/ttySAC*
//also scan /dev/serial/by-id/* on Linux
bool bHaveTtyAMAfree=false;
std::string sLine = "";
std::ifstream infile;
infile.open("/boot/cmdline.txt");
if (infile.is_open())
{
if (!infile.eof())
{
getline(infile, sLine);
bHaveTtyAMAfree=(sLine.find("ttyAMA0")==std::string::npos);
}
}
DIR *d=NULL;
d=opendir("/dev");
if (d != NULL)
{
struct dirent *de=NULL;
// Loop while not NULL
while ((de = readdir(d)))
{
// Only consider character devices and symbolic links
if ((de->d_type == DT_CHR) || (de->d_type == DT_LNK))
{
std::string fname = de->d_name;
if (fname.find("ttyUSB")!=std::string::npos)
{
ret.push_back("/dev/" + fname);
}
else if (fname.find("tty.usbserial")!=std::string::npos)
{
bUseDirectPath=true;
ret.push_back("/dev/" + fname);
}
else if (fname.find("ttyACM")!=std::string::npos)
{
bUseDirectPath=true;
ret.push_back("/dev/" + fname);
}
else if (fname.find("ttySAC") != std::string::npos)
{
bUseDirectPath = true;
ret.push_back("/dev/" + fname);
}
#if defined (__FreeBSD__) || defined (__OpenBSD__) || defined (__NetBSD__)
else if (fname.find("ttyU")!=std::string::npos)
{
bUseDirectPath=true;
ret.push_back("/dev/" + fname);
}
else if (fname.find("cuaU")!=std::string::npos)
{
bUseDirectPath=true;
ret.push_back("/dev/" + fname);
}
#endif
#ifdef __APPLE__
else if (fname.find("cu.")!=std::string::npos)
{
bUseDirectPath=true;
ret.push_back("/dev/" + fname);
}
#endif
if (bHaveTtyAMAfree)
{
if (fname.find("ttyAMA0")!=std::string::npos)
{
ret.push_back("/dev/" + fname);
bUseDirectPath=true;
}
// By default, this is the "small UART" on Rasberry 3 boards
if (fname.find("ttyS0")!=std::string::npos)
{
ret.push_back("/dev/" + fname);
bUseDirectPath=true;
}
// serial0 and serial1 are new with Rasbian Jessie
// Avoids confusion between Raspberry 2 and 3 boards
// More info at http://spellfoundry.com/2016/05/29/configuring-gpio-serial-port-raspbian-jessie-including-pi-3/
if (fname.find("serial")!=std::string::npos)
{
ret.push_back("/dev/" + fname);
bUseDirectPath=true;
}
}
}
}
closedir(d);
}
//also scan in /dev/usb
d=opendir("/dev/usb");
if (d != NULL)
{
struct dirent *de=NULL;
// Loop while not NULL
while ((de = readdir(d)))
{
std::string fname = de->d_name;
if (fname.find("ttyUSB")!=std::string::npos)
{
bUseDirectPath=true;
ret.push_back("/dev/usb/" + fname);
}
}
closedir(d);
}
#if defined(__linux__) || defined(__linux) || defined(linux)
d=opendir("/dev/serial/by-id");
if (d != NULL)
{
struct dirent *de=NULL;
// Loop while not NULL
while ((de = readdir(d)))
{
// Only consider symbolic links
if (de->d_type == DT_LNK)
{
std::string fname = de->d_name;
ret.push_back("/dev/serial/by-id/" + fname);
}
}
closedir(d);
}
#endif
#endif
return ret;
}
bool file_exist (const char *filename)
{
struct stat sbuffer;
return (stat(filename, &sbuffer) == 0);
}
double CalculateAltitudeFromPressure(double pressure)
{
double seaLevelPressure=101325.0;
double altitude = 44330.0 * (1.0 - pow( (pressure / seaLevelPressure), 0.1903));
return altitude;
}
/**************************************************************************/
/*!
Calculates the altitude (in meters) from the specified atmospheric
pressure (in hPa), sea-level pressure (in hPa), and temperature (in °C)
@param seaLevel Sea-level pressure in hPa
@param atmospheric Atmospheric pressure in hPa
@param temp Temperature in degrees Celsius
*/
/**************************************************************************/
float pressureToAltitude(float seaLevel, float atmospheric, float temp)
{
/* Hyposometric formula: */
/* */
/* ((P0/P)^(1/5.257) - 1) * (T + 273.15) */
/* h = ------------------------------------- */
/* 0.0065 */
/* */
/* where: h = height (in meters) */
/* P0 = sea-level pressure (in hPa) */
/* P = atmospheric pressure (in hPa) */
/* T = temperature (in °C) */
return (((float)pow((seaLevel / atmospheric), 0.190223F) - 1.0F)
* (temp + 273.15F)) / 0.0065F;
}
/**************************************************************************/
/*!
Calculates the sea-level pressure (in hPa) based on the current
altitude (in meters), atmospheric pressure (in hPa), and temperature
(in °C)
@param altitude altitude in meters
@param atmospheric Atmospheric pressure in hPa
@param temp Temperature in degrees Celsius
*/
/**************************************************************************/
float pressureSeaLevelFromAltitude(float altitude, float atmospheric, float temp)
{
/* Sea-level pressure: */
/* */
/* 0.0065*h */
/* P0 = P * (1 - ----------------- ) ^ -5.257 */
/* T+0.0065*h+273.15 */
/* */
/* where: P0 = sea-level pressure (in hPa) */
/* P = atmospheric pressure (in hPa) */
/* h = altitude (in meters) */
/* T = Temperature (in °C) */
return atmospheric * (float)pow((1.0F - (0.0065F * altitude) /
(temp + 0.0065F * altitude + 273.15F)), -5.257F);
}
std::string &stdstring_ltrim(std::string &s)
{
while (!s.empty())
{
if (s[0] != ' ')
return s;
s = s.substr(1);
}
// s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
std::string &stdstring_rtrim(std::string &s)
{
while (!s.empty())
{
if (s[s.size() - 1] != ' ')
return s;
s = s.substr(0, s.size() - 1);
}
//s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
std::string &stdstring_trim(std::string &s)
{
return stdstring_ltrim(stdstring_rtrim(s));
}
double CalculateDewPoint(double temp, int humidity)
{
if (humidity==0)
return temp;
double dew_numer = 243.04*(log(double(humidity)/100.0)+((17.625*temp)/(temp+243.04)));
double dew_denom = 17.625-log(double(humidity)/100.0)-((17.625*temp)/(temp+243.04));
if (dew_numer==0)
dew_numer=1;
return dew_numer/dew_denom;
}
uint32_t IPToUInt(const std::string &ip)
{
int a, b, c, d;
uint32_t addr = 0;
if (sscanf(ip.c_str(), "%d.%d.%d.%d", &a, &b, &c, &d) != 4)
return 0;
addr = a << 24;
addr |= b << 16;
addr |= c << 8;
addr |= d;
return addr;
}
bool isInt(const std::string &s)
{
for(size_t i = 0; i < s.length(); i++){
if(!isdigit(s[i]))
return false;
}
return true;
}
void sleep_seconds(const long seconds)
{
std::this_thread::sleep_for(std::chrono::seconds(seconds));
}
void sleep_milliseconds(const long milliseconds)
{
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
}
int createdir(const char *szDirName, int secattr)
{
int ret = 0;
#ifdef WIN32
ret = _mkdir(szDirName);
#else
ret = mkdir(szDirName, secattr);
#endif
return ret;
}
int mkdir_deep(const char *szDirName, int secattr)
{
char DirName[260];
DirName[0] = 0;
const char* p = szDirName;
char* q = DirName;
int ret = 0;
while(*p)
{
if (('\\' == *p) || ('/' == *p))
{
if (':' != *(p-1))
{
ret = createdir(DirName, secattr);
}
}
*q++ = *p++;
*q = '\0';
}
if (DirName[0])
{
ret = createdir(DirName, secattr);
}
return ret;
}
int RemoveDir(const std::string &dirnames, std::string &errorPath)
{
std::vector<std::string> splitresults;
StringSplit(dirnames, "|", splitresults);
int returncode = 0;
if (!splitresults.empty())
{
#ifdef WIN32
for (size_t i = 0; i < splitresults.size(); i++)
{
if (!file_exist(splitresults[i].c_str()))
continue;
size_t s_szLen = strlen(splitresults[i].c_str());
if (s_szLen < MAX_PATH)
{
char deletePath[MAX_PATH + 1];
strcpy_s(deletePath, splitresults[i].c_str());
deletePath[s_szLen + 1] = '\0'; // SHFILEOPSTRUCT needs an additional null char
SHFILEOPSTRUCT shfo = { NULL, FO_DELETE, deletePath, NULL, FOF_SILENT | FOF_NOERRORUI | FOF_NOCONFIRMATION, FALSE, NULL, NULL };
if (returncode = SHFileOperation(&shfo))
{
errorPath = splitresults[i];
break;
}
}
}
#else
for (size_t i = 0; i < splitresults.size(); i++)
{
if (!file_exist(splitresults[i].c_str()))
continue;
ExecuteCommandAndReturn("rm -rf \"" + splitresults[i] + "\"", returncode);
if (returncode)
{
errorPath = splitresults[i];
break;
}
}
#endif
}
return returncode;
}
double ConvertToCelsius(const double Fahrenheit)
{
return (Fahrenheit-32.0) * 0.5556;
}
double ConvertToFahrenheit(const double Celsius)
{
return (Celsius*1.8)+32.0;
}
double RoundDouble(const long double invalue, const short numberOfPrecisions)
{
long long p = (long long) pow(10.0L, numberOfPrecisions);
double ret= (long long)(invalue * p + 0.5L) / (double)p;
return ret;
}
double ConvertTemperature(const double tValue, const unsigned char tSign)
{
if (tSign=='C')
return tValue;
return RoundDouble(ConvertToFahrenheit(tValue),1);
}
std::vector<std::string> ExecuteCommandAndReturn(const std::string &szCommand, int &returncode)
{
std::vector<std::string> ret;
try
{
FILE *fp;
/* Open the command for reading. */
#ifdef WIN32
fp = _popen(szCommand.c_str(), "r");
#else
fp = popen(szCommand.c_str(), "r");
#endif
if (fp != NULL)
{
char path[1035];
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path) - 1, fp) != NULL)
{
ret.push_back(path);
}
/* close */
#ifdef WIN32
returncode = _pclose(fp);
#else
returncode = pclose(fp);
#endif
}
}
catch (...)
{
}
return ret;
}
std::string TimeToString(const time_t *ltime, const _eTimeFormat format)
{
struct tm timeinfo;
struct timeval tv;
std::stringstream sstr;
if (ltime == NULL) // current time
{
#ifdef CLOCK_REALTIME
struct timespec ts;
if (!clock_gettime(CLOCK_REALTIME, &ts))
{
tv.tv_sec = ts.tv_sec;
tv.tv_usec = ts.tv_nsec / 1000;
}
else
#endif
gettimeofday(&tv, NULL);
#ifdef WIN32
time_t tv_sec = tv.tv_sec;
localtime_r(&tv_sec, &timeinfo);
#else
localtime_r(&tv.tv_sec, &timeinfo);
#endif
}
else
localtime_r(ltime, &timeinfo);
if (format > TF_Time)
{
//Date
sstr << (timeinfo.tm_year + 1900) << "-"
<< std::setw(2) << std::setfill('0') << (timeinfo.tm_mon + 1) << "-"
<< std::setw(2) << std::setfill('0') << timeinfo.tm_mday;
}
if (format != TF_Date)
{
//Time
if (format > TF_Time)
sstr << " ";
sstr
<< std::setw(2) << std::setfill('0') << timeinfo.tm_hour << ":"
<< std::setw(2) << std::setfill('0') << timeinfo.tm_min << ":"
<< std::setw(2) << std::setfill('0') << timeinfo.tm_sec;
}
if (format > TF_DateTime && ltime == NULL)
sstr << "." << std::setw(3) << std::setfill('0') << ((int)tv.tv_usec / 1000);
return sstr.str();
}
std::string GenerateMD5Hash(const std::string &InputString, const std::string &Salt)
{
std::string cstring = InputString + Salt;
unsigned char digest[MD5_DIGEST_LENGTH + 1];
digest[MD5_DIGEST_LENGTH] = 0;
MD5((const unsigned char*)cstring.c_str(), cstring.size(), (unsigned char*)&digest);
char mdString[(MD5_DIGEST_LENGTH * 2) + 1];
mdString[MD5_DIGEST_LENGTH * 2] = 0;
for (int i = 0; i < 16; i++)
sprintf(&mdString[i * 2], "%02x", (unsigned int)digest[i]);
return mdString;
}
void hsb2rgb(const float hue, const float saturation, const float vlue, int &outR, int &outG, int &outB, const double maxValue/* = 100.0 */)
{
double hh, p, q, t, ff;
long i;
if(saturation <= 0.0) {
outR = int(vlue*maxValue);
outG = int(vlue*maxValue);
outB = int(vlue*maxValue);
}
hh = hue;
if (hh >= 360.0) hh = 0.0;
hh /= 60.0;
i = (long)hh;
ff = hh - i;
p = vlue * (1.0 - saturation);
q = vlue * (1.0 - (saturation * ff));
t = vlue * (1.0 - (saturation * (1.0 - ff)));
switch (i) {
case 0:
outR = int(vlue*maxValue);
outG = int(t*maxValue);
outB = int(p*maxValue);
break;
case 1:
outR = int(q*maxValue);
outG = int(vlue*maxValue);
outB = int(p*maxValue);
break;
case 2:
outR = int(p*maxValue);
outG = int(vlue*maxValue);
outB = int(t*maxValue);
break;
case 3:
outR = int(p*maxValue);
outG = int(q*maxValue);
outB = int(vlue*maxValue);
break;
case 4:
outR = int(t*maxValue);
outG = int(p*maxValue);
outB = int(vlue*maxValue);
break;
case 5:
default:
outR = int(vlue*maxValue);
outG = int(p*maxValue);
outB = int(q*maxValue);
break;
}
}
void rgb2hsb(const int r, const int g, const int b, float hsbvals[3])
{
float hue, saturation, brightness;
if (hsbvals == NULL)
return;
int cmax = (r > g) ? r : g;
if (b > cmax) cmax = b;
int cmin = (r < g) ? r : g;
if (b < cmin) cmin = b;
brightness = ((float)cmax) / 255.0f;
if (cmax != 0)
saturation = ((float)(cmax - cmin)) / ((float)cmax);
else
saturation = 0;
if (saturation == 0)
hue = 0;
else {
float redc = ((float)(cmax - r)) / ((float)(cmax - cmin));
float greenc = ((float)(cmax - g)) / ((float)(cmax - cmin));
float bluec = ((float)(cmax - b)) / ((float)(cmax - cmin));
if (r == cmax)
hue = bluec - greenc;
else if (g == cmax)
hue = 2.0f + redc - bluec;
else
hue = 4.0f + greenc - redc;
hue = hue / 6.0f;
if (hue < 0)
hue = hue + 1.0f;
}
hsbvals[0] = hue;
hsbvals[1] = saturation;
hsbvals[2] = brightness;
}
bool is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && (isdigit(*it) || (*it == '.') || (*it == '-') || (*it == ' ') || (*it == 0x00))) ++it;
return !s.empty() && it == s.end();
}
void padLeft(std::string &str, const size_t num, const char paddingChar)
{
if (num > str.size())
str.insert(0, num - str.size(), paddingChar);
}
bool IsLightOrSwitch(const int devType, const int subType)
{
bool bIsLightSwitch = false;
switch (devType)
{
case pTypeLighting1:
case pTypeLighting2:
case pTypeLighting3:
case pTypeLighting4:
case pTypeLighting5:
case pTypeLighting6:
case pTypeFan:
case pTypeColorSwitch:
case pTypeSecurity1:
case pTypeSecurity2:
case pTypeCurtain:
case pTypeBlinds:
case pTypeRFY:
case pTypeThermostat2:
case pTypeThermostat3:
case pTypeThermostat4:
case pTypeRemote:
case pTypeGeneralSwitch:
case pTypeHomeConfort:
case pTypeFS20:
bIsLightSwitch = true;
break;
case pTypeRadiator1:
bIsLightSwitch = (subType == sTypeSmartwaresSwitchRadiator);
break;
}
return bIsLightSwitch;
}
int MStoBeaufort(const float ms)
{
if (ms < 0.3f)
return 0;
if (ms < 1.5f)
return 1;
if (ms < 3.3f)
return 2;
if (ms < 5.5f)
return 3;
if (ms < 8.0f)
return 4;
if (ms < 10.8f)
return 5;
if (ms < 13.9f)
return 6;
if (ms < 17.2f)
return 7;
if (ms < 20.7f)
return 8;
if (ms < 24.5f)
return 9;
if (ms < 28.4f)
return 10;
if (ms < 32.6f)
return 11;
return 12;
}
void FixFolderEnding(std::string &folder)
{
#if defined(WIN32)
if (folder.at(folder.length() - 1) != '\\')
folder += "\\";
#else
if (folder.at(folder.length() - 1) != '/')
folder += "/";
#endif
}
bool dirent_is_directory(const std::string &dir, struct dirent *ent)
{
if (ent->d_type == DT_DIR)
return true;
#ifndef WIN32
if (ent->d_type == DT_LNK)
return true;
if (ent->d_type == DT_UNKNOWN) {
std::string fname = dir + "/" + ent->d_name;
struct stat st;
if (!lstat(fname.c_str(), &st))
return S_ISDIR(st.st_mode);
}
#endif
return false;
}
bool dirent_is_file(const std::string &dir, struct dirent *ent)
{
if (ent->d_type == DT_REG)
return true;
#ifndef WIN32
if (ent->d_type == DT_UNKNOWN) {
std::string fname = dir + "/" + ent->d_name;
struct stat st;
if (!lstat(fname.c_str(), &st))
return S_ISREG(st.st_mode);
}
#endif
return false;
}
/*!
* List entries of a directory.
* @param entries A string vector containing the result
* @param dir Target directory for listing
* @param bInclDirs Boolean flag to include directories in the result
* @param bInclFiles Boolean flag to include regular files in the result
*/
void DirectoryListing(std::vector<std::string>& entries, const std::string &dir, bool bInclDirs, bool bInclFiles)
{
DIR *d = NULL;
struct dirent *ent;
if ((d = opendir(dir.c_str())) != NULL)
{
while ((ent = readdir(d)) != NULL) {
std::string name = ent->d_name;
if (bInclDirs && dirent_is_directory(dir, ent) && name != "." && name != "..") {
entries.push_back(name);
continue;
}
if (bInclFiles && dirent_is_file(dir, ent)) {
entries.push_back(name);
continue;
}
}
closedir(d);
}
return;
}
std::string GenerateUserAgent()
{
srand((unsigned int)time(NULL));
int cversion = rand() % 0xFFFF;
int mversion = rand() % 3;
int sversion = rand() % 3;
std::stringstream sstr;
sstr << "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/" << (601 + sversion) << "." << (36+mversion) << " (KHTML, like Gecko) Chrome/" << (53 + mversion) << ".0." << cversion << ".0 Safari/" << (601 + sversion) << "." << (36+sversion);
return sstr.str();
}
std::string MakeHtml(const std::string &txt)
{
std::string sRet = txt;
stdreplace(sRet, "&", "&");
stdreplace(sRet, "\"", """);
stdreplace(sRet, "'", "'");
stdreplace(sRet, "<", "<");
stdreplace(sRet, ">", ">");
stdreplace(sRet, "\r\n", "<br/>");
return sRet;
}
//Prevent against XSS (Cross Site Scripting)
std::string SafeHtml(const std::string &txt)
{
std::string sRet = txt;
stdreplace(sRet, "\"", """);
stdreplace(sRet, "'", "'");
stdreplace(sRet, "<", "<");
stdreplace(sRet, ">", ">");
return sRet;
}
#if defined WIN32
//FILETIME of Jan 1 1970 00:00:00
static const uint64_t epoch = (const uint64_t)(116444736000000000);
int gettimeofday( timeval * tp, void * tzp)
{
FILETIME file_time;
SYSTEMTIME system_time;
ULARGE_INTEGER ularge;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
ularge.LowPart = file_time.dwLowDateTime;
ularge.HighPart = file_time.dwHighDateTime;
tp->tv_sec = (long)((ularge.QuadPart - epoch) / 10000000L);
tp->tv_usec = (long)(system_time.wMilliseconds * 1000);
return 0;
}
#endif
int getclock(struct timeval *tv) {
#ifdef CLOCK_MONOTONIC
struct timespec ts;
if (!clock_gettime(CLOCK_MONOTONIC, &ts)) {
tv->tv_sec = ts.tv_sec;
tv->tv_usec = ts.tv_nsec / 1000;
return 0;
}
#endif
return gettimeofday(tv, NULL);
}
int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y) {
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
const char *szInsecureArgumentOptions[] = {
"import",
"socket",
"process",
"os",
"|",
";",
"&",
"$",
"<",
">",
"\n",
"\r",
NULL
};
bool IsArgumentSecure(const std::string &arg)
{
std::string larg(arg);
std::transform(larg.begin(), larg.end(), larg.begin(), ::tolower);
int ii = 0;
while (szInsecureArgumentOptions[ii] != NULL)
{
if (larg.find(szInsecureArgumentOptions[ii]) != std::string::npos)
return false;
ii++;
}
return true;
}
uint32_t SystemUptime()
{
#if defined(WIN32)
return static_cast<uint32_t>(GetTickCount64() / 1000u);
#elif defined(__linux__) || defined(__linux) || defined(linux)
struct sysinfo info;
if (sysinfo(&info) != 0)
return -1;
return info.uptime;
#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
struct timeval boottime;
std::size_t len = sizeof(boottime);
int mib[2] = { CTL_KERN, KERN_BOOTTIME };
if (sysctl(mib, 2, &boottime, &len, NULL, 0) < 0)
return -1;
return time(NULL) - boottime.tv_sec;
#elif (defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) && defined(CLOCK_UPTIME)
struct timespec ts;
if (clock_gettime(CLOCK_UPTIME, &ts) != 0)
return -1;
return ts.tv_sec;
#else
return 0;
#endif
}
// True random number generator (source: http://www.azillionmonkeys.com/qed/random.html)
static struct
{
int which;
time_t t;
clock_t c;
int counter;
} entropy = { 0, (time_t) 0, (clock_t) 0, 0 };
static unsigned char * p = (unsigned char *) (&entropy + 1);
static int accSeed = 0;
int GenerateRandomNumber(const int range)
{
if (p == ((unsigned char *) (&entropy + 1)))
{
switch (entropy.which)
{
case 0:
entropy.t += time (NULL);
accSeed ^= entropy.t;
break;
case 1:
entropy.c += clock();
break;
case 2:
entropy.counter++;
break;
}
entropy.which = (entropy.which + 1) % 3;
p = (unsigned char *) &entropy.t;
}
accSeed = ((accSeed * (UCHAR_MAX + 2U)) | 1) + (int) *p;
p++;
srand (accSeed);
return (rand() / (RAND_MAX / range));
}
int GetDirFilesRecursive(const std::string &DirPath, std::map<std::string, int> &_Files)
{
DIR* dir;
if ((dir = opendir(DirPath.c_str())) != NULL)
{
struct dirent *ent;
while ((ent = readdir(dir)) != NULL)
{
if (dirent_is_directory(DirPath, ent))
{
if ((strcmp(ent->d_name, ".") != 0) && (strcmp(ent->d_name, "..") != 0) && (strcmp(ent->d_name, ".svn") != 0))
{
std::string nextdir = DirPath + ent->d_name + "/";
if (GetDirFilesRecursive(nextdir.c_str(), _Files))
{
closedir(dir);
return 1;
}
}
}
else
{
std::string fname = DirPath + ent->d_name;
_Files[fname] = 1;
}
}
}
closedir(dir);
return 0;
}
#ifdef WIN32
// From https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
const DWORD MS_VC_EXCEPTION = 0x406D1388;
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
int SetThreadName(const std::thread::native_handle_type &thread, const char* threadName) {
DWORD dwThreadID = ::GetThreadId( static_cast<HANDLE>( thread ) );
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
#pragma warning(push)
#pragma warning(disable: 6320 6322)
__try{
RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
}
__except (EXCEPTION_EXECUTE_HANDLER){
}
#pragma warning(pop)
return 0;
}
#else
// Based on https://stackoverflow.com/questions/2369738/how-to-set-the-name-of-a-thread-in-linux-pthreads
int SetThreadName(const std::thread::native_handle_type &thread, const char *name)
{
#if defined(__linux__) || defined(__linux) || defined(linux)
char name_trunc[16];
strncpy(name_trunc, name, sizeof(name_trunc));
name_trunc[sizeof(name_trunc)-1] = '\0';
return pthread_setname_np(thread, name_trunc);
#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
// Not possible to set name of other thread: https://stackoverflow.com/questions/2369738/how-to-set-the-name-of-a-thread-in-linux-pthreads
return 0;
#elif defined(__NetBSD__)
char name_trunc[PTHREAD_MAX_NAMELEN_NP];
strncpy(name_trunc, name, sizeof(name_trunc));
name_trunc[sizeof(name_trunc)-1] = '\0';
return pthread_setname_np(thread, "%s", (void *)name_trunc);
#elif defined(__OpenBSD__) || defined(__DragonFly__)
char name_trunc[PTHREAD_MAX_NAMELEN_NP];
strncpy(name_trunc, name, sizeof(name_trunc));
name_trunc[sizeof(name_trunc)-1] = '\0';
pthread_setname_np(thread, name_trunc);
return 0;
#elif defined(__FreeBSD__)
char name_trunc[PTHREAD_MAX_NAMELEN_NP];
strncpy(name_trunc, name, sizeof(name_trunc));
name_trunc[sizeof(name_trunc)-1] = '\0';
pthread_set_name_np(thread, name_trunc);
return 0;
#endif
}
#endif
#if !defined(WIN32)
bool IsDebuggerPresent(void)
{
#if defined(__linux__)
// Linux implementation: Search for 'TracerPid:' in /proc/self/status
char buf[4096];
const int status_fd = ::open("/proc/self/status", O_RDONLY);
if (status_fd == -1)
return false;
const ssize_t num_read = ::read(status_fd, buf, sizeof(buf) - 1);
if (num_read <= 0)
return false;
buf[num_read] = '\0';
constexpr char tracerPidString[] = "TracerPid:";
const auto tracer_pid_ptr = ::strstr(buf, tracerPidString);
if (!tracer_pid_ptr)
return false;
for (const char* characterPtr = tracer_pid_ptr + sizeof(tracerPidString) - 1; characterPtr <= buf + num_read; ++characterPtr)
{
if (::isspace(*characterPtr))
continue;
else
return ::isdigit(*characterPtr) != 0 && *characterPtr != '0';
}
return false;
#else
// MacOS X / BSD: TODO
# ifdef _DEBUG
return true;
# else
return false;
# endif
#endif
}
#endif
#if defined(__linux__)
bool IsWSL(void)
{
// Detect WSL according to https://github.com/Microsoft/WSL/issues/423#issuecomment-221627364
bool is_wsl = false;
char buf[1024];
int status_fd = open("/proc/sys/kernel/osrelease", O_RDONLY);
if (status_fd == -1)
return is_wsl;
ssize_t num_read = read(status_fd, buf, sizeof(buf) - 1);
if (num_read > 0)
{
buf[num_read] = 0;
is_wsl |= (strstr(buf, "Microsoft") != NULL);
is_wsl |= (strstr(buf, "WSL") != NULL);
}
status_fd = open("/proc/version", O_RDONLY);
if (status_fd == -1)
return is_wsl;
num_read = read(status_fd, buf, sizeof(buf) - 1);
if (num_read > 0)
{
buf[num_read] = 0;
is_wsl |= (strstr(buf, "Microsoft") != NULL);
is_wsl |= (strstr(buf, "WSL") != NULL);
}
return is_wsl;
}
#endif
const std::string hexCHARS = "0123456789abcdef";
std::string GenerateUUID() // DCE/RFC 4122
{
std::srand((unsigned int)std::time(nullptr));
std::string uuid = std::string(36, ' ');
uuid[8] = '-';
uuid[13] = '-';
uuid[14] = '4'; //M
uuid[18] = '-';
//uuid[19] = ' '; //N Variant 1 UUIDs (10xx N=8..b, 2 bits)
uuid[23] = '-';
for (size_t ii = 0; ii < uuid.size(); ii++)
{
if (uuid[ii] == ' ')
{
uuid[ii] = hexCHARS[(ii == 19) ? (8 + (std::rand() & 0x03)) : std::rand() & 0x0F];
}
}
return uuid;
}
| ./CrossVul/dataset_final_sorted/CWE-93/cpp/good_764_0 |
crossvul-cpp_data_good_2484_0 | /*
* Copyright (C) 1995-1996 Gary Thomas (gdt@linuxppc.org)
*
* 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.
*
* Modified by Cort Dougan (cort@cs.nmt.edu)
* and Paul Mackerras (paulus@samba.org)
*/
/*
* This file handles the architecture-dependent parts of hardware exceptions
*/
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/stddef.h>
#include <linux/unistd.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/user.h>
#include <linux/a.out.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/prctl.h>
#include <linux/delay.h>
#include <linux/kprobes.h>
#include <linux/kexec.h>
#include <linux/backlight.h>
#include <asm/kdebug.h>
#include <asm/pgtable.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/machdep.h>
#include <asm/rtas.h>
#include <asm/pmc.h>
#ifdef CONFIG_PPC32
#include <asm/reg.h>
#endif
#ifdef CONFIG_PMAC_BACKLIGHT
#include <asm/backlight.h>
#endif
#ifdef CONFIG_PPC64
#include <asm/firmware.h>
#include <asm/processor.h>
#endif
#include <asm/kexec.h>
#ifdef CONFIG_PPC64 /* XXX */
#define _IO_BASE pci_io_base
#endif
#ifdef CONFIG_DEBUGGER
int (*__debugger)(struct pt_regs *regs);
int (*__debugger_ipi)(struct pt_regs *regs);
int (*__debugger_bpt)(struct pt_regs *regs);
int (*__debugger_sstep)(struct pt_regs *regs);
int (*__debugger_iabr_match)(struct pt_regs *regs);
int (*__debugger_dabr_match)(struct pt_regs *regs);
int (*__debugger_fault_handler)(struct pt_regs *regs);
EXPORT_SYMBOL(__debugger);
EXPORT_SYMBOL(__debugger_ipi);
EXPORT_SYMBOL(__debugger_bpt);
EXPORT_SYMBOL(__debugger_sstep);
EXPORT_SYMBOL(__debugger_iabr_match);
EXPORT_SYMBOL(__debugger_dabr_match);
EXPORT_SYMBOL(__debugger_fault_handler);
#endif
ATOMIC_NOTIFIER_HEAD(powerpc_die_chain);
int register_die_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_register(&powerpc_die_chain, nb);
}
EXPORT_SYMBOL(register_die_notifier);
int unregister_die_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_unregister(&powerpc_die_chain, nb);
}
EXPORT_SYMBOL(unregister_die_notifier);
/*
* Trap & Exception support
*/
static DEFINE_SPINLOCK(die_lock);
int die(const char *str, struct pt_regs *regs, long err)
{
static int die_counter;
if (debugger(regs))
return 1;
console_verbose();
spin_lock_irq(&die_lock);
bust_spinlocks(1);
#ifdef CONFIG_PMAC_BACKLIGHT
mutex_lock(&pmac_backlight_mutex);
if (machine_is(powermac) && pmac_backlight) {
struct backlight_properties *props;
down(&pmac_backlight->sem);
props = pmac_backlight->props;
props->brightness = props->max_brightness;
props->power = FB_BLANK_UNBLANK;
props->update_status(pmac_backlight);
up(&pmac_backlight->sem);
}
mutex_unlock(&pmac_backlight_mutex);
#endif
printk("Oops: %s, sig: %ld [#%d]\n", str, err, ++die_counter);
#ifdef CONFIG_PREEMPT
printk("PREEMPT ");
#endif
#ifdef CONFIG_SMP
printk("SMP NR_CPUS=%d ", NR_CPUS);
#endif
#ifdef CONFIG_DEBUG_PAGEALLOC
printk("DEBUG_PAGEALLOC ");
#endif
#ifdef CONFIG_NUMA
printk("NUMA ");
#endif
printk("%s\n", ppc_md.name ? "" : ppc_md.name);
print_modules();
show_regs(regs);
bust_spinlocks(0);
spin_unlock_irq(&die_lock);
if (kexec_should_crash(current) ||
kexec_sr_activated(smp_processor_id()))
crash_kexec(regs);
crash_kexec_secondary(regs);
if (in_interrupt())
panic("Fatal exception in interrupt");
if (panic_on_oops)
panic("Fatal exception");
do_exit(err);
return 0;
}
void _exception(int signr, struct pt_regs *regs, int code, unsigned long addr)
{
siginfo_t info;
if (!user_mode(regs)) {
if (die("Exception in kernel mode", regs, signr))
return;
}
memset(&info, 0, sizeof(info));
info.si_signo = signr;
info.si_code = code;
info.si_addr = (void __user *) addr;
force_sig_info(signr, &info, current);
/*
* Init gets no signals that it doesn't have a handler for.
* That's all very well, but if it has caused a synchronous
* exception and we ignore the resulting signal, it will just
* generate the same exception over and over again and we get
* nowhere. Better to kill it and let the kernel panic.
*/
if (current->pid == 1) {
__sighandler_t handler;
spin_lock_irq(¤t->sighand->siglock);
handler = current->sighand->action[signr-1].sa.sa_handler;
spin_unlock_irq(¤t->sighand->siglock);
if (handler == SIG_DFL) {
/* init has generated a synchronous exception
and it doesn't have a handler for the signal */
printk(KERN_CRIT "init has generated signal %d "
"but has no handler for it\n", signr);
do_exit(signr);
}
}
}
#ifdef CONFIG_PPC64
void system_reset_exception(struct pt_regs *regs)
{
/* See if any machine dependent calls */
if (ppc_md.system_reset_exception) {
if (ppc_md.system_reset_exception(regs))
return;
}
#ifdef CONFIG_KEXEC
cpu_set(smp_processor_id(), cpus_in_sr);
#endif
die("System Reset", regs, SIGABRT);
/*
* Some CPUs when released from the debugger will execute this path.
* These CPUs entered the debugger via a soft-reset. If the CPU was
* hung before entering the debugger it will return to the hung
* state when exiting this function. This causes a problem in
* kdump since the hung CPU(s) will not respond to the IPI sent
* from kdump. To prevent the problem we call crash_kexec_secondary()
* here. If a kdump had not been initiated or we exit the debugger
* with the "exit and recover" command (x) crash_kexec_secondary()
* will return after 5ms and the CPU returns to its previous state.
*/
crash_kexec_secondary(regs);
/* Must die if the interrupt is not recoverable */
if (!(regs->msr & MSR_RI))
panic("Unrecoverable System Reset");
/* What should we do here? We could issue a shutdown or hard reset. */
}
#endif
/*
* I/O accesses can cause machine checks on powermacs.
* Check if the NIP corresponds to the address of a sync
* instruction for which there is an entry in the exception
* table.
* Note that the 601 only takes a machine check on TEA
* (transfer error ack) signal assertion, and does not
* set any of the top 16 bits of SRR1.
* -- paulus.
*/
static inline int check_io_access(struct pt_regs *regs)
{
#if defined(CONFIG_PPC_PMAC) && defined(CONFIG_PPC32)
unsigned long msr = regs->msr;
const struct exception_table_entry *entry;
unsigned int *nip = (unsigned int *)regs->nip;
if (((msr & 0xffff0000) == 0 || (msr & (0x80000 | 0x40000)))
&& (entry = search_exception_tables(regs->nip)) != NULL) {
/*
* Check that it's a sync instruction, or somewhere
* in the twi; isync; nop sequence that inb/inw/inl uses.
* As the address is in the exception table
* we should be able to read the instr there.
* For the debug message, we look at the preceding
* load or store.
*/
if (*nip == 0x60000000) /* nop */
nip -= 2;
else if (*nip == 0x4c00012c) /* isync */
--nip;
if (*nip == 0x7c0004ac || (*nip >> 26) == 3) {
/* sync or twi */
unsigned int rb;
--nip;
rb = (*nip >> 11) & 0x1f;
printk(KERN_DEBUG "%s bad port %lx at %p\n",
(*nip & 0x100)? "OUT to": "IN from",
regs->gpr[rb] - _IO_BASE, nip);
regs->msr |= MSR_RI;
regs->nip = entry->fixup;
return 1;
}
}
#endif /* CONFIG_PPC_PMAC && CONFIG_PPC32 */
return 0;
}
#if defined(CONFIG_4xx) || defined(CONFIG_BOOKE)
/* On 4xx, the reason for the machine check or program exception
is in the ESR. */
#define get_reason(regs) ((regs)->dsisr)
#ifndef CONFIG_FSL_BOOKE
#define get_mc_reason(regs) ((regs)->dsisr)
#else
#define get_mc_reason(regs) (mfspr(SPRN_MCSR))
#endif
#define REASON_FP ESR_FP
#define REASON_ILLEGAL (ESR_PIL | ESR_PUO)
#define REASON_PRIVILEGED ESR_PPR
#define REASON_TRAP ESR_PTR
/* single-step stuff */
#define single_stepping(regs) (current->thread.dbcr0 & DBCR0_IC)
#define clear_single_step(regs) (current->thread.dbcr0 &= ~DBCR0_IC)
#else
/* On non-4xx, the reason for the machine check or program
exception is in the MSR. */
#define get_reason(regs) ((regs)->msr)
#define get_mc_reason(regs) ((regs)->msr)
#define REASON_FP 0x100000
#define REASON_ILLEGAL 0x80000
#define REASON_PRIVILEGED 0x40000
#define REASON_TRAP 0x20000
#define single_stepping(regs) ((regs)->msr & MSR_SE)
#define clear_single_step(regs) ((regs)->msr &= ~MSR_SE)
#endif
/*
* This is "fall-back" implementation for configurations
* which don't provide platform-specific machine check info
*/
void __attribute__ ((weak))
platform_machine_check(struct pt_regs *regs)
{
}
void machine_check_exception(struct pt_regs *regs)
{
int recover = 0;
unsigned long reason = get_mc_reason(regs);
/* See if any machine dependent calls */
if (ppc_md.machine_check_exception)
recover = ppc_md.machine_check_exception(regs);
if (recover)
return;
if (user_mode(regs)) {
regs->msr |= MSR_RI;
_exception(SIGBUS, regs, BUS_ADRERR, regs->nip);
return;
}
#if defined(CONFIG_8xx) && defined(CONFIG_PCI)
/* the qspan pci read routines can cause machine checks -- Cort */
bad_page_fault(regs, regs->dar, SIGBUS);
return;
#endif
if (debugger_fault_handler(regs)) {
regs->msr |= MSR_RI;
return;
}
if (check_io_access(regs))
return;
#if defined(CONFIG_4xx) && !defined(CONFIG_440A)
if (reason & ESR_IMCP) {
printk("Instruction");
mtspr(SPRN_ESR, reason & ~ESR_IMCP);
} else
printk("Data");
printk(" machine check in kernel mode.\n");
#elif defined(CONFIG_440A)
printk("Machine check in kernel mode.\n");
if (reason & ESR_IMCP){
printk("Instruction Synchronous Machine Check exception\n");
mtspr(SPRN_ESR, reason & ~ESR_IMCP);
}
else {
u32 mcsr = mfspr(SPRN_MCSR);
if (mcsr & MCSR_IB)
printk("Instruction Read PLB Error\n");
if (mcsr & MCSR_DRB)
printk("Data Read PLB Error\n");
if (mcsr & MCSR_DWB)
printk("Data Write PLB Error\n");
if (mcsr & MCSR_TLBP)
printk("TLB Parity Error\n");
if (mcsr & MCSR_ICP){
flush_instruction_cache();
printk("I-Cache Parity Error\n");
}
if (mcsr & MCSR_DCSP)
printk("D-Cache Search Parity Error\n");
if (mcsr & MCSR_DCFP)
printk("D-Cache Flush Parity Error\n");
if (mcsr & MCSR_IMPE)
printk("Machine Check exception is imprecise\n");
/* Clear MCSR */
mtspr(SPRN_MCSR, mcsr);
}
#elif defined (CONFIG_E500)
printk("Machine check in kernel mode.\n");
printk("Caused by (from MCSR=%lx): ", reason);
if (reason & MCSR_MCP)
printk("Machine Check Signal\n");
if (reason & MCSR_ICPERR)
printk("Instruction Cache Parity Error\n");
if (reason & MCSR_DCP_PERR)
printk("Data Cache Push Parity Error\n");
if (reason & MCSR_DCPERR)
printk("Data Cache Parity Error\n");
if (reason & MCSR_GL_CI)
printk("Guarded Load or Cache-Inhibited stwcx.\n");
if (reason & MCSR_BUS_IAERR)
printk("Bus - Instruction Address Error\n");
if (reason & MCSR_BUS_RAERR)
printk("Bus - Read Address Error\n");
if (reason & MCSR_BUS_WAERR)
printk("Bus - Write Address Error\n");
if (reason & MCSR_BUS_IBERR)
printk("Bus - Instruction Data Error\n");
if (reason & MCSR_BUS_RBERR)
printk("Bus - Read Data Bus Error\n");
if (reason & MCSR_BUS_WBERR)
printk("Bus - Read Data Bus Error\n");
if (reason & MCSR_BUS_IPERR)
printk("Bus - Instruction Parity Error\n");
if (reason & MCSR_BUS_RPERR)
printk("Bus - Read Parity Error\n");
#elif defined (CONFIG_E200)
printk("Machine check in kernel mode.\n");
printk("Caused by (from MCSR=%lx): ", reason);
if (reason & MCSR_MCP)
printk("Machine Check Signal\n");
if (reason & MCSR_CP_PERR)
printk("Cache Push Parity Error\n");
if (reason & MCSR_CPERR)
printk("Cache Parity Error\n");
if (reason & MCSR_EXCP_ERR)
printk("ISI, ITLB, or Bus Error on first instruction fetch for an exception handler\n");
if (reason & MCSR_BUS_IRERR)
printk("Bus - Read Bus Error on instruction fetch\n");
if (reason & MCSR_BUS_DRERR)
printk("Bus - Read Bus Error on data load\n");
if (reason & MCSR_BUS_WRERR)
printk("Bus - Write Bus Error on buffered store or cache line push\n");
#else /* !CONFIG_4xx && !CONFIG_E500 && !CONFIG_E200 */
printk("Machine check in kernel mode.\n");
printk("Caused by (from SRR1=%lx): ", reason);
switch (reason & 0x601F0000) {
case 0x80000:
printk("Machine check signal\n");
break;
case 0: /* for 601 */
case 0x40000:
case 0x140000: /* 7450 MSS error and TEA */
printk("Transfer error ack signal\n");
break;
case 0x20000:
printk("Data parity error signal\n");
break;
case 0x10000:
printk("Address parity error signal\n");
break;
case 0x20000000:
printk("L1 Data Cache error\n");
break;
case 0x40000000:
printk("L1 Instruction Cache error\n");
break;
case 0x00100000:
printk("L2 data cache parity error\n");
break;
default:
printk("Unknown values in msr\n");
}
#endif /* CONFIG_4xx */
/*
* Optional platform-provided routine to print out
* additional info, e.g. bus error registers.
*/
platform_machine_check(regs);
if (debugger_fault_handler(regs))
return;
die("Machine check", regs, SIGBUS);
/* Must die if the interrupt is not recoverable */
if (!(regs->msr & MSR_RI))
panic("Unrecoverable Machine check");
}
void SMIException(struct pt_regs *regs)
{
die("System Management Interrupt", regs, SIGABRT);
}
void unknown_exception(struct pt_regs *regs)
{
printk("Bad trap at PC: %lx, SR: %lx, vector=%lx\n",
regs->nip, regs->msr, regs->trap);
_exception(SIGTRAP, regs, 0, 0);
}
void instruction_breakpoint_exception(struct pt_regs *regs)
{
if (notify_die(DIE_IABR_MATCH, "iabr_match", regs, 5,
5, SIGTRAP) == NOTIFY_STOP)
return;
if (debugger_iabr_match(regs))
return;
_exception(SIGTRAP, regs, TRAP_BRKPT, regs->nip);
}
void RunModeException(struct pt_regs *regs)
{
_exception(SIGTRAP, regs, 0, 0);
}
void __kprobes single_step_exception(struct pt_regs *regs)
{
regs->msr &= ~(MSR_SE | MSR_BE); /* Turn off 'trace' bits */
if (notify_die(DIE_SSTEP, "single_step", regs, 5,
5, SIGTRAP) == NOTIFY_STOP)
return;
if (debugger_sstep(regs))
return;
_exception(SIGTRAP, regs, TRAP_TRACE, regs->nip);
}
/*
* After we have successfully emulated an instruction, we have to
* check if the instruction was being single-stepped, and if so,
* pretend we got a single-step exception. This was pointed out
* by Kumar Gala. -- paulus
*/
static void emulate_single_step(struct pt_regs *regs)
{
if (single_stepping(regs)) {
clear_single_step(regs);
_exception(SIGTRAP, regs, TRAP_TRACE, 0);
}
}
static void parse_fpe(struct pt_regs *regs)
{
int code = 0;
unsigned long fpscr;
flush_fp_to_thread(current);
fpscr = current->thread.fpscr.val;
/* Invalid operation */
if ((fpscr & FPSCR_VE) && (fpscr & FPSCR_VX))
code = FPE_FLTINV;
/* Overflow */
else if ((fpscr & FPSCR_OE) && (fpscr & FPSCR_OX))
code = FPE_FLTOVF;
/* Underflow */
else if ((fpscr & FPSCR_UE) && (fpscr & FPSCR_UX))
code = FPE_FLTUND;
/* Divide by zero */
else if ((fpscr & FPSCR_ZE) && (fpscr & FPSCR_ZX))
code = FPE_FLTDIV;
/* Inexact result */
else if ((fpscr & FPSCR_XE) && (fpscr & FPSCR_XX))
code = FPE_FLTRES;
_exception(SIGFPE, regs, code, regs->nip);
}
/*
* Illegal instruction emulation support. Originally written to
* provide the PVR to user applications using the mfspr rd, PVR.
* Return non-zero if we can't emulate, or -EFAULT if the associated
* memory access caused an access fault. Return zero on success.
*
* There are a couple of ways to do this, either "decode" the instruction
* or directly match lots of bits. In this case, matching lots of
* bits is faster and easier.
*
*/
#define INST_MFSPR_PVR 0x7c1f42a6
#define INST_MFSPR_PVR_MASK 0xfc1fffff
#define INST_DCBA 0x7c0005ec
#define INST_DCBA_MASK 0xfc0007fe
#define INST_MCRXR 0x7c000400
#define INST_MCRXR_MASK 0xfc0007fe
#define INST_STRING 0x7c00042a
#define INST_STRING_MASK 0xfc0007fe
#define INST_STRING_GEN_MASK 0xfc00067e
#define INST_LSWI 0x7c0004aa
#define INST_LSWX 0x7c00042a
#define INST_STSWI 0x7c0005aa
#define INST_STSWX 0x7c00052a
#define INST_POPCNTB 0x7c0000f4
#define INST_POPCNTB_MASK 0xfc0007fe
static int emulate_string_inst(struct pt_regs *regs, u32 instword)
{
u8 rT = (instword >> 21) & 0x1f;
u8 rA = (instword >> 16) & 0x1f;
u8 NB_RB = (instword >> 11) & 0x1f;
u32 num_bytes;
unsigned long EA;
int pos = 0;
/* Early out if we are an invalid form of lswx */
if ((instword & INST_STRING_MASK) == INST_LSWX)
if ((rT == rA) || (rT == NB_RB))
return -EINVAL;
EA = (rA == 0) ? 0 : regs->gpr[rA];
switch (instword & INST_STRING_MASK) {
case INST_LSWX:
case INST_STSWX:
EA += NB_RB;
num_bytes = regs->xer & 0x7f;
break;
case INST_LSWI:
case INST_STSWI:
num_bytes = (NB_RB == 0) ? 32 : NB_RB;
break;
default:
return -EINVAL;
}
while (num_bytes != 0)
{
u8 val;
u32 shift = 8 * (3 - (pos & 0x3));
switch ((instword & INST_STRING_MASK)) {
case INST_LSWX:
case INST_LSWI:
if (get_user(val, (u8 __user *)EA))
return -EFAULT;
/* first time updating this reg,
* zero it out */
if (pos == 0)
regs->gpr[rT] = 0;
regs->gpr[rT] |= val << shift;
break;
case INST_STSWI:
case INST_STSWX:
val = regs->gpr[rT] >> shift;
if (put_user(val, (u8 __user *)EA))
return -EFAULT;
break;
}
/* move EA to next address */
EA += 1;
num_bytes--;
/* manage our position within the register */
if (++pos == 4) {
pos = 0;
if (++rT == 32)
rT = 0;
}
}
return 0;
}
static int emulate_popcntb_inst(struct pt_regs *regs, u32 instword)
{
u32 ra,rs;
unsigned long tmp;
ra = (instword >> 16) & 0x1f;
rs = (instword >> 21) & 0x1f;
tmp = regs->gpr[rs];
tmp = tmp - ((tmp >> 1) & 0x5555555555555555ULL);
tmp = (tmp & 0x3333333333333333ULL) + ((tmp >> 2) & 0x3333333333333333ULL);
tmp = (tmp + (tmp >> 4)) & 0x0f0f0f0f0f0f0f0fULL;
regs->gpr[ra] = tmp;
return 0;
}
static int emulate_instruction(struct pt_regs *regs)
{
u32 instword;
u32 rd;
if (!user_mode(regs) || (regs->msr & MSR_LE))
return -EINVAL;
CHECK_FULL_REGS(regs);
if (get_user(instword, (u32 __user *)(regs->nip)))
return -EFAULT;
/* Emulate the mfspr rD, PVR. */
if ((instword & INST_MFSPR_PVR_MASK) == INST_MFSPR_PVR) {
rd = (instword >> 21) & 0x1f;
regs->gpr[rd] = mfspr(SPRN_PVR);
return 0;
}
/* Emulating the dcba insn is just a no-op. */
if ((instword & INST_DCBA_MASK) == INST_DCBA)
return 0;
/* Emulate the mcrxr insn. */
if ((instword & INST_MCRXR_MASK) == INST_MCRXR) {
int shift = (instword >> 21) & 0x1c;
unsigned long msk = 0xf0000000UL >> shift;
regs->ccr = (regs->ccr & ~msk) | ((regs->xer >> shift) & msk);
regs->xer &= ~0xf0000000UL;
return 0;
}
/* Emulate load/store string insn. */
if ((instword & INST_STRING_GEN_MASK) == INST_STRING)
return emulate_string_inst(regs, instword);
/* Emulate the popcntb (Population Count Bytes) instruction. */
if ((instword & INST_POPCNTB_MASK) == INST_POPCNTB) {
return emulate_popcntb_inst(regs, instword);
}
return -EINVAL;
}
/*
* Look through the list of trap instructions that are used for BUG(),
* BUG_ON() and WARN_ON() and see if we hit one. At this point we know
* that the exception was caused by a trap instruction of some kind.
* Returns 1 if we should continue (i.e. it was a WARN_ON) or 0
* otherwise.
*/
extern struct bug_entry __start___bug_table[], __stop___bug_table[];
#ifndef CONFIG_MODULES
#define module_find_bug(x) NULL
#endif
struct bug_entry *find_bug(unsigned long bugaddr)
{
struct bug_entry *bug;
for (bug = __start___bug_table; bug < __stop___bug_table; ++bug)
if (bugaddr == bug->bug_addr)
return bug;
return module_find_bug(bugaddr);
}
static int check_bug_trap(struct pt_regs *regs)
{
struct bug_entry *bug;
unsigned long addr;
if (regs->msr & MSR_PR)
return 0; /* not in kernel */
addr = regs->nip; /* address of trap instruction */
if (addr < PAGE_OFFSET)
return 0;
bug = find_bug(regs->nip);
if (bug == NULL)
return 0;
if (bug->line & BUG_WARNING_TRAP) {
/* this is a WARN_ON rather than BUG/BUG_ON */
printk(KERN_ERR "Badness in %s at %s:%ld\n",
bug->function, bug->file,
bug->line & ~BUG_WARNING_TRAP);
dump_stack();
return 1;
}
printk(KERN_CRIT "kernel BUG in %s at %s:%ld!\n",
bug->function, bug->file, bug->line);
return 0;
}
void __kprobes program_check_exception(struct pt_regs *regs)
{
unsigned int reason = get_reason(regs);
extern int do_mathemu(struct pt_regs *regs);
#ifdef CONFIG_MATH_EMULATION
/* (reason & REASON_ILLEGAL) would be the obvious thing here,
* but there seems to be a hardware bug on the 405GP (RevD)
* that means ESR is sometimes set incorrectly - either to
* ESR_DST (!?) or 0. In the process of chasing this with the
* hardware people - not sure if it can happen on any illegal
* instruction or only on FP instructions, whether there is a
* pattern to occurences etc. -dgibson 31/Mar/2003 */
if (!(reason & REASON_TRAP) && do_mathemu(regs) == 0) {
emulate_single_step(regs);
return;
}
#endif /* CONFIG_MATH_EMULATION */
if (reason & REASON_FP) {
/* IEEE FP exception */
parse_fpe(regs);
return;
}
if (reason & REASON_TRAP) {
/* trap exception */
if (notify_die(DIE_BPT, "breakpoint", regs, 5, 5, SIGTRAP)
== NOTIFY_STOP)
return;
if (debugger_bpt(regs))
return;
if (check_bug_trap(regs)) {
regs->nip += 4;
return;
}
_exception(SIGTRAP, regs, TRAP_BRKPT, regs->nip);
return;
}
local_irq_enable();
/* Try to emulate it if we should. */
if (reason & (REASON_ILLEGAL | REASON_PRIVILEGED)) {
switch (emulate_instruction(regs)) {
case 0:
regs->nip += 4;
emulate_single_step(regs);
return;
case -EFAULT:
_exception(SIGSEGV, regs, SEGV_MAPERR, regs->nip);
return;
}
}
if (reason & REASON_PRIVILEGED)
_exception(SIGILL, regs, ILL_PRVOPC, regs->nip);
else
_exception(SIGILL, regs, ILL_ILLOPC, regs->nip);
}
void alignment_exception(struct pt_regs *regs)
{
int fixed = 0;
/* we don't implement logging of alignment exceptions */
if (!(current->thread.align_ctl & PR_UNALIGN_SIGBUS))
fixed = fix_alignment(regs);
if (fixed == 1) {
regs->nip += 4; /* skip over emulated instruction */
emulate_single_step(regs);
return;
}
/* Operand address was bad */
if (fixed == -EFAULT) {
if (user_mode(regs))
_exception(SIGSEGV, regs, SEGV_ACCERR, regs->dar);
else
/* Search exception table */
bad_page_fault(regs, regs->dar, SIGSEGV);
return;
}
_exception(SIGBUS, regs, BUS_ADRALN, regs->dar);
}
void StackOverflow(struct pt_regs *regs)
{
printk(KERN_CRIT "Kernel stack overflow in process %p, r1=%lx\n",
current, regs->gpr[1]);
debugger(regs);
show_regs(regs);
panic("kernel stack overflow");
}
void nonrecoverable_exception(struct pt_regs *regs)
{
printk(KERN_ERR "Non-recoverable exception at PC=%lx MSR=%lx\n",
regs->nip, regs->msr);
debugger(regs);
die("nonrecoverable exception", regs, SIGKILL);
}
void trace_syscall(struct pt_regs *regs)
{
printk("Task: %p(%d), PC: %08lX/%08lX, Syscall: %3ld, Result: %s%ld %s\n",
current, current->pid, regs->nip, regs->link, regs->gpr[0],
regs->ccr&0x10000000?"Error=":"", regs->gpr[3], print_tainted());
}
void kernel_fp_unavailable_exception(struct pt_regs *regs)
{
printk(KERN_EMERG "Unrecoverable FP Unavailable Exception "
"%lx at %lx\n", regs->trap, regs->nip);
die("Unrecoverable FP Unavailable Exception", regs, SIGABRT);
}
void altivec_unavailable_exception(struct pt_regs *regs)
{
if (user_mode(regs)) {
/* A user program has executed an altivec instruction,
but this kernel doesn't support altivec. */
_exception(SIGILL, regs, ILL_ILLOPC, regs->nip);
return;
}
printk(KERN_EMERG "Unrecoverable VMX/Altivec Unavailable Exception "
"%lx at %lx\n", regs->trap, regs->nip);
die("Unrecoverable VMX/Altivec Unavailable Exception", regs, SIGABRT);
}
void performance_monitor_exception(struct pt_regs *regs)
{
perf_irq(regs);
}
#ifdef CONFIG_8xx
void SoftwareEmulation(struct pt_regs *regs)
{
extern int do_mathemu(struct pt_regs *);
extern int Soft_emulate_8xx(struct pt_regs *);
int errcode;
CHECK_FULL_REGS(regs);
if (!user_mode(regs)) {
debugger(regs);
die("Kernel Mode Software FPU Emulation", regs, SIGFPE);
}
#ifdef CONFIG_MATH_EMULATION
errcode = do_mathemu(regs);
#else
errcode = Soft_emulate_8xx(regs);
#endif
if (errcode) {
if (errcode > 0)
_exception(SIGFPE, regs, 0, 0);
else if (errcode == -EFAULT)
_exception(SIGSEGV, regs, 0, 0);
else
_exception(SIGILL, regs, ILL_ILLOPC, regs->nip);
} else
emulate_single_step(regs);
}
#endif /* CONFIG_8xx */
#if defined(CONFIG_40x) || defined(CONFIG_BOOKE)
void DebugException(struct pt_regs *regs, unsigned long debug_status)
{
if (debug_status & DBSR_IC) { /* instruction completion */
regs->msr &= ~MSR_DE;
if (user_mode(regs)) {
current->thread.dbcr0 &= ~DBCR0_IC;
} else {
/* Disable instruction completion */
mtspr(SPRN_DBCR0, mfspr(SPRN_DBCR0) & ~DBCR0_IC);
/* Clear the instruction completion event */
mtspr(SPRN_DBSR, DBSR_IC);
if (debugger_sstep(regs))
return;
}
_exception(SIGTRAP, regs, TRAP_TRACE, 0);
}
}
#endif /* CONFIG_4xx || CONFIG_BOOKE */
#if !defined(CONFIG_TAU_INT)
void TAUException(struct pt_regs *regs)
{
printk("TAU trap at PC: %lx, MSR: %lx, vector=%lx %s\n",
regs->nip, regs->msr, regs->trap, print_tainted());
}
#endif /* CONFIG_INT_TAU */
#ifdef CONFIG_ALTIVEC
void altivec_assist_exception(struct pt_regs *regs)
{
int err;
if (!user_mode(regs)) {
printk(KERN_EMERG "VMX/Altivec assist exception in kernel mode"
" at %lx\n", regs->nip);
die("Kernel VMX/Altivec assist exception", regs, SIGILL);
}
flush_altivec_to_thread(current);
err = emulate_altivec(regs);
if (err == 0) {
regs->nip += 4; /* skip emulated instruction */
emulate_single_step(regs);
return;
}
if (err == -EFAULT) {
/* got an error reading the instruction */
_exception(SIGSEGV, regs, SEGV_ACCERR, regs->nip);
} else {
/* didn't recognize the instruction */
/* XXX quick hack for now: set the non-Java bit in the VSCR */
if (printk_ratelimit())
printk(KERN_ERR "Unrecognized altivec instruction "
"in %s at %lx\n", current->comm, regs->nip);
current->thread.vscr.u[3] |= 0x10000;
}
}
#endif /* CONFIG_ALTIVEC */
#ifdef CONFIG_FSL_BOOKE
void CacheLockingException(struct pt_regs *regs, unsigned long address,
unsigned long error_code)
{
/* We treat cache locking instructions from the user
* as priv ops, in the future we could try to do
* something smarter
*/
if (error_code & (ESR_DLK|ESR_ILK))
_exception(SIGILL, regs, ILL_PRVOPC, regs->nip);
return;
}
#endif /* CONFIG_FSL_BOOKE */
#ifdef CONFIG_SPE
void SPEFloatingPointException(struct pt_regs *regs)
{
unsigned long spefscr;
int fpexc_mode;
int code = 0;
spefscr = current->thread.spefscr;
fpexc_mode = current->thread.fpexc_mode;
/* Hardware does not neccessarily set sticky
* underflow/overflow/invalid flags */
if ((spefscr & SPEFSCR_FOVF) && (fpexc_mode & PR_FP_EXC_OVF)) {
code = FPE_FLTOVF;
spefscr |= SPEFSCR_FOVFS;
}
else if ((spefscr & SPEFSCR_FUNF) && (fpexc_mode & PR_FP_EXC_UND)) {
code = FPE_FLTUND;
spefscr |= SPEFSCR_FUNFS;
}
else if ((spefscr & SPEFSCR_FDBZ) && (fpexc_mode & PR_FP_EXC_DIV))
code = FPE_FLTDIV;
else if ((spefscr & SPEFSCR_FINV) && (fpexc_mode & PR_FP_EXC_INV)) {
code = FPE_FLTINV;
spefscr |= SPEFSCR_FINVS;
}
else if ((spefscr & (SPEFSCR_FG | SPEFSCR_FX)) && (fpexc_mode & PR_FP_EXC_RES))
code = FPE_FLTRES;
current->thread.spefscr = spefscr;
_exception(SIGFPE, regs, code, regs->nip);
return;
}
#endif
/*
* We enter here if we get an unrecoverable exception, that is, one
* that happened at a point where the RI (recoverable interrupt) bit
* in the MSR is 0. This indicates that SRR0/1 are live, and that
* we therefore lost state by taking this exception.
*/
void unrecoverable_exception(struct pt_regs *regs)
{
printk(KERN_EMERG "Unrecoverable exception %lx at %lx\n",
regs->trap, regs->nip);
die("Unrecoverable exception", regs, SIGABRT);
}
#ifdef CONFIG_BOOKE_WDT
/*
* Default handler for a Watchdog exception,
* spins until a reboot occurs
*/
void __attribute__ ((weak)) WatchdogHandler(struct pt_regs *regs)
{
/* Generic WatchdogHandler, implement your own */
mtspr(SPRN_TCR, mfspr(SPRN_TCR)&(~TCR_WIE));
return;
}
void WatchdogException(struct pt_regs *regs)
{
printk (KERN_EMERG "PowerPC Book-E Watchdog Exception\n");
WatchdogHandler(regs);
}
#endif
/*
* We enter here if we discover during exception entry that we are
* running in supervisor mode with a userspace value in the stack pointer.
*/
void kernel_bad_stack(struct pt_regs *regs)
{
printk(KERN_EMERG "Bad kernel stack pointer %lx at %lx\n",
regs->gpr[1], regs->nip);
die("Bad kernel stack pointer", regs, SIGABRT);
}
void __init trap_init(void)
{
}
| ./CrossVul/dataset_final_sorted/CWE-19/c/good_2484_0 |
crossvul-cpp_data_bad_5319_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% RRRR GGG FFFFF %
% R R G F %
% RRRR G GG FFF %
% R R G G F %
% R R GGG F %
% %
% %
% Read/Write LEGO Mindstorms EV3 Robot Graphics File %
% %
% Software Design %
% Brian Wheeler %
% August 2013 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/utility.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteRGFImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d X B M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadRGFImage() reads an RGF bitmap image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadRGFImage method is:
%
% Image *ReadRGFImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadRGFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bit,
byte;
ssize_t
y;
unsigned char
*data;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read RGF header.
*/
image->columns = (unsigned long) ReadBlobByte(image);
image->rows = (unsigned long) ReadBlobByte(image);
image->depth=8;
image->storage_class=PseudoClass;
image->colors=2;
/*
Initialize image structure.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize colormap.
*/
image->colormap[0].red=QuantumRange;
image->colormap[0].green=QuantumRange;
image->colormap[0].blue=QuantumRange;
image->colormap[1].red=(Quantum) 0;
image->colormap[1].green=(Quantum) 0;
image->colormap[1].blue=(Quantum) 0;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Read hex image data.
*/
data=(unsigned char *) AcquireQuantumMemory(image->rows,image->columns*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) (image->columns * image->rows); i++)
{
*p++=ReadBlobByte(image);
}
/*
Convert RGF image to pixel packets.
*/
p=data;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
byte=(size_t) (*p++);
SetPixelIndex(indexes+x,(Quantum) ((byte & 0x01) != 0 ? 0x01 : 0x00));
bit++;
byte>>=1;
if (bit == 8)
bit=0;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
data=(unsigned char *) RelinquishMagickMemory(data);
(void) SyncImage(image);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r R G F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterRGFImage() adds attributes for the RGF image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterRGFImage method is:
%
% size_t RegisterRGFImage(void)
%
*/
ModuleExport size_t RegisterRGFImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("RGF");
entry->decoder=(DecodeImageHandler *) ReadRGFImage;
entry->encoder=(EncodeImageHandler *) WriteRGFImage;
entry->adjoin=MagickFalse;
entry->description=ConstantString(
"LEGO Mindstorms EV3 Robot Graphic Format (black and white)");
entry->module=ConstantString("RGF");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r R G F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterRGFImage() removes format registrations made by the
% RGF module from the list of supported formats.
%
% The format of the UnregisterRGFImage method is:
%
% UnregisterRGFImage(void)
%
*/
ModuleExport void UnregisterRGFImage(void)
{
(void) UnregisterMagickInfo("RGF");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e R G F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteRGFImage() writes an image to a file in the X bitmap format.
%
% The format of the WriteRGFImage method is:
%
% MagickBooleanType WriteRGFImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WriteRGFImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
MagickBooleanType
status;
int
bit;
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
y;
unsigned char
byte;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
if((image->columns > 255L) || (image->rows > 255L))
ThrowWriterException(ImageError,"Dimensions must be less than 255x255");
/*
Write header (just the image dimensions)
*/
(void) WriteBlobByte(image,image->columns & 0xff);
(void) WriteBlobByte(image,image->rows & 0xff);
/*
Convert MIFF to bit pixels.
*/
(void) SetImageType(image,BilevelType);
x=0;
y=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte>>=1;
if (GetPixelLuma(image,p) < (QuantumRange/2.0))
byte|=0x80;
bit++;
if (bit == 8)
{
/*
Write a bitmap byte to the image file.
*/
(void) WriteBlobByte(image,byte);
bit=0;
byte=0;
}
p++;
}
if (bit != 0)
(void) WriteBlobByte(image,byte);
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-19/c/bad_5319_0 |
crossvul-cpp_data_bad_1453_0 | /*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would 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 the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_shared.h"
#include "xfs_format.h"
#include "xfs_log_format.h"
#include "xfs_trans_resv.h"
#include "xfs_bit.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_da_format.h"
#include "xfs_da_btree.h"
#include "xfs_attr_sf.h"
#include "xfs_inode.h"
#include "xfs_alloc.h"
#include "xfs_trans.h"
#include "xfs_inode_item.h"
#include "xfs_bmap.h"
#include "xfs_bmap_util.h"
#include "xfs_bmap_btree.h"
#include "xfs_attr.h"
#include "xfs_attr_leaf.h"
#include "xfs_attr_remote.h"
#include "xfs_error.h"
#include "xfs_quota.h"
#include "xfs_trans_space.h"
#include "xfs_trace.h"
#include "xfs_dinode.h"
/*
* xfs_attr.c
*
* Provide the external interfaces to manage attribute lists.
*/
/*========================================================================
* Function prototypes for the kernel.
*========================================================================*/
/*
* Internal routines when attribute list fits inside the inode.
*/
STATIC int xfs_attr_shortform_addname(xfs_da_args_t *args);
/*
* Internal routines when attribute list is one block.
*/
STATIC int xfs_attr_leaf_get(xfs_da_args_t *args);
STATIC int xfs_attr_leaf_addname(xfs_da_args_t *args);
STATIC int xfs_attr_leaf_removename(xfs_da_args_t *args);
/*
* Internal routines when attribute list is more than one block.
*/
STATIC int xfs_attr_node_get(xfs_da_args_t *args);
STATIC int xfs_attr_node_addname(xfs_da_args_t *args);
STATIC int xfs_attr_node_removename(xfs_da_args_t *args);
STATIC int xfs_attr_fillstate(xfs_da_state_t *state);
STATIC int xfs_attr_refillstate(xfs_da_state_t *state);
STATIC int
xfs_attr_name_to_xname(
struct xfs_name *xname,
const unsigned char *aname)
{
if (!aname)
return EINVAL;
xname->name = aname;
xname->len = strlen((char *)aname);
if (xname->len >= MAXNAMELEN)
return EFAULT; /* match IRIX behaviour */
return 0;
}
int
xfs_inode_hasattr(
struct xfs_inode *ip)
{
if (!XFS_IFORK_Q(ip) ||
(ip->i_d.di_aformat == XFS_DINODE_FMT_EXTENTS &&
ip->i_d.di_anextents == 0))
return 0;
return 1;
}
/*========================================================================
* Overall external interface routines.
*========================================================================*/
STATIC int
xfs_attr_get_int(
struct xfs_inode *ip,
struct xfs_name *name,
unsigned char *value,
int *valuelenp,
int flags)
{
xfs_da_args_t args;
int error;
if (!xfs_inode_hasattr(ip))
return ENOATTR;
/*
* Fill in the arg structure for this request.
*/
memset((char *)&args, 0, sizeof(args));
args.name = name->name;
args.namelen = name->len;
args.value = value;
args.valuelen = *valuelenp;
args.flags = flags;
args.hashval = xfs_da_hashname(args.name, args.namelen);
args.dp = ip;
args.whichfork = XFS_ATTR_FORK;
/*
* Decide on what work routines to call based on the inode size.
*/
if (ip->i_d.di_aformat == XFS_DINODE_FMT_LOCAL) {
error = xfs_attr_shortform_getvalue(&args);
} else if (xfs_bmap_one_block(ip, XFS_ATTR_FORK)) {
error = xfs_attr_leaf_get(&args);
} else {
error = xfs_attr_node_get(&args);
}
/*
* Return the number of bytes in the value to the caller.
*/
*valuelenp = args.valuelen;
if (error == EEXIST)
error = 0;
return(error);
}
int
xfs_attr_get(
xfs_inode_t *ip,
const unsigned char *name,
unsigned char *value,
int *valuelenp,
int flags)
{
int error;
struct xfs_name xname;
uint lock_mode;
XFS_STATS_INC(xs_attr_get);
if (XFS_FORCED_SHUTDOWN(ip->i_mount))
return(EIO);
error = xfs_attr_name_to_xname(&xname, name);
if (error)
return error;
lock_mode = xfs_ilock_attr_map_shared(ip);
error = xfs_attr_get_int(ip, &xname, value, valuelenp, flags);
xfs_iunlock(ip, lock_mode);
return(error);
}
/*
* Calculate how many blocks we need for the new attribute,
*/
STATIC int
xfs_attr_calc_size(
struct xfs_inode *ip,
int namelen,
int valuelen,
int *local)
{
struct xfs_mount *mp = ip->i_mount;
int size;
int nblks;
/*
* Determine space new attribute will use, and if it would be
* "local" or "remote" (note: local != inline).
*/
size = xfs_attr_leaf_newentsize(namelen, valuelen,
mp->m_sb.sb_blocksize, local);
nblks = XFS_DAENTER_SPACE_RES(mp, XFS_ATTR_FORK);
if (*local) {
if (size > (mp->m_sb.sb_blocksize >> 1)) {
/* Double split possible */
nblks *= 2;
}
} else {
/*
* Out of line attribute, cannot double split, but
* make room for the attribute value itself.
*/
uint dblocks = XFS_B_TO_FSB(mp, valuelen);
nblks += dblocks;
nblks += XFS_NEXTENTADD_SPACE_RES(mp, dblocks, XFS_ATTR_FORK);
}
return nblks;
}
STATIC int
xfs_attr_set_int(
struct xfs_inode *dp,
struct xfs_name *name,
unsigned char *value,
int valuelen,
int flags)
{
xfs_da_args_t args;
xfs_fsblock_t firstblock;
xfs_bmap_free_t flist;
int error, err2, committed;
struct xfs_mount *mp = dp->i_mount;
struct xfs_trans_res tres;
int rsvd = (flags & ATTR_ROOT) != 0;
int local;
/*
* Attach the dquots to the inode.
*/
error = xfs_qm_dqattach(dp, 0);
if (error)
return error;
/*
* If the inode doesn't have an attribute fork, add one.
* (inode must not be locked when we call this routine)
*/
if (XFS_IFORK_Q(dp) == 0) {
int sf_size = sizeof(xfs_attr_sf_hdr_t) +
XFS_ATTR_SF_ENTSIZE_BYNAME(name->len, valuelen);
if ((error = xfs_bmap_add_attrfork(dp, sf_size, rsvd)))
return(error);
}
/*
* Fill in the arg structure for this request.
*/
memset((char *)&args, 0, sizeof(args));
args.name = name->name;
args.namelen = name->len;
args.value = value;
args.valuelen = valuelen;
args.flags = flags;
args.hashval = xfs_da_hashname(args.name, args.namelen);
args.dp = dp;
args.firstblock = &firstblock;
args.flist = &flist;
args.whichfork = XFS_ATTR_FORK;
args.op_flags = XFS_DA_OP_ADDNAME | XFS_DA_OP_OKNOENT;
/* Size is now blocks for attribute data */
args.total = xfs_attr_calc_size(dp, name->len, valuelen, &local);
/*
* Start our first transaction of the day.
*
* All future transactions during this code must be "chained" off
* this one via the trans_dup() call. All transactions will contain
* the inode, and the inode will always be marked with trans_ihold().
* Since the inode will be locked in all transactions, we must log
* the inode in every transaction to let it float upward through
* the log.
*/
args.trans = xfs_trans_alloc(mp, XFS_TRANS_ATTR_SET);
/*
* Root fork attributes can use reserved data blocks for this
* operation if necessary
*/
if (rsvd)
args.trans->t_flags |= XFS_TRANS_RESERVE;
tres.tr_logres = M_RES(mp)->tr_attrsetm.tr_logres +
M_RES(mp)->tr_attrsetrt.tr_logres * args.total;
tres.tr_logcount = XFS_ATTRSET_LOG_COUNT;
tres.tr_logflags = XFS_TRANS_PERM_LOG_RES;
error = xfs_trans_reserve(args.trans, &tres, args.total, 0);
if (error) {
xfs_trans_cancel(args.trans, 0);
return(error);
}
xfs_ilock(dp, XFS_ILOCK_EXCL);
error = xfs_trans_reserve_quota_nblks(args.trans, dp, args.total, 0,
rsvd ? XFS_QMOPT_RES_REGBLKS | XFS_QMOPT_FORCE_RES :
XFS_QMOPT_RES_REGBLKS);
if (error) {
xfs_iunlock(dp, XFS_ILOCK_EXCL);
xfs_trans_cancel(args.trans, XFS_TRANS_RELEASE_LOG_RES);
return (error);
}
xfs_trans_ijoin(args.trans, dp, 0);
/*
* If the attribute list is non-existent or a shortform list,
* upgrade it to a single-leaf-block attribute list.
*/
if ((dp->i_d.di_aformat == XFS_DINODE_FMT_LOCAL) ||
((dp->i_d.di_aformat == XFS_DINODE_FMT_EXTENTS) &&
(dp->i_d.di_anextents == 0))) {
/*
* Build initial attribute list (if required).
*/
if (dp->i_d.di_aformat == XFS_DINODE_FMT_EXTENTS)
xfs_attr_shortform_create(&args);
/*
* Try to add the attr to the attribute list in
* the inode.
*/
error = xfs_attr_shortform_addname(&args);
if (error != ENOSPC) {
/*
* Commit the shortform mods, and we're done.
* NOTE: this is also the error path (EEXIST, etc).
*/
ASSERT(args.trans != NULL);
/*
* If this is a synchronous mount, make sure that
* the transaction goes to disk before returning
* to the user.
*/
if (mp->m_flags & XFS_MOUNT_WSYNC) {
xfs_trans_set_sync(args.trans);
}
if (!error && (flags & ATTR_KERNOTIME) == 0) {
xfs_trans_ichgtime(args.trans, dp,
XFS_ICHGTIME_CHG);
}
err2 = xfs_trans_commit(args.trans,
XFS_TRANS_RELEASE_LOG_RES);
xfs_iunlock(dp, XFS_ILOCK_EXCL);
return(error == 0 ? err2 : error);
}
/*
* It won't fit in the shortform, transform to a leaf block.
* GROT: another possible req'mt for a double-split btree op.
*/
xfs_bmap_init(args.flist, args.firstblock);
error = xfs_attr_shortform_to_leaf(&args);
if (!error) {
error = xfs_bmap_finish(&args.trans, args.flist,
&committed);
}
if (error) {
ASSERT(committed);
args.trans = NULL;
xfs_bmap_cancel(&flist);
goto out;
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args.trans, dp, 0);
/*
* Commit the leaf transformation. We'll need another (linked)
* transaction to add the new attribute to the leaf.
*/
error = xfs_trans_roll(&args.trans, dp);
if (error)
goto out;
}
if (xfs_bmap_one_block(dp, XFS_ATTR_FORK)) {
error = xfs_attr_leaf_addname(&args);
} else {
error = xfs_attr_node_addname(&args);
}
if (error) {
goto out;
}
/*
* If this is a synchronous mount, make sure that the
* transaction goes to disk before returning to the user.
*/
if (mp->m_flags & XFS_MOUNT_WSYNC) {
xfs_trans_set_sync(args.trans);
}
if ((flags & ATTR_KERNOTIME) == 0)
xfs_trans_ichgtime(args.trans, dp, XFS_ICHGTIME_CHG);
/*
* Commit the last in the sequence of transactions.
*/
xfs_trans_log_inode(args.trans, dp, XFS_ILOG_CORE);
error = xfs_trans_commit(args.trans, XFS_TRANS_RELEASE_LOG_RES);
xfs_iunlock(dp, XFS_ILOCK_EXCL);
return(error);
out:
if (args.trans)
xfs_trans_cancel(args.trans,
XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT);
xfs_iunlock(dp, XFS_ILOCK_EXCL);
return(error);
}
int
xfs_attr_set(
xfs_inode_t *dp,
const unsigned char *name,
unsigned char *value,
int valuelen,
int flags)
{
int error;
struct xfs_name xname;
XFS_STATS_INC(xs_attr_set);
if (XFS_FORCED_SHUTDOWN(dp->i_mount))
return (EIO);
error = xfs_attr_name_to_xname(&xname, name);
if (error)
return error;
return xfs_attr_set_int(dp, &xname, value, valuelen, flags);
}
/*
* Generic handler routine to remove a name from an attribute list.
* Transitions attribute list from Btree to shortform as necessary.
*/
STATIC int
xfs_attr_remove_int(xfs_inode_t *dp, struct xfs_name *name, int flags)
{
xfs_da_args_t args;
xfs_fsblock_t firstblock;
xfs_bmap_free_t flist;
int error;
xfs_mount_t *mp = dp->i_mount;
/*
* Fill in the arg structure for this request.
*/
memset((char *)&args, 0, sizeof(args));
args.name = name->name;
args.namelen = name->len;
args.flags = flags;
args.hashval = xfs_da_hashname(args.name, args.namelen);
args.dp = dp;
args.firstblock = &firstblock;
args.flist = &flist;
args.total = 0;
args.whichfork = XFS_ATTR_FORK;
/*
* we have no control over the attribute names that userspace passes us
* to remove, so we have to allow the name lookup prior to attribute
* removal to fail.
*/
args.op_flags = XFS_DA_OP_OKNOENT;
/*
* Attach the dquots to the inode.
*/
error = xfs_qm_dqattach(dp, 0);
if (error)
return error;
/*
* Start our first transaction of the day.
*
* All future transactions during this code must be "chained" off
* this one via the trans_dup() call. All transactions will contain
* the inode, and the inode will always be marked with trans_ihold().
* Since the inode will be locked in all transactions, we must log
* the inode in every transaction to let it float upward through
* the log.
*/
args.trans = xfs_trans_alloc(mp, XFS_TRANS_ATTR_RM);
/*
* Root fork attributes can use reserved data blocks for this
* operation if necessary
*/
if (flags & ATTR_ROOT)
args.trans->t_flags |= XFS_TRANS_RESERVE;
error = xfs_trans_reserve(args.trans, &M_RES(mp)->tr_attrrm,
XFS_ATTRRM_SPACE_RES(mp), 0);
if (error) {
xfs_trans_cancel(args.trans, 0);
return(error);
}
xfs_ilock(dp, XFS_ILOCK_EXCL);
/*
* No need to make quota reservations here. We expect to release some
* blocks not allocate in the common case.
*/
xfs_trans_ijoin(args.trans, dp, 0);
/*
* Decide on what work routines to call based on the inode size.
*/
if (!xfs_inode_hasattr(dp)) {
error = XFS_ERROR(ENOATTR);
goto out;
}
if (dp->i_d.di_aformat == XFS_DINODE_FMT_LOCAL) {
ASSERT(dp->i_afp->if_flags & XFS_IFINLINE);
error = xfs_attr_shortform_remove(&args);
if (error) {
goto out;
}
} else if (xfs_bmap_one_block(dp, XFS_ATTR_FORK)) {
error = xfs_attr_leaf_removename(&args);
} else {
error = xfs_attr_node_removename(&args);
}
if (error) {
goto out;
}
/*
* If this is a synchronous mount, make sure that the
* transaction goes to disk before returning to the user.
*/
if (mp->m_flags & XFS_MOUNT_WSYNC) {
xfs_trans_set_sync(args.trans);
}
if ((flags & ATTR_KERNOTIME) == 0)
xfs_trans_ichgtime(args.trans, dp, XFS_ICHGTIME_CHG);
/*
* Commit the last in the sequence of transactions.
*/
xfs_trans_log_inode(args.trans, dp, XFS_ILOG_CORE);
error = xfs_trans_commit(args.trans, XFS_TRANS_RELEASE_LOG_RES);
xfs_iunlock(dp, XFS_ILOCK_EXCL);
return(error);
out:
if (args.trans)
xfs_trans_cancel(args.trans,
XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT);
xfs_iunlock(dp, XFS_ILOCK_EXCL);
return(error);
}
int
xfs_attr_remove(
xfs_inode_t *dp,
const unsigned char *name,
int flags)
{
int error;
struct xfs_name xname;
XFS_STATS_INC(xs_attr_remove);
if (XFS_FORCED_SHUTDOWN(dp->i_mount))
return (EIO);
error = xfs_attr_name_to_xname(&xname, name);
if (error)
return error;
xfs_ilock(dp, XFS_ILOCK_SHARED);
if (!xfs_inode_hasattr(dp)) {
xfs_iunlock(dp, XFS_ILOCK_SHARED);
return XFS_ERROR(ENOATTR);
}
xfs_iunlock(dp, XFS_ILOCK_SHARED);
return xfs_attr_remove_int(dp, &xname, flags);
}
/*========================================================================
* External routines when attribute list is inside the inode
*========================================================================*/
/*
* Add a name to the shortform attribute list structure
* This is the external routine.
*/
STATIC int
xfs_attr_shortform_addname(xfs_da_args_t *args)
{
int newsize, forkoff, retval;
trace_xfs_attr_sf_addname(args);
retval = xfs_attr_shortform_lookup(args);
if ((args->flags & ATTR_REPLACE) && (retval == ENOATTR)) {
return(retval);
} else if (retval == EEXIST) {
if (args->flags & ATTR_CREATE)
return(retval);
retval = xfs_attr_shortform_remove(args);
ASSERT(retval == 0);
}
if (args->namelen >= XFS_ATTR_SF_ENTSIZE_MAX ||
args->valuelen >= XFS_ATTR_SF_ENTSIZE_MAX)
return(XFS_ERROR(ENOSPC));
newsize = XFS_ATTR_SF_TOTSIZE(args->dp);
newsize += XFS_ATTR_SF_ENTSIZE_BYNAME(args->namelen, args->valuelen);
forkoff = xfs_attr_shortform_bytesfit(args->dp, newsize);
if (!forkoff)
return(XFS_ERROR(ENOSPC));
xfs_attr_shortform_add(args, forkoff);
return(0);
}
/*========================================================================
* External routines when attribute list is one block
*========================================================================*/
/*
* Add a name to the leaf attribute list structure
*
* This leaf block cannot have a "remote" value, we only call this routine
* if bmap_one_block() says there is only one block (ie: no remote blks).
*/
STATIC int
xfs_attr_leaf_addname(xfs_da_args_t *args)
{
xfs_inode_t *dp;
struct xfs_buf *bp;
int retval, error, committed, forkoff;
trace_xfs_attr_leaf_addname(args);
/*
* Read the (only) block in the attribute list in.
*/
dp = args->dp;
args->blkno = 0;
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return error;
/*
* Look up the given attribute in the leaf block. Figure out if
* the given flags produce an error or call for an atomic rename.
*/
retval = xfs_attr3_leaf_lookup_int(bp, args);
if ((args->flags & ATTR_REPLACE) && (retval == ENOATTR)) {
xfs_trans_brelse(args->trans, bp);
return retval;
} else if (retval == EEXIST) {
if (args->flags & ATTR_CREATE) { /* pure create op */
xfs_trans_brelse(args->trans, bp);
return retval;
}
trace_xfs_attr_leaf_replace(args);
args->op_flags |= XFS_DA_OP_RENAME; /* an atomic rename */
args->blkno2 = args->blkno; /* set 2nd entry info*/
args->index2 = args->index;
args->rmtblkno2 = args->rmtblkno;
args->rmtblkcnt2 = args->rmtblkcnt;
}
/*
* Add the attribute to the leaf block, transitioning to a Btree
* if required.
*/
retval = xfs_attr3_leaf_add(bp, args);
if (retval == ENOSPC) {
/*
* Promote the attribute list to the Btree format, then
* Commit that transaction so that the node_addname() call
* can manage its own transactions.
*/
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr3_leaf_to_node(args);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
/*
* Commit the current trans (including the inode) and start
* a new one.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
/*
* Fob the whole rest of the problem off on the Btree code.
*/
error = xfs_attr_node_addname(args);
return(error);
}
/*
* Commit the transaction that added the attr name so that
* later routines can manage their own transactions.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
/*
* If there was an out-of-line value, allocate the blocks we
* identified for its storage and copy the value. This is done
* after we create the attribute so that we don't overflow the
* maximum size of a transaction and/or hit a deadlock.
*/
if (args->rmtblkno > 0) {
error = xfs_attr_rmtval_set(args);
if (error)
return(error);
}
/*
* If this is an atomic rename operation, we must "flip" the
* incomplete flags on the "new" and "old" attribute/value pairs
* so that one disappears and one appears atomically. Then we
* must remove the "old" attribute/value pair.
*/
if (args->op_flags & XFS_DA_OP_RENAME) {
/*
* In a separate transaction, set the incomplete flag on the
* "old" attr and clear the incomplete flag on the "new" attr.
*/
error = xfs_attr3_leaf_flipflags(args);
if (error)
return(error);
/*
* Dismantle the "old" attribute/value pair by removing
* a "remote" value (if it exists).
*/
args->index = args->index2;
args->blkno = args->blkno2;
args->rmtblkno = args->rmtblkno2;
args->rmtblkcnt = args->rmtblkcnt2;
if (args->rmtblkno) {
error = xfs_attr_rmtval_remove(args);
if (error)
return(error);
}
/*
* Read in the block containing the "old" attr, then
* remove the "old" attr from that block (neat, huh!)
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno,
-1, &bp);
if (error)
return error;
xfs_attr3_leaf_remove(bp, args);
/*
* If the result is small enough, shrink it all into the inode.
*/
if ((forkoff = xfs_attr_shortform_allfit(bp, dp))) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr3_leaf_to_shortform(bp, args, forkoff);
/* bp is gone due to xfs_da_shrink_inode */
if (!error) {
error = xfs_bmap_finish(&args->trans,
args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans
* and started a new one. We need the inode to be
* in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
}
/*
* Commit the remove and start the next trans in series.
*/
error = xfs_trans_roll(&args->trans, dp);
} else if (args->rmtblkno > 0) {
/*
* Added a "remote" value, just clear the incomplete flag.
*/
error = xfs_attr3_leaf_clearflag(args);
}
return error;
}
/*
* Remove a name from the leaf attribute list structure
*
* This leaf block cannot have a "remote" value, we only call this routine
* if bmap_one_block() says there is only one block (ie: no remote blks).
*/
STATIC int
xfs_attr_leaf_removename(xfs_da_args_t *args)
{
xfs_inode_t *dp;
struct xfs_buf *bp;
int error, committed, forkoff;
trace_xfs_attr_leaf_removename(args);
/*
* Remove the attribute.
*/
dp = args->dp;
args->blkno = 0;
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return error;
error = xfs_attr3_leaf_lookup_int(bp, args);
if (error == ENOATTR) {
xfs_trans_brelse(args->trans, bp);
return error;
}
xfs_attr3_leaf_remove(bp, args);
/*
* If the result is small enough, shrink it all into the inode.
*/
if ((forkoff = xfs_attr_shortform_allfit(bp, dp))) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr3_leaf_to_shortform(bp, args, forkoff);
/* bp is gone due to xfs_da_shrink_inode */
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return error;
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
}
return 0;
}
/*
* Look up a name in a leaf attribute list structure.
*
* This leaf block cannot have a "remote" value, we only call this routine
* if bmap_one_block() says there is only one block (ie: no remote blks).
*/
STATIC int
xfs_attr_leaf_get(xfs_da_args_t *args)
{
struct xfs_buf *bp;
int error;
trace_xfs_attr_leaf_get(args);
args->blkno = 0;
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return error;
error = xfs_attr3_leaf_lookup_int(bp, args);
if (error != EEXIST) {
xfs_trans_brelse(args->trans, bp);
return error;
}
error = xfs_attr3_leaf_getvalue(bp, args);
xfs_trans_brelse(args->trans, bp);
if (!error && (args->rmtblkno > 0) && !(args->flags & ATTR_KERNOVAL)) {
error = xfs_attr_rmtval_get(args);
}
return error;
}
/*========================================================================
* External routines when attribute list size > XFS_LBSIZE(mp).
*========================================================================*/
/*
* Add a name to a Btree-format attribute list.
*
* This will involve walking down the Btree, and may involve splitting
* leaf nodes and even splitting intermediate nodes up to and including
* the root node (a special case of an intermediate node).
*
* "Remote" attribute values confuse the issue and atomic rename operations
* add a whole extra layer of confusion on top of that.
*/
STATIC int
xfs_attr_node_addname(xfs_da_args_t *args)
{
xfs_da_state_t *state;
xfs_da_state_blk_t *blk;
xfs_inode_t *dp;
xfs_mount_t *mp;
int committed, retval, error;
trace_xfs_attr_node_addname(args);
/*
* Fill in bucket of arguments/results/context to carry around.
*/
dp = args->dp;
mp = dp->i_mount;
restart:
state = xfs_da_state_alloc();
state->args = args;
state->mp = mp;
state->blocksize = state->mp->m_sb.sb_blocksize;
state->node_ents = state->mp->m_attr_node_ents;
/*
* Search to see if name already exists, and get back a pointer
* to where it should go.
*/
error = xfs_da3_node_lookup_int(state, &retval);
if (error)
goto out;
blk = &state->path.blk[ state->path.active-1 ];
ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC);
if ((args->flags & ATTR_REPLACE) && (retval == ENOATTR)) {
goto out;
} else if (retval == EEXIST) {
if (args->flags & ATTR_CREATE)
goto out;
trace_xfs_attr_node_replace(args);
args->op_flags |= XFS_DA_OP_RENAME; /* atomic rename op */
args->blkno2 = args->blkno; /* set 2nd entry info*/
args->index2 = args->index;
args->rmtblkno2 = args->rmtblkno;
args->rmtblkcnt2 = args->rmtblkcnt;
args->rmtblkno = 0;
args->rmtblkcnt = 0;
}
retval = xfs_attr3_leaf_add(blk->bp, state->args);
if (retval == ENOSPC) {
if (state->path.active == 1) {
/*
* Its really a single leaf node, but it had
* out-of-line values so it looked like it *might*
* have been a b-tree.
*/
xfs_da_state_free(state);
state = NULL;
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr3_leaf_to_node(args);
if (!error) {
error = xfs_bmap_finish(&args->trans,
args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
goto out;
}
/*
* bmap_finish() may have committed the last trans
* and started a new one. We need the inode to be
* in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
/*
* Commit the node conversion and start the next
* trans in the chain.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
goto out;
goto restart;
}
/*
* Split as many Btree elements as required.
* This code tracks the new and old attr's location
* in the index/blkno/rmtblkno/rmtblkcnt fields and
* in the index2/blkno2/rmtblkno2/rmtblkcnt2 fields.
*/
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_da3_split(state);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
goto out;
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
} else {
/*
* Addition succeeded, update Btree hashvals.
*/
xfs_da3_fixhashpath(state, &state->path);
}
/*
* Kill the state structure, we're done with it and need to
* allow the buffers to come back later.
*/
xfs_da_state_free(state);
state = NULL;
/*
* Commit the leaf addition or btree split and start the next
* trans in the chain.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
goto out;
/*
* If there was an out-of-line value, allocate the blocks we
* identified for its storage and copy the value. This is done
* after we create the attribute so that we don't overflow the
* maximum size of a transaction and/or hit a deadlock.
*/
if (args->rmtblkno > 0) {
error = xfs_attr_rmtval_set(args);
if (error)
return(error);
}
/*
* If this is an atomic rename operation, we must "flip" the
* incomplete flags on the "new" and "old" attribute/value pairs
* so that one disappears and one appears atomically. Then we
* must remove the "old" attribute/value pair.
*/
if (args->op_flags & XFS_DA_OP_RENAME) {
/*
* In a separate transaction, set the incomplete flag on the
* "old" attr and clear the incomplete flag on the "new" attr.
*/
error = xfs_attr3_leaf_flipflags(args);
if (error)
goto out;
/*
* Dismantle the "old" attribute/value pair by removing
* a "remote" value (if it exists).
*/
args->index = args->index2;
args->blkno = args->blkno2;
args->rmtblkno = args->rmtblkno2;
args->rmtblkcnt = args->rmtblkcnt2;
if (args->rmtblkno) {
error = xfs_attr_rmtval_remove(args);
if (error)
return(error);
}
/*
* Re-find the "old" attribute entry after any split ops.
* The INCOMPLETE flag means that we will find the "old"
* attr, not the "new" one.
*/
args->flags |= XFS_ATTR_INCOMPLETE;
state = xfs_da_state_alloc();
state->args = args;
state->mp = mp;
state->blocksize = state->mp->m_sb.sb_blocksize;
state->node_ents = state->mp->m_attr_node_ents;
state->inleaf = 0;
error = xfs_da3_node_lookup_int(state, &retval);
if (error)
goto out;
/*
* Remove the name and update the hashvals in the tree.
*/
blk = &state->path.blk[ state->path.active-1 ];
ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC);
error = xfs_attr3_leaf_remove(blk->bp, args);
xfs_da3_fixhashpath(state, &state->path);
/*
* Check to see if the tree needs to be collapsed.
*/
if (retval && (state->path.active > 1)) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_da3_join(state);
if (!error) {
error = xfs_bmap_finish(&args->trans,
args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
goto out;
}
/*
* bmap_finish() may have committed the last trans
* and started a new one. We need the inode to be
* in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
}
/*
* Commit and start the next trans in the chain.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
goto out;
} else if (args->rmtblkno > 0) {
/*
* Added a "remote" value, just clear the incomplete flag.
*/
error = xfs_attr3_leaf_clearflag(args);
if (error)
goto out;
}
retval = error = 0;
out:
if (state)
xfs_da_state_free(state);
if (error)
return(error);
return(retval);
}
/*
* Remove a name from a B-tree attribute list.
*
* This will involve walking down the Btree, and may involve joining
* leaf nodes and even joining intermediate nodes up to and including
* the root node (a special case of an intermediate node).
*/
STATIC int
xfs_attr_node_removename(xfs_da_args_t *args)
{
xfs_da_state_t *state;
xfs_da_state_blk_t *blk;
xfs_inode_t *dp;
struct xfs_buf *bp;
int retval, error, committed, forkoff;
trace_xfs_attr_node_removename(args);
/*
* Tie a string around our finger to remind us where we are.
*/
dp = args->dp;
state = xfs_da_state_alloc();
state->args = args;
state->mp = dp->i_mount;
state->blocksize = state->mp->m_sb.sb_blocksize;
state->node_ents = state->mp->m_attr_node_ents;
/*
* Search to see if name exists, and get back a pointer to it.
*/
error = xfs_da3_node_lookup_int(state, &retval);
if (error || (retval != EEXIST)) {
if (error == 0)
error = retval;
goto out;
}
/*
* If there is an out-of-line value, de-allocate the blocks.
* This is done before we remove the attribute so that we don't
* overflow the maximum size of a transaction and/or hit a deadlock.
*/
blk = &state->path.blk[ state->path.active-1 ];
ASSERT(blk->bp != NULL);
ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC);
if (args->rmtblkno > 0) {
/*
* Fill in disk block numbers in the state structure
* so that we can get the buffers back after we commit
* several transactions in the following calls.
*/
error = xfs_attr_fillstate(state);
if (error)
goto out;
/*
* Mark the attribute as INCOMPLETE, then bunmapi() the
* remote value.
*/
error = xfs_attr3_leaf_setflag(args);
if (error)
goto out;
error = xfs_attr_rmtval_remove(args);
if (error)
goto out;
/*
* Refill the state structure with buffers, the prior calls
* released our buffers.
*/
error = xfs_attr_refillstate(state);
if (error)
goto out;
}
/*
* Remove the name and update the hashvals in the tree.
*/
blk = &state->path.blk[ state->path.active-1 ];
ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC);
retval = xfs_attr3_leaf_remove(blk->bp, args);
xfs_da3_fixhashpath(state, &state->path);
/*
* Check to see if the tree needs to be collapsed.
*/
if (retval && (state->path.active > 1)) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_da3_join(state);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
goto out;
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
/*
* Commit the Btree join operation and start a new trans.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
goto out;
}
/*
* If the result is small enough, push it all into the inode.
*/
if (xfs_bmap_one_block(dp, XFS_ATTR_FORK)) {
/*
* Have to get rid of the copy of this dabuf in the state.
*/
ASSERT(state->path.active == 1);
ASSERT(state->path.blk[0].bp);
state->path.blk[0].bp = NULL;
error = xfs_attr3_leaf_read(args->trans, args->dp, 0, -1, &bp);
if (error)
goto out;
if ((forkoff = xfs_attr_shortform_allfit(bp, dp))) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr3_leaf_to_shortform(bp, args, forkoff);
/* bp is gone due to xfs_da_shrink_inode */
if (!error) {
error = xfs_bmap_finish(&args->trans,
args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
goto out;
}
/*
* bmap_finish() may have committed the last trans
* and started a new one. We need the inode to be
* in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
} else
xfs_trans_brelse(args->trans, bp);
}
error = 0;
out:
xfs_da_state_free(state);
return(error);
}
/*
* Fill in the disk block numbers in the state structure for the buffers
* that are attached to the state structure.
* This is done so that we can quickly reattach ourselves to those buffers
* after some set of transaction commits have released these buffers.
*/
STATIC int
xfs_attr_fillstate(xfs_da_state_t *state)
{
xfs_da_state_path_t *path;
xfs_da_state_blk_t *blk;
int level;
trace_xfs_attr_fillstate(state->args);
/*
* Roll down the "path" in the state structure, storing the on-disk
* block number for those buffers in the "path".
*/
path = &state->path;
ASSERT((path->active >= 0) && (path->active < XFS_DA_NODE_MAXDEPTH));
for (blk = path->blk, level = 0; level < path->active; blk++, level++) {
if (blk->bp) {
blk->disk_blkno = XFS_BUF_ADDR(blk->bp);
blk->bp = NULL;
} else {
blk->disk_blkno = 0;
}
}
/*
* Roll down the "altpath" in the state structure, storing the on-disk
* block number for those buffers in the "altpath".
*/
path = &state->altpath;
ASSERT((path->active >= 0) && (path->active < XFS_DA_NODE_MAXDEPTH));
for (blk = path->blk, level = 0; level < path->active; blk++, level++) {
if (blk->bp) {
blk->disk_blkno = XFS_BUF_ADDR(blk->bp);
blk->bp = NULL;
} else {
blk->disk_blkno = 0;
}
}
return(0);
}
/*
* Reattach the buffers to the state structure based on the disk block
* numbers stored in the state structure.
* This is done after some set of transaction commits have released those
* buffers from our grip.
*/
STATIC int
xfs_attr_refillstate(xfs_da_state_t *state)
{
xfs_da_state_path_t *path;
xfs_da_state_blk_t *blk;
int level, error;
trace_xfs_attr_refillstate(state->args);
/*
* Roll down the "path" in the state structure, storing the on-disk
* block number for those buffers in the "path".
*/
path = &state->path;
ASSERT((path->active >= 0) && (path->active < XFS_DA_NODE_MAXDEPTH));
for (blk = path->blk, level = 0; level < path->active; blk++, level++) {
if (blk->disk_blkno) {
error = xfs_da3_node_read(state->args->trans,
state->args->dp,
blk->blkno, blk->disk_blkno,
&blk->bp, XFS_ATTR_FORK);
if (error)
return(error);
} else {
blk->bp = NULL;
}
}
/*
* Roll down the "altpath" in the state structure, storing the on-disk
* block number for those buffers in the "altpath".
*/
path = &state->altpath;
ASSERT((path->active >= 0) && (path->active < XFS_DA_NODE_MAXDEPTH));
for (blk = path->blk, level = 0; level < path->active; blk++, level++) {
if (blk->disk_blkno) {
error = xfs_da3_node_read(state->args->trans,
state->args->dp,
blk->blkno, blk->disk_blkno,
&blk->bp, XFS_ATTR_FORK);
if (error)
return(error);
} else {
blk->bp = NULL;
}
}
return(0);
}
/*
* Look up a filename in a node attribute list.
*
* This routine gets called for any attribute fork that has more than one
* block, ie: both true Btree attr lists and for single-leaf-blocks with
* "remote" values taking up more blocks.
*/
STATIC int
xfs_attr_node_get(xfs_da_args_t *args)
{
xfs_da_state_t *state;
xfs_da_state_blk_t *blk;
int error, retval;
int i;
trace_xfs_attr_node_get(args);
state = xfs_da_state_alloc();
state->args = args;
state->mp = args->dp->i_mount;
state->blocksize = state->mp->m_sb.sb_blocksize;
state->node_ents = state->mp->m_attr_node_ents;
/*
* Search to see if name exists, and get back a pointer to it.
*/
error = xfs_da3_node_lookup_int(state, &retval);
if (error) {
retval = error;
} else if (retval == EEXIST) {
blk = &state->path.blk[ state->path.active-1 ];
ASSERT(blk->bp != NULL);
ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC);
/*
* Get the value, local or "remote"
*/
retval = xfs_attr3_leaf_getvalue(blk->bp, args);
if (!retval && (args->rmtblkno > 0)
&& !(args->flags & ATTR_KERNOVAL)) {
retval = xfs_attr_rmtval_get(args);
}
}
/*
* If not in a transaction, we have to release all the buffers.
*/
for (i = 0; i < state->path.active; i++) {
xfs_trans_brelse(args->trans, state->path.blk[i].bp);
state->path.blk[i].bp = NULL;
}
xfs_da_state_free(state);
return(retval);
}
| ./CrossVul/dataset_final_sorted/CWE-19/c/bad_1453_0 |
crossvul-cpp_data_bad_1842_1 | /*
* linux/fs/ext4/super.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/backing-dev.h>
#include <linux/parser.h>
#include <linux/buffer_head.h>
#include <linux/exportfs.h>
#include <linux/vfs.h>
#include <linux/random.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/quotaops.h>
#include <linux/seq_file.h>
#include <linux/ctype.h>
#include <linux/log2.h>
#include <linux/crc16.h>
#include <linux/cleancache.h>
#include <asm/uaccess.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include "ext4.h"
#include "ext4_extents.h" /* Needed for trace points definition */
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
#include "mballoc.h"
#define CREATE_TRACE_POINTS
#include <trace/events/ext4.h>
static struct ext4_lazy_init *ext4_li_info;
static struct mutex ext4_li_mtx;
static int ext4_mballoc_ready;
static struct ratelimit_state ext4_mount_msg_ratelimit;
static int ext4_load_journal(struct super_block *, struct ext4_super_block *,
unsigned long journal_devnum);
static int ext4_show_options(struct seq_file *seq, struct dentry *root);
static int ext4_commit_super(struct super_block *sb, int sync);
static void ext4_mark_recovery_complete(struct super_block *sb,
struct ext4_super_block *es);
static void ext4_clear_journal_err(struct super_block *sb,
struct ext4_super_block *es);
static int ext4_sync_fs(struct super_block *sb, int wait);
static int ext4_remount(struct super_block *sb, int *flags, char *data);
static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf);
static int ext4_unfreeze(struct super_block *sb);
static int ext4_freeze(struct super_block *sb);
static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data);
static inline int ext2_feature_set_ok(struct super_block *sb);
static inline int ext3_feature_set_ok(struct super_block *sb);
static int ext4_feature_set_ok(struct super_block *sb, int readonly);
static void ext4_destroy_lazyinit_thread(void);
static void ext4_unregister_li_request(struct super_block *sb);
static void ext4_clear_request_list(void);
/*
* Lock ordering
*
* Note the difference between i_mmap_sem (EXT4_I(inode)->i_mmap_sem) and
* i_mmap_rwsem (inode->i_mmap_rwsem)!
*
* page fault path:
* mmap_sem -> sb_start_pagefault -> i_mmap_sem (r) -> transaction start ->
* page lock -> i_data_sem (rw)
*
* buffered write path:
* sb_start_write -> i_mutex -> mmap_sem
* sb_start_write -> i_mutex -> transaction start -> page lock ->
* i_data_sem (rw)
*
* truncate:
* sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (w) -> i_mmap_sem (w) ->
* i_mmap_rwsem (w) -> page lock
* sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (w) -> i_mmap_sem (w) ->
* transaction start -> i_data_sem (rw)
*
* direct IO:
* sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (r) -> mmap_sem
* sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (r) ->
* transaction start -> i_data_sem (rw)
*
* writepages:
* transaction start -> page lock(s) -> i_data_sem (rw)
*/
#if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
static struct file_system_type ext2_fs_type = {
.owner = THIS_MODULE,
.name = "ext2",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext2");
MODULE_ALIAS("ext2");
#define IS_EXT2_SB(sb) ((sb)->s_bdev->bd_holder == &ext2_fs_type)
#else
#define IS_EXT2_SB(sb) (0)
#endif
static struct file_system_type ext3_fs_type = {
.owner = THIS_MODULE,
.name = "ext3",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext3");
MODULE_ALIAS("ext3");
#define IS_EXT3_SB(sb) ((sb)->s_bdev->bd_holder == &ext3_fs_type)
static int ext4_verify_csum_type(struct super_block *sb,
struct ext4_super_block *es)
{
if (!ext4_has_feature_metadata_csum(sb))
return 1;
return es->s_checksum_type == EXT4_CRC32C_CHKSUM;
}
static __le32 ext4_superblock_csum(struct super_block *sb,
struct ext4_super_block *es)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int offset = offsetof(struct ext4_super_block, s_checksum);
__u32 csum;
csum = ext4_chksum(sbi, ~0, (char *)es, offset);
return cpu_to_le32(csum);
}
static int ext4_superblock_csum_verify(struct super_block *sb,
struct ext4_super_block *es)
{
if (!ext4_has_metadata_csum(sb))
return 1;
return es->s_checksum == ext4_superblock_csum(sb, es);
}
void ext4_superblock_csum_set(struct super_block *sb)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
if (!ext4_has_metadata_csum(sb))
return;
es->s_checksum = ext4_superblock_csum(sb, es);
}
void *ext4_kvmalloc(size_t size, gfp_t flags)
{
void *ret;
ret = kmalloc(size, flags | __GFP_NOWARN);
if (!ret)
ret = __vmalloc(size, flags, PAGE_KERNEL);
return ret;
}
void *ext4_kvzalloc(size_t size, gfp_t flags)
{
void *ret;
ret = kzalloc(size, flags | __GFP_NOWARN);
if (!ret)
ret = __vmalloc(size, flags | __GFP_ZERO, PAGE_KERNEL);
return ret;
}
ext4_fsblk_t ext4_block_bitmap(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_block_bitmap_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0);
}
ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_inode_bitmap_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0);
}
ext4_fsblk_t ext4_inode_table(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_inode_table_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0);
}
__u32 ext4_free_group_clusters(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_free_blocks_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0);
}
__u32 ext4_free_inodes_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_free_inodes_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_free_inodes_count_hi) << 16 : 0);
}
__u32 ext4_used_dirs_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_used_dirs_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0);
}
__u32 ext4_itable_unused_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_itable_unused_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0);
}
void ext4_block_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_block_bitmap_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32);
}
void ext4_inode_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_inode_bitmap_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32);
}
void ext4_inode_table_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_inode_table_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_inode_table_hi = cpu_to_le32(blk >> 32);
}
void ext4_free_group_clusters_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_free_blocks_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16);
}
void ext4_free_inodes_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_free_inodes_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_free_inodes_count_hi = cpu_to_le16(count >> 16);
}
void ext4_used_dirs_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_used_dirs_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16);
}
void ext4_itable_unused_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_itable_unused_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_itable_unused_hi = cpu_to_le16(count >> 16);
}
static void __save_error_info(struct super_block *sb, const char *func,
unsigned int line)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
if (bdev_read_only(sb->s_bdev))
return;
es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
es->s_last_error_time = cpu_to_le32(get_seconds());
strncpy(es->s_last_error_func, func, sizeof(es->s_last_error_func));
es->s_last_error_line = cpu_to_le32(line);
if (!es->s_first_error_time) {
es->s_first_error_time = es->s_last_error_time;
strncpy(es->s_first_error_func, func,
sizeof(es->s_first_error_func));
es->s_first_error_line = cpu_to_le32(line);
es->s_first_error_ino = es->s_last_error_ino;
es->s_first_error_block = es->s_last_error_block;
}
/*
* Start the daily error reporting function if it hasn't been
* started already
*/
if (!es->s_error_count)
mod_timer(&EXT4_SB(sb)->s_err_report, jiffies + 24*60*60*HZ);
le32_add_cpu(&es->s_error_count, 1);
}
static void save_error_info(struct super_block *sb, const char *func,
unsigned int line)
{
__save_error_info(sb, func, line);
ext4_commit_super(sb, 1);
}
/*
* The del_gendisk() function uninitializes the disk-specific data
* structures, including the bdi structure, without telling anyone
* else. Once this happens, any attempt to call mark_buffer_dirty()
* (for example, by ext4_commit_super), will cause a kernel OOPS.
* This is a kludge to prevent these oops until we can put in a proper
* hook in del_gendisk() to inform the VFS and file system layers.
*/
static int block_device_ejected(struct super_block *sb)
{
struct inode *bd_inode = sb->s_bdev->bd_inode;
struct backing_dev_info *bdi = inode_to_bdi(bd_inode);
return bdi->dev == NULL;
}
static void ext4_journal_commit_callback(journal_t *journal, transaction_t *txn)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
int error = is_journal_aborted(journal);
struct ext4_journal_cb_entry *jce;
BUG_ON(txn->t_state == T_FINISHED);
spin_lock(&sbi->s_md_lock);
while (!list_empty(&txn->t_private_list)) {
jce = list_entry(txn->t_private_list.next,
struct ext4_journal_cb_entry, jce_list);
list_del_init(&jce->jce_list);
spin_unlock(&sbi->s_md_lock);
jce->jce_func(sb, jce, error);
spin_lock(&sbi->s_md_lock);
}
spin_unlock(&sbi->s_md_lock);
}
/* Deal with the reporting of failure conditions on a filesystem such as
* inconsistencies detected or read IO failures.
*
* On ext2, we can store the error state of the filesystem in the
* superblock. That is not possible on ext4, because we may have other
* write ordering constraints on the superblock which prevent us from
* writing it out straight away; and given that the journal is about to
* be aborted, we can't rely on the current, or future, transactions to
* write out the superblock safely.
*
* We'll just use the jbd2_journal_abort() error code to record an error in
* the journal instead. On recovery, the journal will complain about
* that error until we've noted it down and cleared it.
*/
static void ext4_handle_error(struct super_block *sb)
{
if (sb->s_flags & MS_RDONLY)
return;
if (!test_opt(sb, ERRORS_CONT)) {
journal_t *journal = EXT4_SB(sb)->s_journal;
EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
if (journal)
jbd2_journal_abort(journal, -EIO);
}
if (test_opt(sb, ERRORS_RO)) {
ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
/*
* Make sure updated value of ->s_mount_flags will be visible
* before ->s_flags update
*/
smp_wmb();
sb->s_flags |= MS_RDONLY;
}
if (test_opt(sb, ERRORS_PANIC)) {
if (EXT4_SB(sb)->s_journal &&
!(EXT4_SB(sb)->s_journal->j_flags & JBD2_REC_ERR))
return;
panic("EXT4-fs (device %s): panic forced after error\n",
sb->s_id);
}
}
#define ext4_error_ratelimit(sb) \
___ratelimit(&(EXT4_SB(sb)->s_err_ratelimit_state), \
"EXT4-fs error")
void __ext4_error(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (ext4_error_ratelimit(sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: comm %s: %pV\n",
sb->s_id, function, line, current->comm, &vaf);
va_end(args);
}
save_error_info(sb, function, line);
ext4_handle_error(sb);
}
void __ext4_error_inode(struct inode *inode, const char *function,
unsigned int line, ext4_fsblk_t block,
const char *fmt, ...)
{
va_list args;
struct va_format vaf;
struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
es->s_last_error_ino = cpu_to_le32(inode->i_ino);
es->s_last_error_block = cpu_to_le64(block);
if (ext4_error_ratelimit(inode->i_sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (block)
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
"inode #%lu: block %llu: comm %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
block, current->comm, &vaf);
else
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
"inode #%lu: comm %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
current->comm, &vaf);
va_end(args);
}
save_error_info(inode->i_sb, function, line);
ext4_handle_error(inode->i_sb);
}
void __ext4_error_file(struct file *file, const char *function,
unsigned int line, ext4_fsblk_t block,
const char *fmt, ...)
{
va_list args;
struct va_format vaf;
struct ext4_super_block *es;
struct inode *inode = file_inode(file);
char pathname[80], *path;
es = EXT4_SB(inode->i_sb)->s_es;
es->s_last_error_ino = cpu_to_le32(inode->i_ino);
if (ext4_error_ratelimit(inode->i_sb)) {
path = file_path(file, pathname, sizeof(pathname));
if (IS_ERR(path))
path = "(unknown)";
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (block)
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: inode #%lu: "
"block %llu: comm %s: path %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
block, current->comm, path, &vaf);
else
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: inode #%lu: "
"comm %s: path %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
current->comm, path, &vaf);
va_end(args);
}
save_error_info(inode->i_sb, function, line);
ext4_handle_error(inode->i_sb);
}
const char *ext4_decode_error(struct super_block *sb, int errno,
char nbuf[16])
{
char *errstr = NULL;
switch (errno) {
case -EFSCORRUPTED:
errstr = "Corrupt filesystem";
break;
case -EFSBADCRC:
errstr = "Filesystem failed CRC";
break;
case -EIO:
errstr = "IO failure";
break;
case -ENOMEM:
errstr = "Out of memory";
break;
case -EROFS:
if (!sb || (EXT4_SB(sb)->s_journal &&
EXT4_SB(sb)->s_journal->j_flags & JBD2_ABORT))
errstr = "Journal has aborted";
else
errstr = "Readonly filesystem";
break;
default:
/* If the caller passed in an extra buffer for unknown
* errors, textualise them now. Else we just return
* NULL. */
if (nbuf) {
/* Check for truncated error codes... */
if (snprintf(nbuf, 16, "error %d", -errno) >= 0)
errstr = nbuf;
}
break;
}
return errstr;
}
/* __ext4_std_error decodes expected errors from journaling functions
* automatically and invokes the appropriate error response. */
void __ext4_std_error(struct super_block *sb, const char *function,
unsigned int line, int errno)
{
char nbuf[16];
const char *errstr;
/* Special case: if the error is EROFS, and we're not already
* inside a transaction, then there's really no point in logging
* an error. */
if (errno == -EROFS && journal_current_handle() == NULL &&
(sb->s_flags & MS_RDONLY))
return;
if (ext4_error_ratelimit(sb)) {
errstr = ext4_decode_error(sb, errno, nbuf);
printk(KERN_CRIT "EXT4-fs error (device %s) in %s:%d: %s\n",
sb->s_id, function, line, errstr);
}
save_error_info(sb, function, line);
ext4_handle_error(sb);
}
/*
* ext4_abort is a much stronger failure handler than ext4_error. The
* abort function may be used to deal with unrecoverable failures such
* as journal IO errors or ENOMEM at a critical moment in log management.
*
* We unconditionally force the filesystem into an ABORT|READONLY state,
* unless the error response on the fs has been set to panic in which
* case we take the easy way out and panic immediately.
*/
void __ext4_abort(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
va_list args;
save_error_info(sb, function, line);
va_start(args, fmt);
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: ", sb->s_id,
function, line);
vprintk(fmt, args);
printk("\n");
va_end(args);
if ((sb->s_flags & MS_RDONLY) == 0) {
ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
/*
* Make sure updated value of ->s_mount_flags will be visible
* before ->s_flags update
*/
smp_wmb();
sb->s_flags |= MS_RDONLY;
if (EXT4_SB(sb)->s_journal)
jbd2_journal_abort(EXT4_SB(sb)->s_journal, -EIO);
save_error_info(sb, function, line);
}
if (test_opt(sb, ERRORS_PANIC)) {
if (EXT4_SB(sb)->s_journal &&
!(EXT4_SB(sb)->s_journal->j_flags & JBD2_REC_ERR))
return;
panic("EXT4-fs panic from previous error\n");
}
}
void __ext4_msg(struct super_block *sb,
const char *prefix, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (!___ratelimit(&(EXT4_SB(sb)->s_msg_ratelimit_state), "EXT4-fs"))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk("%sEXT4-fs (%s): %pV\n", prefix, sb->s_id, &vaf);
va_end(args);
}
#define ext4_warning_ratelimit(sb) \
___ratelimit(&(EXT4_SB(sb)->s_warning_ratelimit_state), \
"EXT4-fs warning")
void __ext4_warning(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (!ext4_warning_ratelimit(sb))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: %pV\n",
sb->s_id, function, line, &vaf);
va_end(args);
}
void __ext4_warning_inode(const struct inode *inode, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (!ext4_warning_ratelimit(inode->i_sb))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: "
"inode #%lu: comm %s: %pV\n", inode->i_sb->s_id,
function, line, inode->i_ino, current->comm, &vaf);
va_end(args);
}
void __ext4_grp_locked_error(const char *function, unsigned int line,
struct super_block *sb, ext4_group_t grp,
unsigned long ino, ext4_fsblk_t block,
const char *fmt, ...)
__releases(bitlock)
__acquires(bitlock)
{
struct va_format vaf;
va_list args;
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
es->s_last_error_ino = cpu_to_le32(ino);
es->s_last_error_block = cpu_to_le64(block);
__save_error_info(sb, function, line);
if (ext4_error_ratelimit(sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: group %u, ",
sb->s_id, function, line, grp);
if (ino)
printk(KERN_CONT "inode %lu: ", ino);
if (block)
printk(KERN_CONT "block %llu:",
(unsigned long long) block);
printk(KERN_CONT "%pV\n", &vaf);
va_end(args);
}
if (test_opt(sb, ERRORS_CONT)) {
ext4_commit_super(sb, 0);
return;
}
ext4_unlock_group(sb, grp);
ext4_handle_error(sb);
/*
* We only get here in the ERRORS_RO case; relocking the group
* may be dangerous, but nothing bad will happen since the
* filesystem will have already been marked read/only and the
* journal has been aborted. We return 1 as a hint to callers
* who might what to use the return value from
* ext4_grp_locked_error() to distinguish between the
* ERRORS_CONT and ERRORS_RO case, and perhaps return more
* aggressively from the ext4 function in question, with a
* more appropriate error code.
*/
ext4_lock_group(sb, grp);
return;
}
void ext4_update_dynamic_rev(struct super_block *sb)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
if (le32_to_cpu(es->s_rev_level) > EXT4_GOOD_OLD_REV)
return;
ext4_warning(sb,
"updating to rev %d because of new feature flag, "
"running e2fsck is recommended",
EXT4_DYNAMIC_REV);
es->s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO);
es->s_inode_size = cpu_to_le16(EXT4_GOOD_OLD_INODE_SIZE);
es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV);
/* leave es->s_feature_*compat flags alone */
/* es->s_uuid will be set by e2fsck if empty */
/*
* The rest of the superblock fields should be zero, and if not it
* means they are likely already in use, so leave them alone. We
* can leave it up to e2fsck to clean up any inconsistencies there.
*/
}
/*
* Open the external journal device
*/
static struct block_device *ext4_blkdev_get(dev_t dev, struct super_block *sb)
{
struct block_device *bdev;
char b[BDEVNAME_SIZE];
bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb);
if (IS_ERR(bdev))
goto fail;
return bdev;
fail:
ext4_msg(sb, KERN_ERR, "failed to open journal device %s: %ld",
__bdevname(dev, b), PTR_ERR(bdev));
return NULL;
}
/*
* Release the journal device
*/
static void ext4_blkdev_put(struct block_device *bdev)
{
blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
}
static void ext4_blkdev_remove(struct ext4_sb_info *sbi)
{
struct block_device *bdev;
bdev = sbi->journal_bdev;
if (bdev) {
ext4_blkdev_put(bdev);
sbi->journal_bdev = NULL;
}
}
static inline struct inode *orphan_list_entry(struct list_head *l)
{
return &list_entry(l, struct ext4_inode_info, i_orphan)->vfs_inode;
}
static void dump_orphan_list(struct super_block *sb, struct ext4_sb_info *sbi)
{
struct list_head *l;
ext4_msg(sb, KERN_ERR, "sb orphan head is %d",
le32_to_cpu(sbi->s_es->s_last_orphan));
printk(KERN_ERR "sb_info orphan list:\n");
list_for_each(l, &sbi->s_orphan) {
struct inode *inode = orphan_list_entry(l);
printk(KERN_ERR " "
"inode %s:%lu at %p: mode %o, nlink %d, next %d\n",
inode->i_sb->s_id, inode->i_ino, inode,
inode->i_mode, inode->i_nlink,
NEXT_ORPHAN(inode));
}
}
static void ext4_put_super(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int i, err;
ext4_unregister_li_request(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
flush_workqueue(sbi->rsv_conversion_wq);
destroy_workqueue(sbi->rsv_conversion_wq);
if (sbi->s_journal) {
err = jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
if (err < 0)
ext4_abort(sb, "Couldn't clean up the journal");
}
ext4_unregister_sysfs(sb);
ext4_es_unregister_shrinker(sbi);
del_timer_sync(&sbi->s_err_report);
ext4_release_system_zone(sb);
ext4_mb_release(sb);
ext4_ext_release(sb);
ext4_xattr_put_super(sb);
if (!(sb->s_flags & MS_RDONLY)) {
ext4_clear_feature_journal_needs_recovery(sb);
es->s_state = cpu_to_le16(sbi->s_mount_state);
}
if (!(sb->s_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
for (i = 0; i < sbi->s_gdb_count; i++)
brelse(sbi->s_group_desc[i]);
kvfree(sbi->s_group_desc);
kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
brelse(sbi->s_sbh);
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
/* Debugging code just in case the in-memory inode orphan list
* isn't empty. The on-disk one can be non-empty if we've
* detected an error and taken the fs readonly, but the
* in-memory list had better be clean by this point. */
if (!list_empty(&sbi->s_orphan))
dump_orphan_list(sb, sbi);
J_ASSERT(list_empty(&sbi->s_orphan));
sync_blockdev(sb->s_bdev);
invalidate_bdev(sb->s_bdev);
if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) {
/*
* Invalidate the journal device's buffers. We don't want them
* floating about in memory - the physical journal device may
* hotswapped, and it breaks the `ro-after' testing code.
*/
sync_blockdev(sbi->journal_bdev);
invalidate_bdev(sbi->journal_bdev);
ext4_blkdev_remove(sbi);
}
if (sbi->s_mb_cache) {
ext4_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
sb->s_fs_info = NULL;
/*
* Now that we are completely done shutting down the
* superblock, we need to actually destroy the kobject.
*/
kobject_put(&sbi->s_kobj);
wait_for_completion(&sbi->s_kobj_unregister);
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
static struct kmem_cache *ext4_inode_cachep;
/*
* Called inside transaction, so use GFP_NOFS
*/
static struct inode *ext4_alloc_inode(struct super_block *sb)
{
struct ext4_inode_info *ei;
ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS);
if (!ei)
return NULL;
ei->vfs_inode.i_version = 1;
spin_lock_init(&ei->i_raw_lock);
INIT_LIST_HEAD(&ei->i_prealloc_list);
spin_lock_init(&ei->i_prealloc_lock);
ext4_es_init_tree(&ei->i_es_tree);
rwlock_init(&ei->i_es_lock);
INIT_LIST_HEAD(&ei->i_es_list);
ei->i_es_all_nr = 0;
ei->i_es_shk_nr = 0;
ei->i_es_shrink_lblk = 0;
ei->i_reserved_data_blocks = 0;
ei->i_reserved_meta_blocks = 0;
ei->i_allocated_meta_blocks = 0;
ei->i_da_metadata_calc_len = 0;
ei->i_da_metadata_calc_last_lblock = 0;
spin_lock_init(&(ei->i_block_reservation_lock));
#ifdef CONFIG_QUOTA
ei->i_reserved_quota = 0;
memset(&ei->i_dquot, 0, sizeof(ei->i_dquot));
#endif
ei->jinode = NULL;
INIT_LIST_HEAD(&ei->i_rsv_conversion_list);
spin_lock_init(&ei->i_completed_io_lock);
ei->i_sync_tid = 0;
ei->i_datasync_tid = 0;
atomic_set(&ei->i_ioend_count, 0);
atomic_set(&ei->i_unwritten, 0);
INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work);
#ifdef CONFIG_EXT4_FS_ENCRYPTION
ei->i_crypt_info = NULL;
#endif
return &ei->vfs_inode;
}
static int ext4_drop_inode(struct inode *inode)
{
int drop = generic_drop_inode(inode);
trace_ext4_drop_inode(inode, drop);
return drop;
}
static void ext4_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(ext4_inode_cachep, EXT4_I(inode));
}
static void ext4_destroy_inode(struct inode *inode)
{
if (!list_empty(&(EXT4_I(inode)->i_orphan))) {
ext4_msg(inode->i_sb, KERN_ERR,
"Inode %lu (%p): orphan list check failed!",
inode->i_ino, EXT4_I(inode));
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 4,
EXT4_I(inode), sizeof(struct ext4_inode_info),
true);
dump_stack();
}
call_rcu(&inode->i_rcu, ext4_i_callback);
}
static void init_once(void *foo)
{
struct ext4_inode_info *ei = (struct ext4_inode_info *) foo;
INIT_LIST_HEAD(&ei->i_orphan);
init_rwsem(&ei->xattr_sem);
init_rwsem(&ei->i_data_sem);
init_rwsem(&ei->i_mmap_sem);
inode_init_once(&ei->vfs_inode);
}
static int __init init_inodecache(void)
{
ext4_inode_cachep = kmem_cache_create("ext4_inode_cache",
sizeof(struct ext4_inode_info),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD|SLAB_ACCOUNT),
init_once);
if (ext4_inode_cachep == NULL)
return -ENOMEM;
return 0;
}
static void destroy_inodecache(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
kmem_cache_destroy(ext4_inode_cachep);
}
void ext4_clear_inode(struct inode *inode)
{
invalidate_inode_buffers(inode);
clear_inode(inode);
dquot_drop(inode);
ext4_discard_preallocations(inode);
ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS);
if (EXT4_I(inode)->jinode) {
jbd2_journal_release_jbd_inode(EXT4_JOURNAL(inode),
EXT4_I(inode)->jinode);
jbd2_free_inode(EXT4_I(inode)->jinode);
EXT4_I(inode)->jinode = NULL;
}
#ifdef CONFIG_EXT4_FS_ENCRYPTION
if (EXT4_I(inode)->i_crypt_info)
ext4_free_encryption_info(inode, EXT4_I(inode)->i_crypt_info);
#endif
}
static struct inode *ext4_nfs_get_inode(struct super_block *sb,
u64 ino, u32 generation)
{
struct inode *inode;
if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
return ERR_PTR(-ESTALE);
if (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
return ERR_PTR(-ESTALE);
/* iget isn't really right if the inode is currently unallocated!!
*
* ext4_read_inode will return a bad_inode if the inode had been
* deleted, so we should be safe.
*
* Currently we don't know the generation for parent directory, so
* a generation of 0 means "accept any"
*/
inode = ext4_iget_normal(sb, ino);
if (IS_ERR(inode))
return ERR_CAST(inode);
if (generation && inode->i_generation != generation) {
iput(inode);
return ERR_PTR(-ESTALE);
}
return inode;
}
static struct dentry *ext4_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
ext4_nfs_get_inode);
}
static struct dentry *ext4_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_parent(sb, fid, fh_len, fh_type,
ext4_nfs_get_inode);
}
/*
* Try to release metadata pages (indirect blocks, directories) which are
* mapped via the block device. Since these pages could have journal heads
* which would prevent try_to_free_buffers() from freeing them, we must use
* jbd2 layer's try_to_free_buffers() function to release them.
*/
static int bdev_try_to_free_page(struct super_block *sb, struct page *page,
gfp_t wait)
{
journal_t *journal = EXT4_SB(sb)->s_journal;
WARN_ON(PageChecked(page));
if (!page_has_buffers(page))
return 0;
if (journal)
return jbd2_journal_try_to_free_buffers(journal, page,
wait & ~__GFP_DIRECT_RECLAIM);
return try_to_free_buffers(page);
}
#ifdef CONFIG_QUOTA
static char *quotatypes[] = INITQFNAMES;
#define QTYPE2NAME(t) (quotatypes[t])
static int ext4_write_dquot(struct dquot *dquot);
static int ext4_acquire_dquot(struct dquot *dquot);
static int ext4_release_dquot(struct dquot *dquot);
static int ext4_mark_dquot_dirty(struct dquot *dquot);
static int ext4_write_info(struct super_block *sb, int type);
static int ext4_quota_on(struct super_block *sb, int type, int format_id,
struct path *path);
static int ext4_quota_off(struct super_block *sb, int type);
static int ext4_quota_on_mount(struct super_block *sb, int type);
static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off);
static ssize_t ext4_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off);
static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
unsigned int flags);
static int ext4_enable_quotas(struct super_block *sb);
static struct dquot **ext4_get_dquots(struct inode *inode)
{
return EXT4_I(inode)->i_dquot;
}
static const struct dquot_operations ext4_quota_operations = {
.get_reserved_space = ext4_get_reserved_space,
.write_dquot = ext4_write_dquot,
.acquire_dquot = ext4_acquire_dquot,
.release_dquot = ext4_release_dquot,
.mark_dirty = ext4_mark_dquot_dirty,
.write_info = ext4_write_info,
.alloc_dquot = dquot_alloc,
.destroy_dquot = dquot_destroy,
.get_projid = ext4_get_projid,
};
static const struct quotactl_ops ext4_qctl_operations = {
.quota_on = ext4_quota_on,
.quota_off = ext4_quota_off,
.quota_sync = dquot_quota_sync,
.get_state = dquot_get_state,
.set_info = dquot_set_dqinfo,
.get_dqblk = dquot_get_dqblk,
.set_dqblk = dquot_set_dqblk
};
#endif
static const struct super_operations ext4_sops = {
.alloc_inode = ext4_alloc_inode,
.destroy_inode = ext4_destroy_inode,
.write_inode = ext4_write_inode,
.dirty_inode = ext4_dirty_inode,
.drop_inode = ext4_drop_inode,
.evict_inode = ext4_evict_inode,
.put_super = ext4_put_super,
.sync_fs = ext4_sync_fs,
.freeze_fs = ext4_freeze,
.unfreeze_fs = ext4_unfreeze,
.statfs = ext4_statfs,
.remount_fs = ext4_remount,
.show_options = ext4_show_options,
#ifdef CONFIG_QUOTA
.quota_read = ext4_quota_read,
.quota_write = ext4_quota_write,
.get_dquots = ext4_get_dquots,
#endif
.bdev_try_to_free_page = bdev_try_to_free_page,
};
static const struct export_operations ext4_export_ops = {
.fh_to_dentry = ext4_fh_to_dentry,
.fh_to_parent = ext4_fh_to_parent,
.get_parent = ext4_get_parent,
};
enum {
Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid,
Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic, Opt_err_ro,
Opt_nouid32, Opt_debug, Opt_removed,
Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl,
Opt_auto_da_alloc, Opt_noauto_da_alloc, Opt_noload,
Opt_commit, Opt_min_batch_time, Opt_max_batch_time, Opt_journal_dev,
Opt_journal_path, Opt_journal_checksum, Opt_journal_async_commit,
Opt_abort, Opt_data_journal, Opt_data_ordered, Opt_data_writeback,
Opt_data_err_abort, Opt_data_err_ignore, Opt_test_dummy_encryption,
Opt_usrjquota, Opt_grpjquota, Opt_offusrjquota, Opt_offgrpjquota,
Opt_jqfmt_vfsold, Opt_jqfmt_vfsv0, Opt_jqfmt_vfsv1, Opt_quota,
Opt_noquota, Opt_barrier, Opt_nobarrier, Opt_err,
Opt_usrquota, Opt_grpquota, Opt_i_version, Opt_dax,
Opt_stripe, Opt_delalloc, Opt_nodelalloc, Opt_mblk_io_submit,
Opt_lazytime, Opt_nolazytime,
Opt_nomblk_io_submit, Opt_block_validity, Opt_noblock_validity,
Opt_inode_readahead_blks, Opt_journal_ioprio,
Opt_dioread_nolock, Opt_dioread_lock,
Opt_discard, Opt_nodiscard, Opt_init_itable, Opt_noinit_itable,
Opt_max_dir_size_kb, Opt_nojournal_checksum,
};
static const match_table_t tokens = {
{Opt_bsd_df, "bsddf"},
{Opt_minix_df, "minixdf"},
{Opt_grpid, "grpid"},
{Opt_grpid, "bsdgroups"},
{Opt_nogrpid, "nogrpid"},
{Opt_nogrpid, "sysvgroups"},
{Opt_resgid, "resgid=%u"},
{Opt_resuid, "resuid=%u"},
{Opt_sb, "sb=%u"},
{Opt_err_cont, "errors=continue"},
{Opt_err_panic, "errors=panic"},
{Opt_err_ro, "errors=remount-ro"},
{Opt_nouid32, "nouid32"},
{Opt_debug, "debug"},
{Opt_removed, "oldalloc"},
{Opt_removed, "orlov"},
{Opt_user_xattr, "user_xattr"},
{Opt_nouser_xattr, "nouser_xattr"},
{Opt_acl, "acl"},
{Opt_noacl, "noacl"},
{Opt_noload, "norecovery"},
{Opt_noload, "noload"},
{Opt_removed, "nobh"},
{Opt_removed, "bh"},
{Opt_commit, "commit=%u"},
{Opt_min_batch_time, "min_batch_time=%u"},
{Opt_max_batch_time, "max_batch_time=%u"},
{Opt_journal_dev, "journal_dev=%u"},
{Opt_journal_path, "journal_path=%s"},
{Opt_journal_checksum, "journal_checksum"},
{Opt_nojournal_checksum, "nojournal_checksum"},
{Opt_journal_async_commit, "journal_async_commit"},
{Opt_abort, "abort"},
{Opt_data_journal, "data=journal"},
{Opt_data_ordered, "data=ordered"},
{Opt_data_writeback, "data=writeback"},
{Opt_data_err_abort, "data_err=abort"},
{Opt_data_err_ignore, "data_err=ignore"},
{Opt_offusrjquota, "usrjquota="},
{Opt_usrjquota, "usrjquota=%s"},
{Opt_offgrpjquota, "grpjquota="},
{Opt_grpjquota, "grpjquota=%s"},
{Opt_jqfmt_vfsold, "jqfmt=vfsold"},
{Opt_jqfmt_vfsv0, "jqfmt=vfsv0"},
{Opt_jqfmt_vfsv1, "jqfmt=vfsv1"},
{Opt_grpquota, "grpquota"},
{Opt_noquota, "noquota"},
{Opt_quota, "quota"},
{Opt_usrquota, "usrquota"},
{Opt_barrier, "barrier=%u"},
{Opt_barrier, "barrier"},
{Opt_nobarrier, "nobarrier"},
{Opt_i_version, "i_version"},
{Opt_dax, "dax"},
{Opt_stripe, "stripe=%u"},
{Opt_delalloc, "delalloc"},
{Opt_lazytime, "lazytime"},
{Opt_nolazytime, "nolazytime"},
{Opt_nodelalloc, "nodelalloc"},
{Opt_removed, "mblk_io_submit"},
{Opt_removed, "nomblk_io_submit"},
{Opt_block_validity, "block_validity"},
{Opt_noblock_validity, "noblock_validity"},
{Opt_inode_readahead_blks, "inode_readahead_blks=%u"},
{Opt_journal_ioprio, "journal_ioprio=%u"},
{Opt_auto_da_alloc, "auto_da_alloc=%u"},
{Opt_auto_da_alloc, "auto_da_alloc"},
{Opt_noauto_da_alloc, "noauto_da_alloc"},
{Opt_dioread_nolock, "dioread_nolock"},
{Opt_dioread_lock, "dioread_lock"},
{Opt_discard, "discard"},
{Opt_nodiscard, "nodiscard"},
{Opt_init_itable, "init_itable=%u"},
{Opt_init_itable, "init_itable"},
{Opt_noinit_itable, "noinit_itable"},
{Opt_max_dir_size_kb, "max_dir_size_kb=%u"},
{Opt_test_dummy_encryption, "test_dummy_encryption"},
{Opt_removed, "check=none"}, /* mount option from ext2/3 */
{Opt_removed, "nocheck"}, /* mount option from ext2/3 */
{Opt_removed, "reservation"}, /* mount option from ext2/3 */
{Opt_removed, "noreservation"}, /* mount option from ext2/3 */
{Opt_removed, "journal=%u"}, /* mount option from ext2/3 */
{Opt_err, NULL},
};
static ext4_fsblk_t get_sb_block(void **data)
{
ext4_fsblk_t sb_block;
char *options = (char *) *data;
if (!options || strncmp(options, "sb=", 3) != 0)
return 1; /* Default location */
options += 3;
/* TODO: use simple_strtoll with >32bit ext4 */
sb_block = simple_strtoul(options, &options, 0);
if (*options && *options != ',') {
printk(KERN_ERR "EXT4-fs: Invalid sb specification: %s\n",
(char *) *data);
return 1;
}
if (*options == ',')
options++;
*data = (void *) options;
return sb_block;
}
#define DEFAULT_JOURNAL_IOPRIO (IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 3))
static char deprecated_msg[] = "Mount option \"%s\" will be removed by %s\n"
"Contact linux-ext4@vger.kernel.org if you think we should keep it.\n";
#ifdef CONFIG_QUOTA
static int set_qf_name(struct super_block *sb, int qtype, substring_t *args)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
char *qname;
int ret = -1;
if (sb_any_quota_loaded(sb) &&
!sbi->s_qf_names[qtype]) {
ext4_msg(sb, KERN_ERR,
"Cannot change journaled "
"quota options when quota turned on");
return -1;
}
if (ext4_has_feature_quota(sb)) {
ext4_msg(sb, KERN_ERR, "Cannot set journaled quota options "
"when QUOTA feature is enabled");
return -1;
}
qname = match_strdup(args);
if (!qname) {
ext4_msg(sb, KERN_ERR,
"Not enough memory for storing quotafile name");
return -1;
}
if (sbi->s_qf_names[qtype]) {
if (strcmp(sbi->s_qf_names[qtype], qname) == 0)
ret = 1;
else
ext4_msg(sb, KERN_ERR,
"%s quota file already specified",
QTYPE2NAME(qtype));
goto errout;
}
if (strchr(qname, '/')) {
ext4_msg(sb, KERN_ERR,
"quotafile must be on filesystem root");
goto errout;
}
sbi->s_qf_names[qtype] = qname;
set_opt(sb, QUOTA);
return 1;
errout:
kfree(qname);
return ret;
}
static int clear_qf_name(struct super_block *sb, int qtype)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (sb_any_quota_loaded(sb) &&
sbi->s_qf_names[qtype]) {
ext4_msg(sb, KERN_ERR, "Cannot change journaled quota options"
" when quota turned on");
return -1;
}
kfree(sbi->s_qf_names[qtype]);
sbi->s_qf_names[qtype] = NULL;
return 1;
}
#endif
#define MOPT_SET 0x0001
#define MOPT_CLEAR 0x0002
#define MOPT_NOSUPPORT 0x0004
#define MOPT_EXPLICIT 0x0008
#define MOPT_CLEAR_ERR 0x0010
#define MOPT_GTE0 0x0020
#ifdef CONFIG_QUOTA
#define MOPT_Q 0
#define MOPT_QFMT 0x0040
#else
#define MOPT_Q MOPT_NOSUPPORT
#define MOPT_QFMT MOPT_NOSUPPORT
#endif
#define MOPT_DATAJ 0x0080
#define MOPT_NO_EXT2 0x0100
#define MOPT_NO_EXT3 0x0200
#define MOPT_EXT4_ONLY (MOPT_NO_EXT2 | MOPT_NO_EXT3)
#define MOPT_STRING 0x0400
static const struct mount_opts {
int token;
int mount_opt;
int flags;
} ext4_mount_opts[] = {
{Opt_minix_df, EXT4_MOUNT_MINIX_DF, MOPT_SET},
{Opt_bsd_df, EXT4_MOUNT_MINIX_DF, MOPT_CLEAR},
{Opt_grpid, EXT4_MOUNT_GRPID, MOPT_SET},
{Opt_nogrpid, EXT4_MOUNT_GRPID, MOPT_CLEAR},
{Opt_block_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_SET},
{Opt_noblock_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_CLEAR},
{Opt_dioread_nolock, EXT4_MOUNT_DIOREAD_NOLOCK,
MOPT_EXT4_ONLY | MOPT_SET},
{Opt_dioread_lock, EXT4_MOUNT_DIOREAD_NOLOCK,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_discard, EXT4_MOUNT_DISCARD, MOPT_SET},
{Opt_nodiscard, EXT4_MOUNT_DISCARD, MOPT_CLEAR},
{Opt_delalloc, EXT4_MOUNT_DELALLOC,
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_nodelalloc, EXT4_MOUNT_DELALLOC,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_nojournal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_journal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_journal_async_commit, (EXT4_MOUNT_JOURNAL_ASYNC_COMMIT |
EXT4_MOUNT_JOURNAL_CHECKSUM),
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_noload, EXT4_MOUNT_NOLOAD, MOPT_NO_EXT2 | MOPT_SET},
{Opt_err_panic, EXT4_MOUNT_ERRORS_PANIC, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_err_ro, EXT4_MOUNT_ERRORS_RO, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_err_cont, EXT4_MOUNT_ERRORS_CONT, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_data_err_abort, EXT4_MOUNT_DATA_ERR_ABORT,
MOPT_NO_EXT2 | MOPT_SET},
{Opt_data_err_ignore, EXT4_MOUNT_DATA_ERR_ABORT,
MOPT_NO_EXT2 | MOPT_CLEAR},
{Opt_barrier, EXT4_MOUNT_BARRIER, MOPT_SET},
{Opt_nobarrier, EXT4_MOUNT_BARRIER, MOPT_CLEAR},
{Opt_noauto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_SET},
{Opt_auto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_CLEAR},
{Opt_noinit_itable, EXT4_MOUNT_INIT_INODE_TABLE, MOPT_CLEAR},
{Opt_commit, 0, MOPT_GTE0},
{Opt_max_batch_time, 0, MOPT_GTE0},
{Opt_min_batch_time, 0, MOPT_GTE0},
{Opt_inode_readahead_blks, 0, MOPT_GTE0},
{Opt_init_itable, 0, MOPT_GTE0},
{Opt_dax, EXT4_MOUNT_DAX, MOPT_SET},
{Opt_stripe, 0, MOPT_GTE0},
{Opt_resuid, 0, MOPT_GTE0},
{Opt_resgid, 0, MOPT_GTE0},
{Opt_journal_dev, 0, MOPT_NO_EXT2 | MOPT_GTE0},
{Opt_journal_path, 0, MOPT_NO_EXT2 | MOPT_STRING},
{Opt_journal_ioprio, 0, MOPT_NO_EXT2 | MOPT_GTE0},
{Opt_data_journal, EXT4_MOUNT_JOURNAL_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_data_ordered, EXT4_MOUNT_ORDERED_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_data_writeback, EXT4_MOUNT_WRITEBACK_DATA,
MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_user_xattr, EXT4_MOUNT_XATTR_USER, MOPT_SET},
{Opt_nouser_xattr, EXT4_MOUNT_XATTR_USER, MOPT_CLEAR},
#ifdef CONFIG_EXT4_FS_POSIX_ACL
{Opt_acl, EXT4_MOUNT_POSIX_ACL, MOPT_SET},
{Opt_noacl, EXT4_MOUNT_POSIX_ACL, MOPT_CLEAR},
#else
{Opt_acl, 0, MOPT_NOSUPPORT},
{Opt_noacl, 0, MOPT_NOSUPPORT},
#endif
{Opt_nouid32, EXT4_MOUNT_NO_UID32, MOPT_SET},
{Opt_debug, EXT4_MOUNT_DEBUG, MOPT_SET},
{Opt_quota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA, MOPT_SET | MOPT_Q},
{Opt_usrquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA,
MOPT_SET | MOPT_Q},
{Opt_grpquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_GRPQUOTA,
MOPT_SET | MOPT_Q},
{Opt_noquota, (EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA |
EXT4_MOUNT_GRPQUOTA), MOPT_CLEAR | MOPT_Q},
{Opt_usrjquota, 0, MOPT_Q},
{Opt_grpjquota, 0, MOPT_Q},
{Opt_offusrjquota, 0, MOPT_Q},
{Opt_offgrpjquota, 0, MOPT_Q},
{Opt_jqfmt_vfsold, QFMT_VFS_OLD, MOPT_QFMT},
{Opt_jqfmt_vfsv0, QFMT_VFS_V0, MOPT_QFMT},
{Opt_jqfmt_vfsv1, QFMT_VFS_V1, MOPT_QFMT},
{Opt_max_dir_size_kb, 0, MOPT_GTE0},
{Opt_test_dummy_encryption, 0, MOPT_GTE0},
{Opt_err, 0, 0}
};
static int handle_mount_opt(struct super_block *sb, char *opt, int token,
substring_t *args, unsigned long *journal_devnum,
unsigned int *journal_ioprio, int is_remount)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
const struct mount_opts *m;
kuid_t uid;
kgid_t gid;
int arg = 0;
#ifdef CONFIG_QUOTA
if (token == Opt_usrjquota)
return set_qf_name(sb, USRQUOTA, &args[0]);
else if (token == Opt_grpjquota)
return set_qf_name(sb, GRPQUOTA, &args[0]);
else if (token == Opt_offusrjquota)
return clear_qf_name(sb, USRQUOTA);
else if (token == Opt_offgrpjquota)
return clear_qf_name(sb, GRPQUOTA);
#endif
switch (token) {
case Opt_noacl:
case Opt_nouser_xattr:
ext4_msg(sb, KERN_WARNING, deprecated_msg, opt, "3.5");
break;
case Opt_sb:
return 1; /* handled by get_sb_block() */
case Opt_removed:
ext4_msg(sb, KERN_WARNING, "Ignoring removed %s option", opt);
return 1;
case Opt_abort:
sbi->s_mount_flags |= EXT4_MF_FS_ABORTED;
return 1;
case Opt_i_version:
sb->s_flags |= MS_I_VERSION;
return 1;
case Opt_lazytime:
sb->s_flags |= MS_LAZYTIME;
return 1;
case Opt_nolazytime:
sb->s_flags &= ~MS_LAZYTIME;
return 1;
}
for (m = ext4_mount_opts; m->token != Opt_err; m++)
if (token == m->token)
break;
if (m->token == Opt_err) {
ext4_msg(sb, KERN_ERR, "Unrecognized mount option \"%s\" "
"or missing value", opt);
return -1;
}
if ((m->flags & MOPT_NO_EXT2) && IS_EXT2_SB(sb)) {
ext4_msg(sb, KERN_ERR,
"Mount option \"%s\" incompatible with ext2", opt);
return -1;
}
if ((m->flags & MOPT_NO_EXT3) && IS_EXT3_SB(sb)) {
ext4_msg(sb, KERN_ERR,
"Mount option \"%s\" incompatible with ext3", opt);
return -1;
}
if (args->from && !(m->flags & MOPT_STRING) && match_int(args, &arg))
return -1;
if (args->from && (m->flags & MOPT_GTE0) && (arg < 0))
return -1;
if (m->flags & MOPT_EXPLICIT) {
if (m->mount_opt & EXT4_MOUNT_DELALLOC) {
set_opt2(sb, EXPLICIT_DELALLOC);
} else if (m->mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) {
set_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM);
} else
return -1;
}
if (m->flags & MOPT_CLEAR_ERR)
clear_opt(sb, ERRORS_MASK);
if (token == Opt_noquota && sb_any_quota_loaded(sb)) {
ext4_msg(sb, KERN_ERR, "Cannot change quota "
"options when quota turned on");
return -1;
}
if (m->flags & MOPT_NOSUPPORT) {
ext4_msg(sb, KERN_ERR, "%s option not supported", opt);
} else if (token == Opt_commit) {
if (arg == 0)
arg = JBD2_DEFAULT_MAX_COMMIT_AGE;
sbi->s_commit_interval = HZ * arg;
} else if (token == Opt_max_batch_time) {
sbi->s_max_batch_time = arg;
} else if (token == Opt_min_batch_time) {
sbi->s_min_batch_time = arg;
} else if (token == Opt_inode_readahead_blks) {
if (arg && (arg > (1 << 30) || !is_power_of_2(arg))) {
ext4_msg(sb, KERN_ERR,
"EXT4-fs: inode_readahead_blks must be "
"0 or a power of 2 smaller than 2^31");
return -1;
}
sbi->s_inode_readahead_blks = arg;
} else if (token == Opt_init_itable) {
set_opt(sb, INIT_INODE_TABLE);
if (!args->from)
arg = EXT4_DEF_LI_WAIT_MULT;
sbi->s_li_wait_mult = arg;
} else if (token == Opt_max_dir_size_kb) {
sbi->s_max_dir_size_kb = arg;
} else if (token == Opt_stripe) {
sbi->s_stripe = arg;
} else if (token == Opt_resuid) {
uid = make_kuid(current_user_ns(), arg);
if (!uid_valid(uid)) {
ext4_msg(sb, KERN_ERR, "Invalid uid value %d", arg);
return -1;
}
sbi->s_resuid = uid;
} else if (token == Opt_resgid) {
gid = make_kgid(current_user_ns(), arg);
if (!gid_valid(gid)) {
ext4_msg(sb, KERN_ERR, "Invalid gid value %d", arg);
return -1;
}
sbi->s_resgid = gid;
} else if (token == Opt_journal_dev) {
if (is_remount) {
ext4_msg(sb, KERN_ERR,
"Cannot specify journal on remount");
return -1;
}
*journal_devnum = arg;
} else if (token == Opt_journal_path) {
char *journal_path;
struct inode *journal_inode;
struct path path;
int error;
if (is_remount) {
ext4_msg(sb, KERN_ERR,
"Cannot specify journal on remount");
return -1;
}
journal_path = match_strdup(&args[0]);
if (!journal_path) {
ext4_msg(sb, KERN_ERR, "error: could not dup "
"journal device string");
return -1;
}
error = kern_path(journal_path, LOOKUP_FOLLOW, &path);
if (error) {
ext4_msg(sb, KERN_ERR, "error: could not find "
"journal device path: error %d", error);
kfree(journal_path);
return -1;
}
journal_inode = d_inode(path.dentry);
if (!S_ISBLK(journal_inode->i_mode)) {
ext4_msg(sb, KERN_ERR, "error: journal path %s "
"is not a block device", journal_path);
path_put(&path);
kfree(journal_path);
return -1;
}
*journal_devnum = new_encode_dev(journal_inode->i_rdev);
path_put(&path);
kfree(journal_path);
} else if (token == Opt_journal_ioprio) {
if (arg > 7) {
ext4_msg(sb, KERN_ERR, "Invalid journal IO priority"
" (must be 0-7)");
return -1;
}
*journal_ioprio =
IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, arg);
} else if (token == Opt_test_dummy_encryption) {
#ifdef CONFIG_EXT4_FS_ENCRYPTION
sbi->s_mount_flags |= EXT4_MF_TEST_DUMMY_ENCRYPTION;
ext4_msg(sb, KERN_WARNING,
"Test dummy encryption mode enabled");
#else
ext4_msg(sb, KERN_WARNING,
"Test dummy encryption mount option ignored");
#endif
} else if (m->flags & MOPT_DATAJ) {
if (is_remount) {
if (!sbi->s_journal)
ext4_msg(sb, KERN_WARNING, "Remounting file system with no journal so ignoring journalled data option");
else if (test_opt(sb, DATA_FLAGS) != m->mount_opt) {
ext4_msg(sb, KERN_ERR,
"Cannot change data mode on remount");
return -1;
}
} else {
clear_opt(sb, DATA_FLAGS);
sbi->s_mount_opt |= m->mount_opt;
}
#ifdef CONFIG_QUOTA
} else if (m->flags & MOPT_QFMT) {
if (sb_any_quota_loaded(sb) &&
sbi->s_jquota_fmt != m->mount_opt) {
ext4_msg(sb, KERN_ERR, "Cannot change journaled "
"quota options when quota turned on");
return -1;
}
if (ext4_has_feature_quota(sb)) {
ext4_msg(sb, KERN_ERR,
"Cannot set journaled quota options "
"when QUOTA feature is enabled");
return -1;
}
sbi->s_jquota_fmt = m->mount_opt;
#endif
} else if (token == Opt_dax) {
#ifdef CONFIG_FS_DAX
ext4_msg(sb, KERN_WARNING,
"DAX enabled. Warning: EXPERIMENTAL, use at your own risk");
sbi->s_mount_opt |= m->mount_opt;
#else
ext4_msg(sb, KERN_INFO, "dax option not supported");
return -1;
#endif
} else {
if (!args->from)
arg = 1;
if (m->flags & MOPT_CLEAR)
arg = !arg;
else if (unlikely(!(m->flags & MOPT_SET))) {
ext4_msg(sb, KERN_WARNING,
"buggy handling of option %s", opt);
WARN_ON(1);
return -1;
}
if (arg != 0)
sbi->s_mount_opt |= m->mount_opt;
else
sbi->s_mount_opt &= ~m->mount_opt;
}
return 1;
}
static int parse_options(char *options, struct super_block *sb,
unsigned long *journal_devnum,
unsigned int *journal_ioprio,
int is_remount)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
char *p;
substring_t args[MAX_OPT_ARGS];
int token;
if (!options)
return 1;
while ((p = strsep(&options, ",")) != NULL) {
if (!*p)
continue;
/*
* Initialize args struct so we know whether arg was
* found; some options take optional arguments.
*/
args[0].to = args[0].from = NULL;
token = match_token(p, tokens, args);
if (handle_mount_opt(sb, p, token, args, journal_devnum,
journal_ioprio, is_remount) < 0)
return 0;
}
#ifdef CONFIG_QUOTA
if (ext4_has_feature_quota(sb) &&
(test_opt(sb, USRQUOTA) || test_opt(sb, GRPQUOTA))) {
ext4_msg(sb, KERN_ERR, "Cannot set quota options when QUOTA "
"feature is enabled");
return 0;
}
if (sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
if (test_opt(sb, USRQUOTA) && sbi->s_qf_names[USRQUOTA])
clear_opt(sb, USRQUOTA);
if (test_opt(sb, GRPQUOTA) && sbi->s_qf_names[GRPQUOTA])
clear_opt(sb, GRPQUOTA);
if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) {
ext4_msg(sb, KERN_ERR, "old and new quota "
"format mixing");
return 0;
}
if (!sbi->s_jquota_fmt) {
ext4_msg(sb, KERN_ERR, "journaled quota format "
"not specified");
return 0;
}
}
#endif
if (test_opt(sb, DIOREAD_NOLOCK)) {
int blocksize =
BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);
if (blocksize < PAGE_CACHE_SIZE) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"dioread_nolock if block size != PAGE_SIZE");
return 0;
}
}
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA &&
test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ext4_msg(sb, KERN_ERR, "can't mount with journal_async_commit "
"in data=ordered mode");
return 0;
}
return 1;
}
static inline void ext4_show_quota_options(struct seq_file *seq,
struct super_block *sb)
{
#if defined(CONFIG_QUOTA)
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (sbi->s_jquota_fmt) {
char *fmtname = "";
switch (sbi->s_jquota_fmt) {
case QFMT_VFS_OLD:
fmtname = "vfsold";
break;
case QFMT_VFS_V0:
fmtname = "vfsv0";
break;
case QFMT_VFS_V1:
fmtname = "vfsv1";
break;
}
seq_printf(seq, ",jqfmt=%s", fmtname);
}
if (sbi->s_qf_names[USRQUOTA])
seq_show_option(seq, "usrjquota", sbi->s_qf_names[USRQUOTA]);
if (sbi->s_qf_names[GRPQUOTA])
seq_show_option(seq, "grpjquota", sbi->s_qf_names[GRPQUOTA]);
#endif
}
static const char *token2str(int token)
{
const struct match_token *t;
for (t = tokens; t->token != Opt_err; t++)
if (t->token == token && !strchr(t->pattern, '='))
break;
return t->pattern;
}
/*
* Show an option if
* - it's set to a non-default value OR
* - if the per-sb default is different from the global default
*/
static int _ext4_show_options(struct seq_file *seq, struct super_block *sb,
int nodefs)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int def_errors, def_mount_opt = nodefs ? 0 : sbi->s_def_mount_opt;
const struct mount_opts *m;
char sep = nodefs ? '\n' : ',';
#define SEQ_OPTS_PUTS(str) seq_printf(seq, "%c" str, sep)
#define SEQ_OPTS_PRINT(str, arg) seq_printf(seq, "%c" str, sep, arg)
if (sbi->s_sb_block != 1)
SEQ_OPTS_PRINT("sb=%llu", sbi->s_sb_block);
for (m = ext4_mount_opts; m->token != Opt_err; m++) {
int want_set = m->flags & MOPT_SET;
if (((m->flags & (MOPT_SET|MOPT_CLEAR)) == 0) ||
(m->flags & MOPT_CLEAR_ERR))
continue;
if (!(m->mount_opt & (sbi->s_mount_opt ^ def_mount_opt)))
continue; /* skip if same as the default */
if ((want_set &&
(sbi->s_mount_opt & m->mount_opt) != m->mount_opt) ||
(!want_set && (sbi->s_mount_opt & m->mount_opt)))
continue; /* select Opt_noFoo vs Opt_Foo */
SEQ_OPTS_PRINT("%s", token2str(m->token));
}
if (nodefs || !uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT4_DEF_RESUID)) ||
le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID)
SEQ_OPTS_PRINT("resuid=%u",
from_kuid_munged(&init_user_ns, sbi->s_resuid));
if (nodefs || !gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT4_DEF_RESGID)) ||
le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID)
SEQ_OPTS_PRINT("resgid=%u",
from_kgid_munged(&init_user_ns, sbi->s_resgid));
def_errors = nodefs ? -1 : le16_to_cpu(es->s_errors);
if (test_opt(sb, ERRORS_RO) && def_errors != EXT4_ERRORS_RO)
SEQ_OPTS_PUTS("errors=remount-ro");
if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE)
SEQ_OPTS_PUTS("errors=continue");
if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC)
SEQ_OPTS_PUTS("errors=panic");
if (nodefs || sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ)
SEQ_OPTS_PRINT("commit=%lu", sbi->s_commit_interval / HZ);
if (nodefs || sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME)
SEQ_OPTS_PRINT("min_batch_time=%u", sbi->s_min_batch_time);
if (nodefs || sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME)
SEQ_OPTS_PRINT("max_batch_time=%u", sbi->s_max_batch_time);
if (sb->s_flags & MS_I_VERSION)
SEQ_OPTS_PUTS("i_version");
if (nodefs || sbi->s_stripe)
SEQ_OPTS_PRINT("stripe=%lu", sbi->s_stripe);
if (EXT4_MOUNT_DATA_FLAGS & (sbi->s_mount_opt ^ def_mount_opt)) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
SEQ_OPTS_PUTS("data=journal");
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
SEQ_OPTS_PUTS("data=ordered");
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)
SEQ_OPTS_PUTS("data=writeback");
}
if (nodefs ||
sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS)
SEQ_OPTS_PRINT("inode_readahead_blks=%u",
sbi->s_inode_readahead_blks);
if (nodefs || (test_opt(sb, INIT_INODE_TABLE) &&
(sbi->s_li_wait_mult != EXT4_DEF_LI_WAIT_MULT)))
SEQ_OPTS_PRINT("init_itable=%u", sbi->s_li_wait_mult);
if (nodefs || sbi->s_max_dir_size_kb)
SEQ_OPTS_PRINT("max_dir_size_kb=%u", sbi->s_max_dir_size_kb);
ext4_show_quota_options(seq, sb);
return 0;
}
static int ext4_show_options(struct seq_file *seq, struct dentry *root)
{
return _ext4_show_options(seq, root->d_sb, 0);
}
int ext4_seq_options_show(struct seq_file *seq, void *offset)
{
struct super_block *sb = seq->private;
int rc;
seq_puts(seq, (sb->s_flags & MS_RDONLY) ? "ro" : "rw");
rc = _ext4_show_options(seq, sb, 1);
seq_puts(seq, "\n");
return rc;
}
static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es,
int read_only)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int res = 0;
if (le32_to_cpu(es->s_rev_level) > EXT4_MAX_SUPP_REV) {
ext4_msg(sb, KERN_ERR, "revision level too high, "
"forcing read-only mode");
res = MS_RDONLY;
}
if (read_only)
goto done;
if (!(sbi->s_mount_state & EXT4_VALID_FS))
ext4_msg(sb, KERN_WARNING, "warning: mounting unchecked fs, "
"running e2fsck is recommended");
else if (sbi->s_mount_state & EXT4_ERROR_FS)
ext4_msg(sb, KERN_WARNING,
"warning: mounting fs with errors, "
"running e2fsck is recommended");
else if ((__s16) le16_to_cpu(es->s_max_mnt_count) > 0 &&
le16_to_cpu(es->s_mnt_count) >=
(unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count))
ext4_msg(sb, KERN_WARNING,
"warning: maximal mount count reached, "
"running e2fsck is recommended");
else if (le32_to_cpu(es->s_checkinterval) &&
(le32_to_cpu(es->s_lastcheck) +
le32_to_cpu(es->s_checkinterval) <= get_seconds()))
ext4_msg(sb, KERN_WARNING,
"warning: checktime reached, "
"running e2fsck is recommended");
if (!sbi->s_journal)
es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
if (!(__s16) le16_to_cpu(es->s_max_mnt_count))
es->s_max_mnt_count = cpu_to_le16(EXT4_DFL_MAX_MNT_COUNT);
le16_add_cpu(&es->s_mnt_count, 1);
es->s_mtime = cpu_to_le32(get_seconds());
ext4_update_dynamic_rev(sb);
if (sbi->s_journal)
ext4_set_feature_journal_needs_recovery(sb);
ext4_commit_super(sb, 1);
done:
if (test_opt(sb, DEBUG))
printk(KERN_INFO "[EXT4 FS bs=%lu, gc=%u, "
"bpg=%lu, ipg=%lu, mo=%04x, mo2=%04x]\n",
sb->s_blocksize,
sbi->s_groups_count,
EXT4_BLOCKS_PER_GROUP(sb),
EXT4_INODES_PER_GROUP(sb),
sbi->s_mount_opt, sbi->s_mount_opt2);
cleancache_init_fs(sb);
return res;
}
int ext4_alloc_flex_bg_array(struct super_block *sb, ext4_group_t ngroup)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct flex_groups *new_groups;
int size;
if (!sbi->s_log_groups_per_flex)
return 0;
size = ext4_flex_group(sbi, ngroup - 1) + 1;
if (size <= sbi->s_flex_groups_allocated)
return 0;
size = roundup_pow_of_two(size * sizeof(struct flex_groups));
new_groups = ext4_kvzalloc(size, GFP_KERNEL);
if (!new_groups) {
ext4_msg(sb, KERN_ERR, "not enough memory for %d flex groups",
size / (int) sizeof(struct flex_groups));
return -ENOMEM;
}
if (sbi->s_flex_groups) {
memcpy(new_groups, sbi->s_flex_groups,
(sbi->s_flex_groups_allocated *
sizeof(struct flex_groups)));
kvfree(sbi->s_flex_groups);
}
sbi->s_flex_groups = new_groups;
sbi->s_flex_groups_allocated = size / sizeof(struct flex_groups);
return 0;
}
static int ext4_fill_flex_info(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp = NULL;
ext4_group_t flex_group;
int i, err;
sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
if (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) {
sbi->s_log_groups_per_flex = 0;
return 1;
}
err = ext4_alloc_flex_bg_array(sb, sbi->s_groups_count);
if (err)
goto failed;
for (i = 0; i < sbi->s_groups_count; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
flex_group = ext4_flex_group(sbi, i);
atomic_add(ext4_free_inodes_count(sb, gdp),
&sbi->s_flex_groups[flex_group].free_inodes);
atomic64_add(ext4_free_group_clusters(sb, gdp),
&sbi->s_flex_groups[flex_group].free_clusters);
atomic_add(ext4_used_dirs_count(sb, gdp),
&sbi->s_flex_groups[flex_group].used_dirs);
}
return 1;
failed:
return 0;
}
static __le16 ext4_group_desc_csum(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
int offset;
__u16 crc = 0;
__le32 le_group = cpu_to_le32(block_group);
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (ext4_has_metadata_csum(sbi->s_sb)) {
/* Use new metadata_csum algorithm */
__le16 save_csum;
__u32 csum32;
save_csum = gdp->bg_checksum;
gdp->bg_checksum = 0;
csum32 = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&le_group,
sizeof(le_group));
csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp,
sbi->s_desc_size);
gdp->bg_checksum = save_csum;
crc = csum32 & 0xFFFF;
goto out;
}
/* old crc16 code */
if (!ext4_has_feature_gdt_csum(sb))
return 0;
offset = offsetof(struct ext4_group_desc, bg_checksum);
crc = crc16(~0, sbi->s_es->s_uuid, sizeof(sbi->s_es->s_uuid));
crc = crc16(crc, (__u8 *)&le_group, sizeof(le_group));
crc = crc16(crc, (__u8 *)gdp, offset);
offset += sizeof(gdp->bg_checksum); /* skip checksum */
/* for checksum of struct ext4_group_desc do the rest...*/
if (ext4_has_feature_64bit(sb) &&
offset < le16_to_cpu(sbi->s_es->s_desc_size))
crc = crc16(crc, (__u8 *)gdp + offset,
le16_to_cpu(sbi->s_es->s_desc_size) -
offset);
out:
return cpu_to_le16(crc);
}
int ext4_group_desc_csum_verify(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
if (ext4_has_group_desc_csum(sb) &&
(gdp->bg_checksum != ext4_group_desc_csum(sb, block_group, gdp)))
return 0;
return 1;
}
void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
if (!ext4_has_group_desc_csum(sb))
return;
gdp->bg_checksum = ext4_group_desc_csum(sb, block_group, gdp);
}
/* Called at mount-time, super-block is locked */
static int ext4_check_descriptors(struct super_block *sb,
ext4_group_t *first_not_zeroed)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block);
ext4_fsblk_t last_block;
ext4_fsblk_t block_bitmap;
ext4_fsblk_t inode_bitmap;
ext4_fsblk_t inode_table;
int flexbg_flag = 0;
ext4_group_t i, grp = sbi->s_groups_count;
if (ext4_has_feature_flex_bg(sb))
flexbg_flag = 1;
ext4_debug("Checking group descriptors");
for (i = 0; i < sbi->s_groups_count; i++) {
struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
if (i == sbi->s_groups_count - 1 || flexbg_flag)
last_block = ext4_blocks_count(sbi->s_es) - 1;
else
last_block = first_block +
(EXT4_BLOCKS_PER_GROUP(sb) - 1);
if ((grp == sbi->s_groups_count) &&
!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
grp = i;
block_bitmap = ext4_block_bitmap(sb, gdp);
if (block_bitmap < first_block || block_bitmap > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Block bitmap for group %u not in group "
"(block %llu)!", i, block_bitmap);
return 0;
}
inode_bitmap = ext4_inode_bitmap(sb, gdp);
if (inode_bitmap < first_block || inode_bitmap > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode bitmap for group %u not in group "
"(block %llu)!", i, inode_bitmap);
return 0;
}
inode_table = ext4_inode_table(sb, gdp);
if (inode_table < first_block ||
inode_table + sbi->s_itb_per_group - 1 > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode table for group %u not in group "
"(block %llu)!", i, inode_table);
return 0;
}
ext4_lock_group(sb, i);
if (!ext4_group_desc_csum_verify(sb, i, gdp)) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Checksum for group %u failed (%u!=%u)",
i, le16_to_cpu(ext4_group_desc_csum(sb, i,
gdp)), le16_to_cpu(gdp->bg_checksum));
if (!(sb->s_flags & MS_RDONLY)) {
ext4_unlock_group(sb, i);
return 0;
}
}
ext4_unlock_group(sb, i);
if (!flexbg_flag)
first_block += EXT4_BLOCKS_PER_GROUP(sb);
}
if (NULL != first_not_zeroed)
*first_not_zeroed = grp;
return 1;
}
/* ext4_orphan_cleanup() walks a singly-linked list of inodes (starting at
* the superblock) which were deleted from all directories, but held open by
* a process at the time of a crash. We walk the list and try to delete these
* inodes at recovery time (only with a read-write filesystem).
*
* In order to keep the orphan inode chain consistent during traversal (in
* case of crash during recovery), we link each inode into the superblock
* orphan list_head and handle it the same way as an inode deletion during
* normal operation (which journals the operations for us).
*
* We only do an iget() and an iput() on each inode, which is very safe if we
* accidentally point at an in-use or already deleted inode. The worst that
* can happen in this case is that we get a "bit already cleared" message from
* ext4_free_inode(). The only reason we would point at a wrong inode is if
* e2fsck was run on this filesystem, and it must have already done the orphan
* inode cleanup for us, so we can safely abort without any further action.
*/
static void ext4_orphan_cleanup(struct super_block *sb,
struct ext4_super_block *es)
{
unsigned int s_flags = sb->s_flags;
int nr_orphans = 0, nr_truncates = 0;
#ifdef CONFIG_QUOTA
int i;
#endif
if (!es->s_last_orphan) {
jbd_debug(4, "no orphan inodes to clean up\n");
return;
}
if (bdev_read_only(sb->s_bdev)) {
ext4_msg(sb, KERN_ERR, "write access "
"unavailable, skipping orphan cleanup");
return;
}
/* Check if feature set would not allow a r/w mount */
if (!ext4_feature_set_ok(sb, 0)) {
ext4_msg(sb, KERN_INFO, "Skipping orphan cleanup due to "
"unknown ROCOMPAT features");
return;
}
if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
/* don't clear list on RO mount w/ errors */
if (es->s_last_orphan && !(s_flags & MS_RDONLY)) {
ext4_msg(sb, KERN_INFO, "Errors on filesystem, "
"clearing orphan list.\n");
es->s_last_orphan = 0;
}
jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
return;
}
if (s_flags & MS_RDONLY) {
ext4_msg(sb, KERN_INFO, "orphan cleanup on readonly fs");
sb->s_flags &= ~MS_RDONLY;
}
#ifdef CONFIG_QUOTA
/* Needed for iput() to work correctly and not trash data */
sb->s_flags |= MS_ACTIVE;
/* Turn on quotas so that they are updated correctly */
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
if (EXT4_SB(sb)->s_qf_names[i]) {
int ret = ext4_quota_on_mount(sb, i);
if (ret < 0)
ext4_msg(sb, KERN_ERR,
"Cannot turn on journaled "
"quota: error %d", ret);
}
}
#endif
while (es->s_last_orphan) {
struct inode *inode;
inode = ext4_orphan_get(sb, le32_to_cpu(es->s_last_orphan));
if (IS_ERR(inode)) {
es->s_last_orphan = 0;
break;
}
list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
dquot_initialize(inode);
if (inode->i_nlink) {
if (test_opt(sb, DEBUG))
ext4_msg(sb, KERN_DEBUG,
"%s: truncating inode %lu to %lld bytes",
__func__, inode->i_ino, inode->i_size);
jbd_debug(2, "truncating inode %lu to %lld bytes\n",
inode->i_ino, inode->i_size);
inode_lock(inode);
truncate_inode_pages(inode->i_mapping, inode->i_size);
ext4_truncate(inode);
inode_unlock(inode);
nr_truncates++;
} else {
if (test_opt(sb, DEBUG))
ext4_msg(sb, KERN_DEBUG,
"%s: deleting unreferenced inode %lu",
__func__, inode->i_ino);
jbd_debug(2, "deleting unreferenced inode %lu\n",
inode->i_ino);
nr_orphans++;
}
iput(inode); /* The delete magic happens here! */
}
#define PLURAL(x) (x), ((x) == 1) ? "" : "s"
if (nr_orphans)
ext4_msg(sb, KERN_INFO, "%d orphan inode%s deleted",
PLURAL(nr_orphans));
if (nr_truncates)
ext4_msg(sb, KERN_INFO, "%d truncate%s cleaned up",
PLURAL(nr_truncates));
#ifdef CONFIG_QUOTA
/* Turn quotas off */
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
if (sb_dqopt(sb)->files[i])
dquot_quota_off(sb, i);
}
#endif
sb->s_flags = s_flags; /* Restore MS_RDONLY status */
}
/*
* Maximal extent format file size.
* Resulting logical blkno at s_maxbytes must fit in our on-disk
* extent format containers, within a sector_t, and within i_blocks
* in the vfs. ext4 inode has 48 bits of i_block in fsblock units,
* so that won't be a limiting factor.
*
* However there is other limiting factor. We do store extents in the form
* of starting block and length, hence the resulting length of the extent
* covering maximum file size must fit into on-disk format containers as
* well. Given that length is always by 1 unit bigger than max unit (because
* we count 0 as well) we have to lower the s_maxbytes by one fs block.
*
* Note, this does *not* consider any metadata overhead for vfs i_blocks.
*/
static loff_t ext4_max_size(int blkbits, int has_huge_files)
{
loff_t res;
loff_t upper_limit = MAX_LFS_FILESIZE;
/* small i_blocks in vfs inode? */
if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
/*
* CONFIG_LBDAF is not enabled implies the inode
* i_block represent total blocks in 512 bytes
* 32 == size of vfs inode i_blocks * 8
*/
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (blkbits - 9);
upper_limit <<= blkbits;
}
/*
* 32-bit extent-start container, ee_block. We lower the maxbytes
* by one fs block, so ee_len can cover the extent of maximum file
* size
*/
res = (1LL << 32) - 1;
res <<= blkbits;
/* Sanity check against vm- & vfs- imposed limits */
if (res > upper_limit)
res = upper_limit;
return res;
}
/*
* Maximal bitmap file size. There is a direct, and {,double-,triple-}indirect
* block limit, and also a limit of (2^48 - 1) 512-byte sectors in i_blocks.
* We need to be 1 filesystem block less than the 2^48 sector limit.
*/
static loff_t ext4_max_bitmap_size(int bits, int has_huge_files)
{
loff_t res = EXT4_NDIR_BLOCKS;
int meta_blocks;
loff_t upper_limit;
/* This is calculated to be the largest file size for a dense, block
* mapped file such that the file's total number of 512-byte sectors,
* including data and all indirect blocks, does not exceed (2^48 - 1).
*
* __u32 i_blocks_lo and _u16 i_blocks_high represent the total
* number of 512-byte sectors of the file.
*/
if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
/*
* !has_huge_files or CONFIG_LBDAF not enabled implies that
* the inode i_block field represents total file blocks in
* 2^32 512-byte sectors == size of vfs inode i_blocks * 8
*/
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (bits - 9);
} else {
/*
* We use 48 bit ext4_inode i_blocks
* With EXT4_HUGE_FILE_FL set the i_blocks
* represent total number of blocks in
* file system block size
*/
upper_limit = (1LL << 48) - 1;
}
/* indirect blocks */
meta_blocks = 1;
/* double indirect blocks */
meta_blocks += 1 + (1LL << (bits-2));
/* tripple indirect blocks */
meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2)));
upper_limit -= meta_blocks;
upper_limit <<= bits;
res += 1LL << (bits-2);
res += 1LL << (2*(bits-2));
res += 1LL << (3*(bits-2));
res <<= bits;
if (res > upper_limit)
res = upper_limit;
if (res > MAX_LFS_FILESIZE)
res = MAX_LFS_FILESIZE;
return res;
}
static ext4_fsblk_t descriptor_loc(struct super_block *sb,
ext4_fsblk_t logical_sb_block, int nr)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_group_t bg, first_meta_bg;
int has_super = 0;
first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
if (!ext4_has_feature_meta_bg(sb) || nr < first_meta_bg)
return logical_sb_block + nr + 1;
bg = sbi->s_desc_per_block * nr;
if (ext4_bg_has_super(sb, bg))
has_super = 1;
/*
* If we have a meta_bg fs with 1k blocks, group 0's GDT is at
* block 2, not 1. If s_first_data_block == 0 (bigalloc is enabled
* on modern mke2fs or blksize > 1k on older mke2fs) then we must
* compensate.
*/
if (sb->s_blocksize == 1024 && nr == 0 &&
le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block) == 0)
has_super++;
return (has_super + ext4_group_first_block_no(sb, bg));
}
/**
* ext4_get_stripe_size: Get the stripe size.
* @sbi: In memory super block info
*
* If we have specified it via mount option, then
* use the mount option value. If the value specified at mount time is
* greater than the blocks per group use the super block value.
* If the super block value is greater than blocks per group return 0.
* Allocator needs it be less than blocks per group.
*
*/
static unsigned long ext4_get_stripe_size(struct ext4_sb_info *sbi)
{
unsigned long stride = le16_to_cpu(sbi->s_es->s_raid_stride);
unsigned long stripe_width =
le32_to_cpu(sbi->s_es->s_raid_stripe_width);
int ret;
if (sbi->s_stripe && sbi->s_stripe <= sbi->s_blocks_per_group)
ret = sbi->s_stripe;
else if (stripe_width <= sbi->s_blocks_per_group)
ret = stripe_width;
else if (stride <= sbi->s_blocks_per_group)
ret = stride;
else
ret = 0;
/*
* If the stripe width is 1, this makes no sense and
* we set it to 0 to turn off stripe handling code.
*/
if (ret <= 1)
ret = 0;
return ret;
}
/*
* Check whether this filesystem can be mounted based on
* the features present and the RDONLY/RDWR mount requested.
* Returns 1 if this filesystem can be mounted as requested,
* 0 if it cannot be.
*/
static int ext4_feature_set_ok(struct super_block *sb, int readonly)
{
if (ext4_has_unknown_ext4_incompat_features(sb)) {
ext4_msg(sb, KERN_ERR,
"Couldn't mount because of "
"unsupported optional features (%x)",
(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) &
~EXT4_FEATURE_INCOMPAT_SUPP));
return 0;
}
if (readonly)
return 1;
if (ext4_has_feature_readonly(sb)) {
ext4_msg(sb, KERN_INFO, "filesystem is read-only");
sb->s_flags |= MS_RDONLY;
return 1;
}
/* Check that feature set is OK for a read-write mount */
if (ext4_has_unknown_ext4_ro_compat_features(sb)) {
ext4_msg(sb, KERN_ERR, "couldn't mount RDWR because of "
"unsupported optional features (%x)",
(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) &
~EXT4_FEATURE_RO_COMPAT_SUPP));
return 0;
}
/*
* Large file size enabled file system can only be mounted
* read-write on 32-bit systems if kernel is built with CONFIG_LBDAF
*/
if (ext4_has_feature_huge_file(sb)) {
if (sizeof(blkcnt_t) < sizeof(u64)) {
ext4_msg(sb, KERN_ERR, "Filesystem with huge files "
"cannot be mounted RDWR without "
"CONFIG_LBDAF");
return 0;
}
}
if (ext4_has_feature_bigalloc(sb) && !ext4_has_feature_extents(sb)) {
ext4_msg(sb, KERN_ERR,
"Can't support bigalloc feature without "
"extents feature\n");
return 0;
}
#ifndef CONFIG_QUOTA
if (ext4_has_feature_quota(sb) && !readonly) {
ext4_msg(sb, KERN_ERR,
"Filesystem with quota feature cannot be mounted RDWR "
"without CONFIG_QUOTA");
return 0;
}
if (ext4_has_feature_project(sb) && !readonly) {
ext4_msg(sb, KERN_ERR,
"Filesystem with project quota feature cannot be mounted RDWR "
"without CONFIG_QUOTA");
return 0;
}
#endif /* CONFIG_QUOTA */
return 1;
}
/*
* This function is called once a day if we have errors logged
* on the file system
*/
static void print_daily_error_info(unsigned long arg)
{
struct super_block *sb = (struct super_block *) arg;
struct ext4_sb_info *sbi;
struct ext4_super_block *es;
sbi = EXT4_SB(sb);
es = sbi->s_es;
if (es->s_error_count)
/* fsck newer than v1.41.13 is needed to clean this condition. */
ext4_msg(sb, KERN_NOTICE, "error count since last fsck: %u",
le32_to_cpu(es->s_error_count));
if (es->s_first_error_time) {
printk(KERN_NOTICE "EXT4-fs (%s): initial error at time %u: %.*s:%d",
sb->s_id, le32_to_cpu(es->s_first_error_time),
(int) sizeof(es->s_first_error_func),
es->s_first_error_func,
le32_to_cpu(es->s_first_error_line));
if (es->s_first_error_ino)
printk(": inode %u",
le32_to_cpu(es->s_first_error_ino));
if (es->s_first_error_block)
printk(": block %llu", (unsigned long long)
le64_to_cpu(es->s_first_error_block));
printk("\n");
}
if (es->s_last_error_time) {
printk(KERN_NOTICE "EXT4-fs (%s): last error at time %u: %.*s:%d",
sb->s_id, le32_to_cpu(es->s_last_error_time),
(int) sizeof(es->s_last_error_func),
es->s_last_error_func,
le32_to_cpu(es->s_last_error_line));
if (es->s_last_error_ino)
printk(": inode %u",
le32_to_cpu(es->s_last_error_ino));
if (es->s_last_error_block)
printk(": block %llu", (unsigned long long)
le64_to_cpu(es->s_last_error_block));
printk("\n");
}
mod_timer(&sbi->s_err_report, jiffies + 24*60*60*HZ); /* Once a day */
}
/* Find next suitable group and run ext4_init_inode_table */
static int ext4_run_li_request(struct ext4_li_request *elr)
{
struct ext4_group_desc *gdp = NULL;
ext4_group_t group, ngroups;
struct super_block *sb;
unsigned long timeout = 0;
int ret = 0;
sb = elr->lr_super;
ngroups = EXT4_SB(sb)->s_groups_count;
sb_start_write(sb);
for (group = elr->lr_next_group; group < ngroups; group++) {
gdp = ext4_get_group_desc(sb, group, NULL);
if (!gdp) {
ret = 1;
break;
}
if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
break;
}
if (group >= ngroups)
ret = 1;
if (!ret) {
timeout = jiffies;
ret = ext4_init_inode_table(sb, group,
elr->lr_timeout ? 0 : 1);
if (elr->lr_timeout == 0) {
timeout = (jiffies - timeout) *
elr->lr_sbi->s_li_wait_mult;
elr->lr_timeout = timeout;
}
elr->lr_next_sched = jiffies + elr->lr_timeout;
elr->lr_next_group = group + 1;
}
sb_end_write(sb);
return ret;
}
/*
* Remove lr_request from the list_request and free the
* request structure. Should be called with li_list_mtx held
*/
static void ext4_remove_li_request(struct ext4_li_request *elr)
{
struct ext4_sb_info *sbi;
if (!elr)
return;
sbi = elr->lr_sbi;
list_del(&elr->lr_request);
sbi->s_li_request = NULL;
kfree(elr);
}
static void ext4_unregister_li_request(struct super_block *sb)
{
mutex_lock(&ext4_li_mtx);
if (!ext4_li_info) {
mutex_unlock(&ext4_li_mtx);
return;
}
mutex_lock(&ext4_li_info->li_list_mtx);
ext4_remove_li_request(EXT4_SB(sb)->s_li_request);
mutex_unlock(&ext4_li_info->li_list_mtx);
mutex_unlock(&ext4_li_mtx);
}
static struct task_struct *ext4_lazyinit_task;
/*
* This is the function where ext4lazyinit thread lives. It walks
* through the request list searching for next scheduled filesystem.
* When such a fs is found, run the lazy initialization request
* (ext4_rn_li_request) and keep track of the time spend in this
* function. Based on that time we compute next schedule time of
* the request. When walking through the list is complete, compute
* next waking time and put itself into sleep.
*/
static int ext4_lazyinit_thread(void *arg)
{
struct ext4_lazy_init *eli = (struct ext4_lazy_init *)arg;
struct list_head *pos, *n;
struct ext4_li_request *elr;
unsigned long next_wakeup, cur;
BUG_ON(NULL == eli);
cont_thread:
while (true) {
next_wakeup = MAX_JIFFY_OFFSET;
mutex_lock(&eli->li_list_mtx);
if (list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
goto exit_thread;
}
list_for_each_safe(pos, n, &eli->li_request_list) {
elr = list_entry(pos, struct ext4_li_request,
lr_request);
if (time_after_eq(jiffies, elr->lr_next_sched)) {
if (ext4_run_li_request(elr) != 0) {
/* error, remove the lazy_init job */
ext4_remove_li_request(elr);
continue;
}
}
if (time_before(elr->lr_next_sched, next_wakeup))
next_wakeup = elr->lr_next_sched;
}
mutex_unlock(&eli->li_list_mtx);
try_to_freeze();
cur = jiffies;
if ((time_after_eq(cur, next_wakeup)) ||
(MAX_JIFFY_OFFSET == next_wakeup)) {
cond_resched();
continue;
}
schedule_timeout_interruptible(next_wakeup - cur);
if (kthread_should_stop()) {
ext4_clear_request_list();
goto exit_thread;
}
}
exit_thread:
/*
* It looks like the request list is empty, but we need
* to check it under the li_list_mtx lock, to prevent any
* additions into it, and of course we should lock ext4_li_mtx
* to atomically free the list and ext4_li_info, because at
* this point another ext4 filesystem could be registering
* new one.
*/
mutex_lock(&ext4_li_mtx);
mutex_lock(&eli->li_list_mtx);
if (!list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
mutex_unlock(&ext4_li_mtx);
goto cont_thread;
}
mutex_unlock(&eli->li_list_mtx);
kfree(ext4_li_info);
ext4_li_info = NULL;
mutex_unlock(&ext4_li_mtx);
return 0;
}
static void ext4_clear_request_list(void)
{
struct list_head *pos, *n;
struct ext4_li_request *elr;
mutex_lock(&ext4_li_info->li_list_mtx);
list_for_each_safe(pos, n, &ext4_li_info->li_request_list) {
elr = list_entry(pos, struct ext4_li_request,
lr_request);
ext4_remove_li_request(elr);
}
mutex_unlock(&ext4_li_info->li_list_mtx);
}
static int ext4_run_lazyinit_thread(void)
{
ext4_lazyinit_task = kthread_run(ext4_lazyinit_thread,
ext4_li_info, "ext4lazyinit");
if (IS_ERR(ext4_lazyinit_task)) {
int err = PTR_ERR(ext4_lazyinit_task);
ext4_clear_request_list();
kfree(ext4_li_info);
ext4_li_info = NULL;
printk(KERN_CRIT "EXT4-fs: error %d creating inode table "
"initialization thread\n",
err);
return err;
}
ext4_li_info->li_state |= EXT4_LAZYINIT_RUNNING;
return 0;
}
/*
* Check whether it make sense to run itable init. thread or not.
* If there is at least one uninitialized inode table, return
* corresponding group number, else the loop goes through all
* groups and return total number of groups.
*/
static ext4_group_t ext4_has_uninit_itable(struct super_block *sb)
{
ext4_group_t group, ngroups = EXT4_SB(sb)->s_groups_count;
struct ext4_group_desc *gdp = NULL;
for (group = 0; group < ngroups; group++) {
gdp = ext4_get_group_desc(sb, group, NULL);
if (!gdp)
continue;
if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
break;
}
return group;
}
static int ext4_li_info_new(void)
{
struct ext4_lazy_init *eli = NULL;
eli = kzalloc(sizeof(*eli), GFP_KERNEL);
if (!eli)
return -ENOMEM;
INIT_LIST_HEAD(&eli->li_request_list);
mutex_init(&eli->li_list_mtx);
eli->li_state |= EXT4_LAZYINIT_QUIT;
ext4_li_info = eli;
return 0;
}
static struct ext4_li_request *ext4_li_request_new(struct super_block *sb,
ext4_group_t start)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_li_request *elr;
elr = kzalloc(sizeof(*elr), GFP_KERNEL);
if (!elr)
return NULL;
elr->lr_super = sb;
elr->lr_sbi = sbi;
elr->lr_next_group = start;
/*
* Randomize first schedule time of the request to
* spread the inode table initialization requests
* better.
*/
elr->lr_next_sched = jiffies + (prandom_u32() %
(EXT4_DEF_LI_MAX_START_DELAY * HZ));
return elr;
}
int ext4_register_li_request(struct super_block *sb,
ext4_group_t first_not_zeroed)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_li_request *elr = NULL;
ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
int ret = 0;
mutex_lock(&ext4_li_mtx);
if (sbi->s_li_request != NULL) {
/*
* Reset timeout so it can be computed again, because
* s_li_wait_mult might have changed.
*/
sbi->s_li_request->lr_timeout = 0;
goto out;
}
if (first_not_zeroed == ngroups ||
(sb->s_flags & MS_RDONLY) ||
!test_opt(sb, INIT_INODE_TABLE))
goto out;
elr = ext4_li_request_new(sb, first_not_zeroed);
if (!elr) {
ret = -ENOMEM;
goto out;
}
if (NULL == ext4_li_info) {
ret = ext4_li_info_new();
if (ret)
goto out;
}
mutex_lock(&ext4_li_info->li_list_mtx);
list_add(&elr->lr_request, &ext4_li_info->li_request_list);
mutex_unlock(&ext4_li_info->li_list_mtx);
sbi->s_li_request = elr;
/*
* set elr to NULL here since it has been inserted to
* the request_list and the removal and free of it is
* handled by ext4_clear_request_list from now on.
*/
elr = NULL;
if (!(ext4_li_info->li_state & EXT4_LAZYINIT_RUNNING)) {
ret = ext4_run_lazyinit_thread();
if (ret)
goto out;
}
out:
mutex_unlock(&ext4_li_mtx);
if (ret)
kfree(elr);
return ret;
}
/*
* We do not need to lock anything since this is called on
* module unload.
*/
static void ext4_destroy_lazyinit_thread(void)
{
/*
* If thread exited earlier
* there's nothing to be done.
*/
if (!ext4_li_info || !ext4_lazyinit_task)
return;
kthread_stop(ext4_lazyinit_task);
}
static int set_journal_csum_feature_set(struct super_block *sb)
{
int ret = 1;
int compat, incompat;
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (ext4_has_metadata_csum(sb)) {
/* journal checksum v3 */
compat = 0;
incompat = JBD2_FEATURE_INCOMPAT_CSUM_V3;
} else {
/* journal checksum v1 */
compat = JBD2_FEATURE_COMPAT_CHECKSUM;
incompat = 0;
}
jbd2_journal_clear_features(sbi->s_journal,
JBD2_FEATURE_COMPAT_CHECKSUM, 0,
JBD2_FEATURE_INCOMPAT_CSUM_V3 |
JBD2_FEATURE_INCOMPAT_CSUM_V2);
if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ret = jbd2_journal_set_features(sbi->s_journal,
compat, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT |
incompat);
} else if (test_opt(sb, JOURNAL_CHECKSUM)) {
ret = jbd2_journal_set_features(sbi->s_journal,
compat, 0,
incompat);
jbd2_journal_clear_features(sbi->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
} else {
jbd2_journal_clear_features(sbi->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
}
return ret;
}
/*
* Note: calculating the overhead so we can be compatible with
* historical BSD practice is quite difficult in the face of
* clusters/bigalloc. This is because multiple metadata blocks from
* different block group can end up in the same allocation cluster.
* Calculating the exact overhead in the face of clustered allocation
* requires either O(all block bitmaps) in memory or O(number of block
* groups**2) in time. We will still calculate the superblock for
* older file systems --- and if we come across with a bigalloc file
* system with zero in s_overhead_clusters the estimate will be close to
* correct especially for very large cluster sizes --- but for newer
* file systems, it's better to calculate this figure once at mkfs
* time, and store it in the superblock. If the superblock value is
* present (even for non-bigalloc file systems), we will use it.
*/
static int count_overhead(struct super_block *sb, ext4_group_t grp,
char *buf)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp;
ext4_fsblk_t first_block, last_block, b;
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
int s, j, count = 0;
if (!ext4_has_feature_bigalloc(sb))
return (ext4_bg_has_super(sb, grp) + ext4_bg_num_gdb(sb, grp) +
sbi->s_itb_per_group + 2);
first_block = le32_to_cpu(sbi->s_es->s_first_data_block) +
(grp * EXT4_BLOCKS_PER_GROUP(sb));
last_block = first_block + EXT4_BLOCKS_PER_GROUP(sb) - 1;
for (i = 0; i < ngroups; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
b = ext4_block_bitmap(sb, gdp);
if (b >= first_block && b <= last_block) {
ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
count++;
}
b = ext4_inode_bitmap(sb, gdp);
if (b >= first_block && b <= last_block) {
ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
count++;
}
b = ext4_inode_table(sb, gdp);
if (b >= first_block && b + sbi->s_itb_per_group <= last_block)
for (j = 0; j < sbi->s_itb_per_group; j++, b++) {
int c = EXT4_B2C(sbi, b - first_block);
ext4_set_bit(c, buf);
count++;
}
if (i != grp)
continue;
s = 0;
if (ext4_bg_has_super(sb, grp)) {
ext4_set_bit(s++, buf);
count++;
}
for (j = ext4_bg_num_gdb(sb, grp); j > 0; j--) {
ext4_set_bit(EXT4_B2C(sbi, s++), buf);
count++;
}
}
if (!count)
return 0;
return EXT4_CLUSTERS_PER_GROUP(sb) -
ext4_count_free(buf, EXT4_CLUSTERS_PER_GROUP(sb) / 8);
}
/*
* Compute the overhead and stash it in sbi->s_overhead
*/
int ext4_calculate_overhead(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
ext4_fsblk_t overhead = 0;
char *buf = (char *) get_zeroed_page(GFP_NOFS);
if (!buf)
return -ENOMEM;
/*
* Compute the overhead (FS structures). This is constant
* for a given filesystem unless the number of block groups
* changes so we cache the previous value until it does.
*/
/*
* All of the blocks before first_data_block are overhead
*/
overhead = EXT4_B2C(sbi, le32_to_cpu(es->s_first_data_block));
/*
* Add the overhead found in each block group
*/
for (i = 0; i < ngroups; i++) {
int blks;
blks = count_overhead(sb, i, buf);
overhead += blks;
if (blks)
memset(buf, 0, PAGE_SIZE);
cond_resched();
}
/* Add the internal journal blocks as well */
if (sbi->s_journal && !sbi->journal_bdev)
overhead += EXT4_NUM_B2C(sbi, sbi->s_journal->j_maxlen);
sbi->s_overhead = overhead;
smp_wmb();
free_page((unsigned long) buf);
return 0;
}
static void ext4_set_resv_clusters(struct super_block *sb)
{
ext4_fsblk_t resv_clusters;
struct ext4_sb_info *sbi = EXT4_SB(sb);
/*
* There's no need to reserve anything when we aren't using extents.
* The space estimates are exact, there are no unwritten extents,
* hole punching doesn't need new metadata... This is needed especially
* to keep ext2/3 backward compatibility.
*/
if (!ext4_has_feature_extents(sb))
return;
/*
* By default we reserve 2% or 4096 clusters, whichever is smaller.
* This should cover the situations where we can not afford to run
* out of space like for example punch hole, or converting
* unwritten extents in delalloc path. In most cases such
* allocation would require 1, or 2 blocks, higher numbers are
* very rare.
*/
resv_clusters = (ext4_blocks_count(sbi->s_es) >>
sbi->s_cluster_bits);
do_div(resv_clusters, 50);
resv_clusters = min_t(ext4_fsblk_t, resv_clusters, 4096);
atomic64_set(&sbi->s_resv_clusters, resv_clusters);
}
static int ext4_fill_super(struct super_block *sb, void *data, int silent)
{
char *orig_data = kstrdup(data, GFP_KERNEL);
struct buffer_head *bh;
struct ext4_super_block *es = NULL;
struct ext4_sb_info *sbi;
ext4_fsblk_t block;
ext4_fsblk_t sb_block = get_sb_block(&data);
ext4_fsblk_t logical_sb_block;
unsigned long offset = 0;
unsigned long journal_devnum = 0;
unsigned long def_mount_opts;
struct inode *root;
const char *descr;
int ret = -ENOMEM;
int blocksize, clustersize;
unsigned int db_count;
unsigned int i;
int needs_recovery, has_huge_files, has_bigalloc;
__u64 blocks_count;
int err = 0;
unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
ext4_group_t first_not_zeroed;
sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
if (!sbi)
goto out_free_orig;
sbi->s_blockgroup_lock =
kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
if (!sbi->s_blockgroup_lock) {
kfree(sbi);
goto out_free_orig;
}
sb->s_fs_info = sbi;
sbi->s_sb = sb;
sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;
sbi->s_sb_block = sb_block;
if (sb->s_bdev->bd_part)
sbi->s_sectors_written_start =
part_stat_read(sb->s_bdev->bd_part, sectors[1]);
/* Cleanup superblock name */
strreplace(sb->s_id, '/', '!');
/* -EINVAL is default */
ret = -EINVAL;
blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);
if (!blocksize) {
ext4_msg(sb, KERN_ERR, "unable to set blocksize");
goto out_fail;
}
/*
* The ext4 superblock will not be buffer aligned for other than 1kB
* block sizes. We need to calculate the offset from buffer start.
*/
if (blocksize != EXT4_MIN_BLOCK_SIZE) {
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
} else {
logical_sb_block = sb_block;
}
if (!(bh = sb_bread_unmovable(sb, logical_sb_block))) {
ext4_msg(sb, KERN_ERR, "unable to read superblock");
goto out_fail;
}
/*
* Note: s_es must be initialized as soon as possible because
* some ext4 macro-instructions depend on its value
*/
es = (struct ext4_super_block *) (bh->b_data + offset);
sbi->s_es = es;
sb->s_magic = le16_to_cpu(es->s_magic);
if (sb->s_magic != EXT4_SUPER_MAGIC)
goto cantfind_ext4;
sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written);
/* Warn if metadata_csum and gdt_csum are both set. */
if (ext4_has_feature_metadata_csum(sb) &&
ext4_has_feature_gdt_csum(sb))
ext4_warning(sb, "metadata_csum and uninit_bg are "
"redundant flags; please run fsck.");
/* Check for a known checksum algorithm */
if (!ext4_verify_csum_type(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"unknown checksum algorithm.");
silent = 1;
goto cantfind_ext4;
}
/* Load the checksum driver */
if (ext4_has_feature_metadata_csum(sb)) {
sbi->s_chksum_driver = crypto_alloc_shash("crc32c", 0, 0);
if (IS_ERR(sbi->s_chksum_driver)) {
ext4_msg(sb, KERN_ERR, "Cannot load crc32c driver.");
ret = PTR_ERR(sbi->s_chksum_driver);
sbi->s_chksum_driver = NULL;
goto failed_mount;
}
}
/* Check superblock checksum */
if (!ext4_superblock_csum_verify(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"invalid superblock checksum. Run e2fsck?");
silent = 1;
ret = -EFSBADCRC;
goto cantfind_ext4;
}
/* Precompute checksum seed for all metadata */
if (ext4_has_feature_csum_seed(sb))
sbi->s_csum_seed = le32_to_cpu(es->s_checksum_seed);
else if (ext4_has_metadata_csum(sb))
sbi->s_csum_seed = ext4_chksum(sbi, ~0, es->s_uuid,
sizeof(es->s_uuid));
/* Set defaults before we parse the mount options */
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
set_opt(sb, INIT_INODE_TABLE);
if (def_mount_opts & EXT4_DEFM_DEBUG)
set_opt(sb, DEBUG);
if (def_mount_opts & EXT4_DEFM_BSDGROUPS)
set_opt(sb, GRPID);
if (def_mount_opts & EXT4_DEFM_UID16)
set_opt(sb, NO_UID32);
/* xattr user namespace & acls are now defaulted on */
set_opt(sb, XATTR_USER);
#ifdef CONFIG_EXT4_FS_POSIX_ACL
set_opt(sb, POSIX_ACL);
#endif
/* don't forget to enable journal_csum when metadata_csum is enabled. */
if (ext4_has_metadata_csum(sb))
set_opt(sb, JOURNAL_CHECKSUM);
if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)
set_opt(sb, JOURNAL_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)
set_opt(sb, ORDERED_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)
set_opt(sb, WRITEBACK_DATA);
if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC)
set_opt(sb, ERRORS_PANIC);
else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE)
set_opt(sb, ERRORS_CONT);
else
set_opt(sb, ERRORS_RO);
/* block_validity enabled by default; disable with noblock_validity */
set_opt(sb, BLOCK_VALIDITY);
if (def_mount_opts & EXT4_DEFM_DISCARD)
set_opt(sb, DISCARD);
sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));
sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));
sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;
sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;
sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;
if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0)
set_opt(sb, BARRIER);
/*
* enable delayed allocation by default
* Use -o nodelalloc to turn it off
*/
if (!IS_EXT3_SB(sb) && !IS_EXT2_SB(sb) &&
((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0))
set_opt(sb, DELALLOC);
/*
* set default s_li_wait_mult for lazyinit, for the case there is
* no mount option specified.
*/
sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT;
if (!parse_options((char *) sbi->s_es->s_mount_opts, sb,
&journal_devnum, &journal_ioprio, 0)) {
ext4_msg(sb, KERN_WARNING,
"failed to parse options in superblock: %s",
sbi->s_es->s_mount_opts);
}
sbi->s_def_mount_opt = sbi->s_mount_opt;
if (!parse_options((char *) data, sb, &journal_devnum,
&journal_ioprio, 0))
goto failed_mount;
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
printk_once(KERN_WARNING "EXT4-fs: Warning: mounting "
"with data=journal disables delayed "
"allocation and O_DIRECT support!\n");
if (test_opt2(sb, EXPLICIT_DELALLOC)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
goto failed_mount;
}
if (test_opt(sb, DIOREAD_NOLOCK)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dioread_nolock");
goto failed_mount;
}
if (test_opt(sb, DAX)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dax");
goto failed_mount;
}
if (test_opt(sb, DELALLOC))
clear_opt(sb, DELALLOC);
} else {
sb->s_iflags |= SB_I_CGROUPWB;
}
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&
(ext4_has_compat_features(sb) ||
ext4_has_ro_compat_features(sb) ||
ext4_has_incompat_features(sb)))
ext4_msg(sb, KERN_WARNING,
"feature flags set on rev 0 fs, "
"running e2fsck is recommended");
if (es->s_creator_os == cpu_to_le32(EXT4_OS_HURD)) {
set_opt2(sb, HURD_COMPAT);
if (ext4_has_feature_64bit(sb)) {
ext4_msg(sb, KERN_ERR,
"The Hurd can't support 64-bit file systems");
goto failed_mount;
}
}
if (IS_EXT2_SB(sb)) {
if (ext2_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext2 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext2 due "
"to feature incompatibilities");
goto failed_mount;
}
}
if (IS_EXT3_SB(sb)) {
if (ext3_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext3 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext3 due "
"to feature incompatibilities");
goto failed_mount;
}
}
/*
* Check feature flags regardless of the revision level, since we
* previously didn't change the revision level when setting the flags,
* so there is a chance incompat flags are set on a rev 0 filesystem.
*/
if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY)))
goto failed_mount;
blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);
if (blocksize < EXT4_MIN_BLOCK_SIZE ||
blocksize > EXT4_MAX_BLOCK_SIZE) {
ext4_msg(sb, KERN_ERR,
"Unsupported filesystem blocksize %d", blocksize);
goto failed_mount;
}
if (sbi->s_mount_opt & EXT4_MOUNT_DAX) {
if (blocksize != PAGE_SIZE) {
ext4_msg(sb, KERN_ERR,
"error: unsupported blocksize for dax");
goto failed_mount;
}
if (!sb->s_bdev->bd_disk->fops->direct_access) {
ext4_msg(sb, KERN_ERR,
"error: device does not support dax");
goto failed_mount;
}
}
if (ext4_has_feature_encrypt(sb) && es->s_encryption_level) {
ext4_msg(sb, KERN_ERR, "Unsupported encryption level %d",
es->s_encryption_level);
goto failed_mount;
}
if (sb->s_blocksize != blocksize) {
/* Validate the filesystem blocksize */
if (!sb_set_blocksize(sb, blocksize)) {
ext4_msg(sb, KERN_ERR, "bad block size %d",
blocksize);
goto failed_mount;
}
brelse(bh);
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
bh = sb_bread_unmovable(sb, logical_sb_block);
if (!bh) {
ext4_msg(sb, KERN_ERR,
"Can't read superblock on 2nd try");
goto failed_mount;
}
es = (struct ext4_super_block *)(bh->b_data + offset);
sbi->s_es = es;
if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {
ext4_msg(sb, KERN_ERR,
"Magic mismatch, very weird!");
goto failed_mount;
}
}
has_huge_files = ext4_has_feature_huge_file(sb);
sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,
has_huge_files);
sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {
sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;
sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
} else {
sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||
(!is_power_of_2(sbi->s_inode_size)) ||
(sbi->s_inode_size > blocksize)) {
ext4_msg(sb, KERN_ERR,
"unsupported inode size: %d",
sbi->s_inode_size);
goto failed_mount;
}
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE)
sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2);
}
sbi->s_desc_size = le16_to_cpu(es->s_desc_size);
if (ext4_has_feature_64bit(sb)) {
if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||
sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||
!is_power_of_2(sbi->s_desc_size)) {
ext4_msg(sb, KERN_ERR,
"unsupported descriptor size %lu",
sbi->s_desc_size);
goto failed_mount;
}
} else
sbi->s_desc_size = EXT4_MIN_DESC_SIZE;
sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
if (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0)
goto cantfind_ext4;
sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb);
if (sbi->s_inodes_per_block == 0)
goto cantfind_ext4;
sbi->s_itb_per_group = sbi->s_inodes_per_group /
sbi->s_inodes_per_block;
sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb);
sbi->s_sbh = bh;
sbi->s_mount_state = le16_to_cpu(es->s_state);
sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));
sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));
for (i = 0; i < 4; i++)
sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);
sbi->s_def_hash_version = es->s_def_hash_version;
if (ext4_has_feature_dir_index(sb)) {
i = le32_to_cpu(es->s_flags);
if (i & EXT2_FLAGS_UNSIGNED_HASH)
sbi->s_hash_unsigned = 3;
else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {
#ifdef __CHAR_UNSIGNED__
if (!(sb->s_flags & MS_RDONLY))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);
sbi->s_hash_unsigned = 3;
#else
if (!(sb->s_flags & MS_RDONLY))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_SIGNED_HASH);
#endif
}
}
/* Handle clustersize */
clustersize = BLOCK_SIZE << le32_to_cpu(es->s_log_cluster_size);
has_bigalloc = ext4_has_feature_bigalloc(sb);
if (has_bigalloc) {
if (clustersize < blocksize) {
ext4_msg(sb, KERN_ERR,
"cluster size (%d) smaller than "
"block size (%d)", clustersize, blocksize);
goto failed_mount;
}
sbi->s_cluster_bits = le32_to_cpu(es->s_log_cluster_size) -
le32_to_cpu(es->s_log_block_size);
sbi->s_clusters_per_group =
le32_to_cpu(es->s_clusters_per_group);
if (sbi->s_clusters_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#clusters per group too big: %lu",
sbi->s_clusters_per_group);
goto failed_mount;
}
if (sbi->s_blocks_per_group !=
(sbi->s_clusters_per_group * (clustersize / blocksize))) {
ext4_msg(sb, KERN_ERR, "blocks per group (%lu) and "
"clusters per group (%lu) inconsistent",
sbi->s_blocks_per_group,
sbi->s_clusters_per_group);
goto failed_mount;
}
} else {
if (clustersize != blocksize) {
ext4_warning(sb, "fragment/cluster size (%d) != "
"block size (%d)", clustersize,
blocksize);
clustersize = blocksize;
}
if (sbi->s_blocks_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#blocks per group too big: %lu",
sbi->s_blocks_per_group);
goto failed_mount;
}
sbi->s_clusters_per_group = sbi->s_blocks_per_group;
sbi->s_cluster_bits = 0;
}
sbi->s_cluster_ratio = clustersize / blocksize;
if (sbi->s_inodes_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#inodes per group too big: %lu",
sbi->s_inodes_per_group);
goto failed_mount;
}
/* Do we have standard group size of clustersize * 8 blocks ? */
if (sbi->s_blocks_per_group == clustersize << 3)
set_opt2(sb, STD_GROUP_SIZE);
/*
* Test whether we have more sectors than will fit in sector_t,
* and whether the max offset is addressable by the page cache.
*/
err = generic_check_addressable(sb->s_blocksize_bits,
ext4_blocks_count(es));
if (err) {
ext4_msg(sb, KERN_ERR, "filesystem"
" too large to mount safely on this system");
if (sizeof(sector_t) < 8)
ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled");
goto failed_mount;
}
if (EXT4_BLOCKS_PER_GROUP(sb) == 0)
goto cantfind_ext4;
/* check blocks count against device size */
blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
if (blocks_count && ext4_blocks_count(es) > blocks_count) {
ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu "
"exceeds size of device (%llu blocks)",
ext4_blocks_count(es), blocks_count);
goto failed_mount;
}
/*
* It makes no sense for the first data block to be beyond the end
* of the filesystem.
*/
if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) {
ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
"block %u is beyond end of filesystem (%llu)",
le32_to_cpu(es->s_first_data_block),
ext4_blocks_count(es));
goto failed_mount;
}
blocks_count = (ext4_blocks_count(es) -
le32_to_cpu(es->s_first_data_block) +
EXT4_BLOCKS_PER_GROUP(sb) - 1);
do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));
if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) {
ext4_msg(sb, KERN_WARNING, "groups count too large: %u "
"(block count %llu, first data block %u, "
"blocks per group %lu)", sbi->s_groups_count,
ext4_blocks_count(es),
le32_to_cpu(es->s_first_data_block),
EXT4_BLOCKS_PER_GROUP(sb));
goto failed_mount;
}
sbi->s_groups_count = blocks_count;
sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
(EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /
EXT4_DESC_PER_BLOCK(sb);
sbi->s_group_desc = ext4_kvmalloc(db_count *
sizeof(struct buffer_head *),
GFP_KERNEL);
if (sbi->s_group_desc == NULL) {
ext4_msg(sb, KERN_ERR, "not enough memory");
ret = -ENOMEM;
goto failed_mount;
}
bgl_lock_init(sbi->s_blockgroup_lock);
for (i = 0; i < db_count; i++) {
block = descriptor_loc(sb, logical_sb_block, i);
sbi->s_group_desc[i] = sb_bread_unmovable(sb, block);
if (!sbi->s_group_desc[i]) {
ext4_msg(sb, KERN_ERR,
"can't read group descriptor %d", i);
db_count = i;
goto failed_mount2;
}
}
if (!ext4_check_descriptors(sb, &first_not_zeroed)) {
ext4_msg(sb, KERN_ERR, "group descriptors corrupted!");
ret = -EFSCORRUPTED;
goto failed_mount2;
}
sbi->s_gdb_count = db_count;
get_random_bytes(&sbi->s_next_generation, sizeof(u32));
spin_lock_init(&sbi->s_next_gen_lock);
setup_timer(&sbi->s_err_report, print_daily_error_info,
(unsigned long) sb);
/* Register extent status tree shrinker */
if (ext4_es_register_shrinker(sbi))
goto failed_mount3;
sbi->s_stripe = ext4_get_stripe_size(sbi);
sbi->s_extent_max_zeroout_kb = 32;
/*
* set up enough so that it can read an inode
*/
sb->s_op = &ext4_sops;
sb->s_export_op = &ext4_export_ops;
sb->s_xattr = ext4_xattr_handlers;
#ifdef CONFIG_QUOTA
sb->dq_op = &ext4_quota_operations;
if (ext4_has_feature_quota(sb))
sb->s_qcop = &dquot_quotactl_sysfile_ops;
else
sb->s_qcop = &ext4_qctl_operations;
sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;
#endif
memcpy(sb->s_uuid, es->s_uuid, sizeof(es->s_uuid));
INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */
mutex_init(&sbi->s_orphan_lock);
sb->s_root = NULL;
needs_recovery = (es->s_last_orphan != 0 ||
ext4_has_feature_journal_needs_recovery(sb));
if (ext4_has_feature_mmp(sb) && !(sb->s_flags & MS_RDONLY))
if (ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block)))
goto failed_mount3a;
/*
* The first inode we look at is the journal inode. Don't try
* root first: it may be modified in the journal!
*/
if (!test_opt(sb, NOLOAD) && ext4_has_feature_journal(sb)) {
if (ext4_load_journal(sb, es, journal_devnum))
goto failed_mount3a;
} else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) &&
ext4_has_feature_journal_needs_recovery(sb)) {
ext4_msg(sb, KERN_ERR, "required journal recovery "
"suppressed and not mounted read-only");
goto failed_mount_wq;
} else {
/* Nojournal mode, all journal mount options are illegal */
if (test_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_checksum, fs mounted w/o journal");
goto failed_mount_wq;
}
if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_async_commit, fs mounted w/o journal");
goto failed_mount_wq;
}
if (sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"commit=%lu, fs mounted w/o journal",
sbi->s_commit_interval / HZ);
goto failed_mount_wq;
}
if (EXT4_MOUNT_DATA_FLAGS &
(sbi->s_mount_opt ^ sbi->s_def_mount_opt)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"data=, fs mounted w/o journal");
goto failed_mount_wq;
}
sbi->s_def_mount_opt &= EXT4_MOUNT_JOURNAL_CHECKSUM;
clear_opt(sb, JOURNAL_CHECKSUM);
clear_opt(sb, DATA_FLAGS);
sbi->s_journal = NULL;
needs_recovery = 0;
goto no_journal;
}
if (ext4_has_feature_64bit(sb) &&
!jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_64BIT)) {
ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature");
goto failed_mount_wq;
}
if (!set_journal_csum_feature_set(sb)) {
ext4_msg(sb, KERN_ERR, "Failed to set journal checksum "
"feature set");
goto failed_mount_wq;
}
/* We have now updated the journal if required, so we can
* validate the data journaling mode. */
switch (test_opt(sb, DATA_FLAGS)) {
case 0:
/* No mode set, assume a default based on the journal
* capabilities: ORDERED_DATA if the journal can
* cope, else JOURNAL_DATA
*/
if (jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE))
set_opt(sb, ORDERED_DATA);
else
set_opt(sb, JOURNAL_DATA);
break;
case EXT4_MOUNT_ORDERED_DATA:
case EXT4_MOUNT_WRITEBACK_DATA:
if (!jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
ext4_msg(sb, KERN_ERR, "Journal does not support "
"requested data journaling mode");
goto failed_mount_wq;
}
default:
break;
}
set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
sbi->s_journal->j_commit_callback = ext4_journal_commit_callback;
no_journal:
if (ext4_mballoc_ready) {
sbi->s_mb_cache = ext4_xattr_create_cache(sb->s_id);
if (!sbi->s_mb_cache) {
ext4_msg(sb, KERN_ERR, "Failed to create an mb_cache");
goto failed_mount_wq;
}
}
if ((DUMMY_ENCRYPTION_ENABLED(sbi) || ext4_has_feature_encrypt(sb)) &&
(blocksize != PAGE_CACHE_SIZE)) {
ext4_msg(sb, KERN_ERR,
"Unsupported blocksize for fs encryption");
goto failed_mount_wq;
}
if (DUMMY_ENCRYPTION_ENABLED(sbi) && !(sb->s_flags & MS_RDONLY) &&
!ext4_has_feature_encrypt(sb)) {
ext4_set_feature_encrypt(sb);
ext4_commit_super(sb, 1);
}
/*
* Get the # of file system overhead blocks from the
* superblock if present.
*/
if (es->s_overhead_clusters)
sbi->s_overhead = le32_to_cpu(es->s_overhead_clusters);
else {
err = ext4_calculate_overhead(sb);
if (err)
goto failed_mount_wq;
}
/*
* The maximum number of concurrent works can be high and
* concurrency isn't really necessary. Limit it to 1.
*/
EXT4_SB(sb)->rsv_conversion_wq =
alloc_workqueue("ext4-rsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
if (!EXT4_SB(sb)->rsv_conversion_wq) {
printk(KERN_ERR "EXT4-fs: failed to create workqueue\n");
ret = -ENOMEM;
goto failed_mount4;
}
/*
* The jbd2_journal_load will have done any necessary log recovery,
* so we can safely mount the rest of the filesystem now.
*/
root = ext4_iget(sb, EXT4_ROOT_INO);
if (IS_ERR(root)) {
ext4_msg(sb, KERN_ERR, "get root inode failed");
ret = PTR_ERR(root);
root = NULL;
goto failed_mount4;
}
if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck");
iput(root);
goto failed_mount4;
}
sb->s_root = d_make_root(root);
if (!sb->s_root) {
ext4_msg(sb, KERN_ERR, "get root dentry failed");
ret = -ENOMEM;
goto failed_mount4;
}
if (ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY))
sb->s_flags |= MS_RDONLY;
/* determine the minimum size of new large inodes, if present */
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
if (ext4_has_feature_extra_isize(sb)) {
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_want_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_want_extra_isize);
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_min_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_min_extra_isize);
}
}
/* Check if enough inode space is available */
if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize >
sbi->s_inode_size) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
ext4_msg(sb, KERN_INFO, "required extra inode space not"
"available");
}
ext4_set_resv_clusters(sb);
err = ext4_setup_system_zone(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize system "
"zone (%d)", err);
goto failed_mount4a;
}
ext4_ext_init(sb);
err = ext4_mb_init(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)",
err);
goto failed_mount5;
}
block = ext4_count_free_clusters(sb);
ext4_free_blocks_count_set(sbi->s_es,
EXT4_C2B(sbi, block));
err = percpu_counter_init(&sbi->s_freeclusters_counter, block,
GFP_KERNEL);
if (!err) {
unsigned long freei = ext4_count_free_inodes(sb);
sbi->s_es->s_free_inodes_count = cpu_to_le32(freei);
err = percpu_counter_init(&sbi->s_freeinodes_counter, freei,
GFP_KERNEL);
}
if (!err)
err = percpu_counter_init(&sbi->s_dirs_counter,
ext4_count_dirs(sb), GFP_KERNEL);
if (!err)
err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0,
GFP_KERNEL);
if (err) {
ext4_msg(sb, KERN_ERR, "insufficient memory");
goto failed_mount6;
}
if (ext4_has_feature_flex_bg(sb))
if (!ext4_fill_flex_info(sb)) {
ext4_msg(sb, KERN_ERR,
"unable to initialize "
"flex_bg meta info!");
goto failed_mount6;
}
err = ext4_register_li_request(sb, first_not_zeroed);
if (err)
goto failed_mount6;
err = ext4_register_sysfs(sb);
if (err)
goto failed_mount7;
#ifdef CONFIG_QUOTA
/* Enable quota usage during mount. */
if (ext4_has_feature_quota(sb) && !(sb->s_flags & MS_RDONLY)) {
err = ext4_enable_quotas(sb);
if (err)
goto failed_mount8;
}
#endif /* CONFIG_QUOTA */
EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;
ext4_orphan_cleanup(sb, es);
EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;
if (needs_recovery) {
ext4_msg(sb, KERN_INFO, "recovery complete");
ext4_mark_recovery_complete(sb, es);
}
if (EXT4_SB(sb)->s_journal) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
descr = " journalled data mode";
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
descr = " ordered data mode";
else
descr = " writeback data mode";
} else
descr = "out journal";
if (test_opt(sb, DISCARD)) {
struct request_queue *q = bdev_get_queue(sb->s_bdev);
if (!blk_queue_discard(q))
ext4_msg(sb, KERN_WARNING,
"mounting with \"discard\" option, but "
"the device does not support discard");
}
if (___ratelimit(&ext4_mount_msg_ratelimit, "EXT4-fs mount"))
ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. "
"Opts: %s%s%s", descr, sbi->s_es->s_mount_opts,
*sbi->s_es->s_mount_opts ? "; " : "", orig_data);
if (es->s_error_count)
mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */
/* Enable message ratelimiting. Default is 10 messages per 5 secs. */
ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10);
kfree(orig_data);
return 0;
cantfind_ext4:
if (!silent)
ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem");
goto failed_mount;
#ifdef CONFIG_QUOTA
failed_mount8:
ext4_unregister_sysfs(sb);
#endif
failed_mount7:
ext4_unregister_li_request(sb);
failed_mount6:
ext4_mb_release(sb);
if (sbi->s_flex_groups)
kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
failed_mount5:
ext4_ext_release(sb);
ext4_release_system_zone(sb);
failed_mount4a:
dput(sb->s_root);
sb->s_root = NULL;
failed_mount4:
ext4_msg(sb, KERN_ERR, "mount failed");
if (EXT4_SB(sb)->rsv_conversion_wq)
destroy_workqueue(EXT4_SB(sb)->rsv_conversion_wq);
failed_mount_wq:
if (sbi->s_journal) {
jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
}
failed_mount3a:
ext4_es_unregister_shrinker(sbi);
failed_mount3:
del_timer_sync(&sbi->s_err_report);
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
failed_mount2:
for (i = 0; i < db_count; i++)
brelse(sbi->s_group_desc[i]);
kvfree(sbi->s_group_desc);
failed_mount:
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
ext4_blkdev_remove(sbi);
brelse(bh);
out_fail:
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
out_free_orig:
kfree(orig_data);
return err ? err : ret;
}
/*
* Setup any per-fs journal parameters now. We'll do this both on
* initial mount, once the journal has been initialised but before we've
* done any recovery; and again on any subsequent remount.
*/
static void ext4_init_journal_params(struct super_block *sb, journal_t *journal)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
journal->j_commit_interval = sbi->s_commit_interval;
journal->j_min_batch_time = sbi->s_min_batch_time;
journal->j_max_batch_time = sbi->s_max_batch_time;
write_lock(&journal->j_state_lock);
if (test_opt(sb, BARRIER))
journal->j_flags |= JBD2_BARRIER;
else
journal->j_flags &= ~JBD2_BARRIER;
if (test_opt(sb, DATA_ERR_ABORT))
journal->j_flags |= JBD2_ABORT_ON_SYNCDATA_ERR;
else
journal->j_flags &= ~JBD2_ABORT_ON_SYNCDATA_ERR;
write_unlock(&journal->j_state_lock);
}
static journal_t *ext4_get_journal(struct super_block *sb,
unsigned int journal_inum)
{
struct inode *journal_inode;
journal_t *journal;
BUG_ON(!ext4_has_feature_journal(sb));
/* First, test for the existence of a valid inode on disk. Bad
* things happen if we iget() an unused inode, as the subsequent
* iput() will try to delete it. */
journal_inode = ext4_iget(sb, journal_inum);
if (IS_ERR(journal_inode)) {
ext4_msg(sb, KERN_ERR, "no journal found");
return NULL;
}
if (!journal_inode->i_nlink) {
make_bad_inode(journal_inode);
iput(journal_inode);
ext4_msg(sb, KERN_ERR, "journal inode is deleted");
return NULL;
}
jbd_debug(2, "Journal inode found at %p: %lld bytes\n",
journal_inode, journal_inode->i_size);
if (!S_ISREG(journal_inode->i_mode)) {
ext4_msg(sb, KERN_ERR, "invalid journal inode");
iput(journal_inode);
return NULL;
}
journal = jbd2_journal_init_inode(journal_inode);
if (!journal) {
ext4_msg(sb, KERN_ERR, "Could not load journal inode");
iput(journal_inode);
return NULL;
}
journal->j_private = sb;
ext4_init_journal_params(sb, journal);
return journal;
}
static journal_t *ext4_get_dev_journal(struct super_block *sb,
dev_t j_dev)
{
struct buffer_head *bh;
journal_t *journal;
ext4_fsblk_t start;
ext4_fsblk_t len;
int hblock, blocksize;
ext4_fsblk_t sb_block;
unsigned long offset;
struct ext4_super_block *es;
struct block_device *bdev;
BUG_ON(!ext4_has_feature_journal(sb));
bdev = ext4_blkdev_get(j_dev, sb);
if (bdev == NULL)
return NULL;
blocksize = sb->s_blocksize;
hblock = bdev_logical_block_size(bdev);
if (blocksize < hblock) {
ext4_msg(sb, KERN_ERR,
"blocksize too small for journal device");
goto out_bdev;
}
sb_block = EXT4_MIN_BLOCK_SIZE / blocksize;
offset = EXT4_MIN_BLOCK_SIZE % blocksize;
set_blocksize(bdev, blocksize);
if (!(bh = __bread(bdev, sb_block, blocksize))) {
ext4_msg(sb, KERN_ERR, "couldn't read superblock of "
"external journal");
goto out_bdev;
}
es = (struct ext4_super_block *) (bh->b_data + offset);
if ((le16_to_cpu(es->s_magic) != EXT4_SUPER_MAGIC) ||
!(le32_to_cpu(es->s_feature_incompat) &
EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)) {
ext4_msg(sb, KERN_ERR, "external journal has "
"bad superblock");
brelse(bh);
goto out_bdev;
}
if ((le32_to_cpu(es->s_feature_ro_compat) &
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) &&
es->s_checksum != ext4_superblock_csum(sb, es)) {
ext4_msg(sb, KERN_ERR, "external journal has "
"corrupt superblock");
brelse(bh);
goto out_bdev;
}
if (memcmp(EXT4_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) {
ext4_msg(sb, KERN_ERR, "journal UUID does not match");
brelse(bh);
goto out_bdev;
}
len = ext4_blocks_count(es);
start = sb_block + 1;
brelse(bh); /* we're done with the superblock */
journal = jbd2_journal_init_dev(bdev, sb->s_bdev,
start, len, blocksize);
if (!journal) {
ext4_msg(sb, KERN_ERR, "failed to create device journal");
goto out_bdev;
}
journal->j_private = sb;
ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &journal->j_sb_buffer);
wait_on_buffer(journal->j_sb_buffer);
if (!buffer_uptodate(journal->j_sb_buffer)) {
ext4_msg(sb, KERN_ERR, "I/O error on journal device");
goto out_journal;
}
if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) {
ext4_msg(sb, KERN_ERR, "External journal has more than one "
"user (unsupported) - %d",
be32_to_cpu(journal->j_superblock->s_nr_users));
goto out_journal;
}
EXT4_SB(sb)->journal_bdev = bdev;
ext4_init_journal_params(sb, journal);
return journal;
out_journal:
jbd2_journal_destroy(journal);
out_bdev:
ext4_blkdev_put(bdev);
return NULL;
}
static int ext4_load_journal(struct super_block *sb,
struct ext4_super_block *es,
unsigned long journal_devnum)
{
journal_t *journal;
unsigned int journal_inum = le32_to_cpu(es->s_journal_inum);
dev_t journal_dev;
int err = 0;
int really_read_only;
BUG_ON(!ext4_has_feature_journal(sb));
if (journal_devnum &&
journal_devnum != le32_to_cpu(es->s_journal_dev)) {
ext4_msg(sb, KERN_INFO, "external journal device major/minor "
"numbers have changed");
journal_dev = new_decode_dev(journal_devnum);
} else
journal_dev = new_decode_dev(le32_to_cpu(es->s_journal_dev));
really_read_only = bdev_read_only(sb->s_bdev);
/*
* Are we loading a blank journal or performing recovery after a
* crash? For recovery, we need to check in advance whether we
* can get read-write access to the device.
*/
if (ext4_has_feature_journal_needs_recovery(sb)) {
if (sb->s_flags & MS_RDONLY) {
ext4_msg(sb, KERN_INFO, "INFO: recovery "
"required on readonly filesystem");
if (really_read_only) {
ext4_msg(sb, KERN_ERR, "write access "
"unavailable, cannot proceed");
return -EROFS;
}
ext4_msg(sb, KERN_INFO, "write access will "
"be enabled during recovery");
}
}
if (journal_inum && journal_dev) {
ext4_msg(sb, KERN_ERR, "filesystem has both journal "
"and inode journals!");
return -EINVAL;
}
if (journal_inum) {
if (!(journal = ext4_get_journal(sb, journal_inum)))
return -EINVAL;
} else {
if (!(journal = ext4_get_dev_journal(sb, journal_dev)))
return -EINVAL;
}
if (!(journal->j_flags & JBD2_BARRIER))
ext4_msg(sb, KERN_INFO, "barriers disabled");
if (!ext4_has_feature_journal_needs_recovery(sb))
err = jbd2_journal_wipe(journal, !really_read_only);
if (!err) {
char *save = kmalloc(EXT4_S_ERR_LEN, GFP_KERNEL);
if (save)
memcpy(save, ((char *) es) +
EXT4_S_ERR_START, EXT4_S_ERR_LEN);
err = jbd2_journal_load(journal);
if (save)
memcpy(((char *) es) + EXT4_S_ERR_START,
save, EXT4_S_ERR_LEN);
kfree(save);
}
if (err) {
ext4_msg(sb, KERN_ERR, "error loading journal");
jbd2_journal_destroy(journal);
return err;
}
EXT4_SB(sb)->s_journal = journal;
ext4_clear_journal_err(sb, es);
if (!really_read_only && journal_devnum &&
journal_devnum != le32_to_cpu(es->s_journal_dev)) {
es->s_journal_dev = cpu_to_le32(journal_devnum);
/* Make sure we flush the recovery flag to disk. */
ext4_commit_super(sb, 1);
}
return 0;
}
static int ext4_commit_super(struct super_block *sb, int sync)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
struct buffer_head *sbh = EXT4_SB(sb)->s_sbh;
int error = 0;
if (!sbh || block_device_ejected(sb))
return error;
if (buffer_write_io_error(sbh)) {
/*
* Oh, dear. A previous attempt to write the
* superblock failed. This could happen because the
* USB device was yanked out. Or it could happen to
* be a transient write error and maybe the block will
* be remapped. Nothing we can do but to retry the
* write and hope for the best.
*/
ext4_msg(sb, KERN_ERR, "previous I/O error to "
"superblock detected");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
}
/*
* If the file system is mounted read-only, don't update the
* superblock write time. This avoids updating the superblock
* write time when we are mounting the root file system
* read/only but we need to replay the journal; at that point,
* for people who are east of GMT and who make their clock
* tick in localtime for Windows bug-for-bug compatibility,
* the clock is set in the future, and this will cause e2fsck
* to complain and force a full file system check.
*/
if (!(sb->s_flags & MS_RDONLY))
es->s_wtime = cpu_to_le32(get_seconds());
if (sb->s_bdev->bd_part)
es->s_kbytes_written =
cpu_to_le64(EXT4_SB(sb)->s_kbytes_written +
((part_stat_read(sb->s_bdev->bd_part, sectors[1]) -
EXT4_SB(sb)->s_sectors_written_start) >> 1));
else
es->s_kbytes_written =
cpu_to_le64(EXT4_SB(sb)->s_kbytes_written);
if (percpu_counter_initialized(&EXT4_SB(sb)->s_freeclusters_counter))
ext4_free_blocks_count_set(es,
EXT4_C2B(EXT4_SB(sb), percpu_counter_sum_positive(
&EXT4_SB(sb)->s_freeclusters_counter)));
if (percpu_counter_initialized(&EXT4_SB(sb)->s_freeinodes_counter))
es->s_free_inodes_count =
cpu_to_le32(percpu_counter_sum_positive(
&EXT4_SB(sb)->s_freeinodes_counter));
BUFFER_TRACE(sbh, "marking dirty");
ext4_superblock_csum_set(sb);
mark_buffer_dirty(sbh);
if (sync) {
error = __sync_dirty_buffer(sbh,
test_opt(sb, BARRIER) ? WRITE_FUA : WRITE_SYNC);
if (error)
return error;
error = buffer_write_io_error(sbh);
if (error) {
ext4_msg(sb, KERN_ERR, "I/O error while writing "
"superblock");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
}
}
return error;
}
/*
* Have we just finished recovery? If so, and if we are mounting (or
* remounting) the filesystem readonly, then we will end up with a
* consistent fs on disk. Record that fact.
*/
static void ext4_mark_recovery_complete(struct super_block *sb,
struct ext4_super_block *es)
{
journal_t *journal = EXT4_SB(sb)->s_journal;
if (!ext4_has_feature_journal(sb)) {
BUG_ON(journal != NULL);
return;
}
jbd2_journal_lock_updates(journal);
if (jbd2_journal_flush(journal) < 0)
goto out;
if (ext4_has_feature_journal_needs_recovery(sb) &&
sb->s_flags & MS_RDONLY) {
ext4_clear_feature_journal_needs_recovery(sb);
ext4_commit_super(sb, 1);
}
out:
jbd2_journal_unlock_updates(journal);
}
/*
* If we are mounting (or read-write remounting) a filesystem whose journal
* has recorded an error from a previous lifetime, move that error to the
* main filesystem now.
*/
static void ext4_clear_journal_err(struct super_block *sb,
struct ext4_super_block *es)
{
journal_t *journal;
int j_errno;
const char *errstr;
BUG_ON(!ext4_has_feature_journal(sb));
journal = EXT4_SB(sb)->s_journal;
/*
* Now check for any error status which may have been recorded in the
* journal by a prior ext4_error() or ext4_abort()
*/
j_errno = jbd2_journal_errno(journal);
if (j_errno) {
char nbuf[16];
errstr = ext4_decode_error(sb, j_errno, nbuf);
ext4_warning(sb, "Filesystem error recorded "
"from previous mount: %s", errstr);
ext4_warning(sb, "Marking fs in need of filesystem check.");
EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
ext4_commit_super(sb, 1);
jbd2_journal_clear_err(journal);
jbd2_journal_update_sb_errno(journal);
}
}
/*
* Force the running and committing transactions to commit,
* and wait on the commit.
*/
int ext4_force_commit(struct super_block *sb)
{
journal_t *journal;
if (sb->s_flags & MS_RDONLY)
return 0;
journal = EXT4_SB(sb)->s_journal;
return ext4_journal_force_commit(journal);
}
static int ext4_sync_fs(struct super_block *sb, int wait)
{
int ret = 0;
tid_t target;
bool needs_barrier = false;
struct ext4_sb_info *sbi = EXT4_SB(sb);
trace_ext4_sync_fs(sb, wait);
flush_workqueue(sbi->rsv_conversion_wq);
/*
* Writeback quota in non-journalled quota case - journalled quota has
* no dirty dquots
*/
dquot_writeback_dquots(sb, -1);
/*
* Data writeback is possible w/o journal transaction, so barrier must
* being sent at the end of the function. But we can skip it if
* transaction_commit will do it for us.
*/
if (sbi->s_journal) {
target = jbd2_get_latest_transaction(sbi->s_journal);
if (wait && sbi->s_journal->j_flags & JBD2_BARRIER &&
!jbd2_trans_will_send_data_barrier(sbi->s_journal, target))
needs_barrier = true;
if (jbd2_journal_start_commit(sbi->s_journal, &target)) {
if (wait)
ret = jbd2_log_wait_commit(sbi->s_journal,
target);
}
} else if (wait && test_opt(sb, BARRIER))
needs_barrier = true;
if (needs_barrier) {
int err;
err = blkdev_issue_flush(sb->s_bdev, GFP_KERNEL, NULL);
if (!ret)
ret = err;
}
return ret;
}
/*
* LVM calls this function before a (read-only) snapshot is created. This
* gives us a chance to flush the journal completely and mark the fs clean.
*
* Note that only this function cannot bring a filesystem to be in a clean
* state independently. It relies on upper layer to stop all data & metadata
* modifications.
*/
static int ext4_freeze(struct super_block *sb)
{
int error = 0;
journal_t *journal;
if (sb->s_flags & MS_RDONLY)
return 0;
journal = EXT4_SB(sb)->s_journal;
if (journal) {
/* Now we set up the journal barrier. */
jbd2_journal_lock_updates(journal);
/*
* Don't clear the needs_recovery flag if we failed to
* flush the journal.
*/
error = jbd2_journal_flush(journal);
if (error < 0)
goto out;
/* Journal blocked and flushed, clear needs_recovery flag. */
ext4_clear_feature_journal_needs_recovery(sb);
}
error = ext4_commit_super(sb, 1);
out:
if (journal)
/* we rely on upper layer to stop further updates */
jbd2_journal_unlock_updates(journal);
return error;
}
/*
* Called by LVM after the snapshot is done. We need to reset the RECOVER
* flag here, even though the filesystem is not technically dirty yet.
*/
static int ext4_unfreeze(struct super_block *sb)
{
if (sb->s_flags & MS_RDONLY)
return 0;
if (EXT4_SB(sb)->s_journal) {
/* Reset the needs_recovery flag before the fs is unlocked. */
ext4_set_feature_journal_needs_recovery(sb);
}
ext4_commit_super(sb, 1);
return 0;
}
/*
* Structure to save mount options for ext4_remount's benefit
*/
struct ext4_mount_options {
unsigned long s_mount_opt;
unsigned long s_mount_opt2;
kuid_t s_resuid;
kgid_t s_resgid;
unsigned long s_commit_interval;
u32 s_min_batch_time, s_max_batch_time;
#ifdef CONFIG_QUOTA
int s_jquota_fmt;
char *s_qf_names[EXT4_MAXQUOTAS];
#endif
};
static int ext4_remount(struct super_block *sb, int *flags, char *data)
{
struct ext4_super_block *es;
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned long old_sb_flags;
struct ext4_mount_options old_opts;
int enable_quota = 0;
ext4_group_t g;
unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
int err = 0;
#ifdef CONFIG_QUOTA
int i, j;
#endif
char *orig_data = kstrdup(data, GFP_KERNEL);
/* Store the original options */
old_sb_flags = sb->s_flags;
old_opts.s_mount_opt = sbi->s_mount_opt;
old_opts.s_mount_opt2 = sbi->s_mount_opt2;
old_opts.s_resuid = sbi->s_resuid;
old_opts.s_resgid = sbi->s_resgid;
old_opts.s_commit_interval = sbi->s_commit_interval;
old_opts.s_min_batch_time = sbi->s_min_batch_time;
old_opts.s_max_batch_time = sbi->s_max_batch_time;
#ifdef CONFIG_QUOTA
old_opts.s_jquota_fmt = sbi->s_jquota_fmt;
for (i = 0; i < EXT4_MAXQUOTAS; i++)
if (sbi->s_qf_names[i]) {
old_opts.s_qf_names[i] = kstrdup(sbi->s_qf_names[i],
GFP_KERNEL);
if (!old_opts.s_qf_names[i]) {
for (j = 0; j < i; j++)
kfree(old_opts.s_qf_names[j]);
kfree(orig_data);
return -ENOMEM;
}
} else
old_opts.s_qf_names[i] = NULL;
#endif
if (sbi->s_journal && sbi->s_journal->j_task->io_context)
journal_ioprio = sbi->s_journal->j_task->io_context->ioprio;
if (!parse_options(data, sb, NULL, &journal_ioprio, 1)) {
err = -EINVAL;
goto restore_opts;
}
if ((old_opts.s_mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) ^
test_opt(sb, JOURNAL_CHECKSUM)) {
ext4_msg(sb, KERN_ERR, "changing journal_checksum "
"during remount not supported; ignoring");
sbi->s_mount_opt ^= EXT4_MOUNT_JOURNAL_CHECKSUM;
}
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
if (test_opt2(sb, EXPLICIT_DELALLOC)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
err = -EINVAL;
goto restore_opts;
}
if (test_opt(sb, DIOREAD_NOLOCK)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dioread_nolock");
err = -EINVAL;
goto restore_opts;
}
if (test_opt(sb, DAX)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dax");
err = -EINVAL;
goto restore_opts;
}
}
if ((sbi->s_mount_opt ^ old_opts.s_mount_opt) & EXT4_MOUNT_DAX) {
ext4_msg(sb, KERN_WARNING, "warning: refusing change of "
"dax flag with busy inodes while remounting");
sbi->s_mount_opt ^= EXT4_MOUNT_DAX;
}
if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED)
ext4_abort(sb, "Abort forced by user");
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
es = sbi->s_es;
if (sbi->s_journal) {
ext4_init_journal_params(sb, sbi->s_journal);
set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
}
if (*flags & MS_LAZYTIME)
sb->s_flags |= MS_LAZYTIME;
if ((*flags & MS_RDONLY) != (sb->s_flags & MS_RDONLY)) {
if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED) {
err = -EROFS;
goto restore_opts;
}
if (*flags & MS_RDONLY) {
err = sync_filesystem(sb);
if (err < 0)
goto restore_opts;
err = dquot_suspend(sb, -1);
if (err < 0)
goto restore_opts;
/*
* First of all, the unconditional stuff we have to do
* to disable replay of the journal when we next remount
*/
sb->s_flags |= MS_RDONLY;
/*
* OK, test if we are remounting a valid rw partition
* readonly, and if so set the rdonly flag and then
* mark the partition as valid again.
*/
if (!(es->s_state & cpu_to_le16(EXT4_VALID_FS)) &&
(sbi->s_mount_state & EXT4_VALID_FS))
es->s_state = cpu_to_le16(sbi->s_mount_state);
if (sbi->s_journal)
ext4_mark_recovery_complete(sb, es);
} else {
/* Make sure we can mount this feature set readwrite */
if (ext4_has_feature_readonly(sb) ||
!ext4_feature_set_ok(sb, 0)) {
err = -EROFS;
goto restore_opts;
}
/*
* Make sure the group descriptor checksums
* are sane. If they aren't, refuse to remount r/w.
*/
for (g = 0; g < sbi->s_groups_count; g++) {
struct ext4_group_desc *gdp =
ext4_get_group_desc(sb, g, NULL);
if (!ext4_group_desc_csum_verify(sb, g, gdp)) {
ext4_msg(sb, KERN_ERR,
"ext4_remount: Checksum for group %u failed (%u!=%u)",
g, le16_to_cpu(ext4_group_desc_csum(sb, g, gdp)),
le16_to_cpu(gdp->bg_checksum));
err = -EFSBADCRC;
goto restore_opts;
}
}
/*
* If we have an unprocessed orphan list hanging
* around from a previously readonly bdev mount,
* require a full umount/remount for now.
*/
if (es->s_last_orphan) {
ext4_msg(sb, KERN_WARNING, "Couldn't "
"remount RDWR because of unprocessed "
"orphan inode list. Please "
"umount/remount instead");
err = -EINVAL;
goto restore_opts;
}
/*
* Mounting a RDONLY partition read-write, so reread
* and store the current valid flag. (It may have
* been changed by e2fsck since we originally mounted
* the partition.)
*/
if (sbi->s_journal)
ext4_clear_journal_err(sb, es);
sbi->s_mount_state = le16_to_cpu(es->s_state);
if (!ext4_setup_super(sb, es, 0))
sb->s_flags &= ~MS_RDONLY;
if (ext4_has_feature_mmp(sb))
if (ext4_multi_mount_protect(sb,
le64_to_cpu(es->s_mmp_block))) {
err = -EROFS;
goto restore_opts;
}
enable_quota = 1;
}
}
/*
* Reinitialize lazy itable initialization thread based on
* current settings
*/
if ((sb->s_flags & MS_RDONLY) || !test_opt(sb, INIT_INODE_TABLE))
ext4_unregister_li_request(sb);
else {
ext4_group_t first_not_zeroed;
first_not_zeroed = ext4_has_uninit_itable(sb);
ext4_register_li_request(sb, first_not_zeroed);
}
ext4_setup_system_zone(sb);
if (sbi->s_journal == NULL && !(old_sb_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
#ifdef CONFIG_QUOTA
/* Release old quota file names */
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(old_opts.s_qf_names[i]);
if (enable_quota) {
if (sb_any_quota_suspended(sb))
dquot_resume(sb, -1);
else if (ext4_has_feature_quota(sb)) {
err = ext4_enable_quotas(sb);
if (err)
goto restore_opts;
}
}
#endif
*flags = (*flags & ~MS_LAZYTIME) | (sb->s_flags & MS_LAZYTIME);
ext4_msg(sb, KERN_INFO, "re-mounted. Opts: %s", orig_data);
kfree(orig_data);
return 0;
restore_opts:
sb->s_flags = old_sb_flags;
sbi->s_mount_opt = old_opts.s_mount_opt;
sbi->s_mount_opt2 = old_opts.s_mount_opt2;
sbi->s_resuid = old_opts.s_resuid;
sbi->s_resgid = old_opts.s_resgid;
sbi->s_commit_interval = old_opts.s_commit_interval;
sbi->s_min_batch_time = old_opts.s_min_batch_time;
sbi->s_max_batch_time = old_opts.s_max_batch_time;
#ifdef CONFIG_QUOTA
sbi->s_jquota_fmt = old_opts.s_jquota_fmt;
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
kfree(sbi->s_qf_names[i]);
sbi->s_qf_names[i] = old_opts.s_qf_names[i];
}
#endif
kfree(orig_data);
return err;
}
#ifdef CONFIG_QUOTA
static int ext4_statfs_project(struct super_block *sb,
kprojid_t projid, struct kstatfs *buf)
{
struct kqid qid;
struct dquot *dquot;
u64 limit;
u64 curblock;
qid = make_kqid_projid(projid);
dquot = dqget(sb, qid);
if (IS_ERR(dquot))
return PTR_ERR(dquot);
spin_lock(&dq_data_lock);
limit = (dquot->dq_dqb.dqb_bsoftlimit ?
dquot->dq_dqb.dqb_bsoftlimit :
dquot->dq_dqb.dqb_bhardlimit) >> sb->s_blocksize_bits;
if (limit && buf->f_blocks > limit) {
curblock = dquot->dq_dqb.dqb_curspace >> sb->s_blocksize_bits;
buf->f_blocks = limit;
buf->f_bfree = buf->f_bavail =
(buf->f_blocks > curblock) ?
(buf->f_blocks - curblock) : 0;
}
limit = dquot->dq_dqb.dqb_isoftlimit ?
dquot->dq_dqb.dqb_isoftlimit :
dquot->dq_dqb.dqb_ihardlimit;
if (limit && buf->f_files > limit) {
buf->f_files = limit;
buf->f_ffree =
(buf->f_files > dquot->dq_dqb.dqb_curinodes) ?
(buf->f_files - dquot->dq_dqb.dqb_curinodes) : 0;
}
spin_unlock(&dq_data_lock);
dqput(dquot);
return 0;
}
#endif
static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_fsblk_t overhead = 0, resv_blocks;
u64 fsid;
s64 bfree;
resv_blocks = EXT4_C2B(sbi, atomic64_read(&sbi->s_resv_clusters));
if (!test_opt(sb, MINIX_DF))
overhead = sbi->s_overhead;
buf->f_type = EXT4_SUPER_MAGIC;
buf->f_bsize = sb->s_blocksize;
buf->f_blocks = ext4_blocks_count(es) - EXT4_C2B(sbi, overhead);
bfree = percpu_counter_sum_positive(&sbi->s_freeclusters_counter) -
percpu_counter_sum_positive(&sbi->s_dirtyclusters_counter);
/* prevent underflow in case that few free space is available */
buf->f_bfree = EXT4_C2B(sbi, max_t(s64, bfree, 0));
buf->f_bavail = buf->f_bfree -
(ext4_r_blocks_count(es) + resv_blocks);
if (buf->f_bfree < (ext4_r_blocks_count(es) + resv_blocks))
buf->f_bavail = 0;
buf->f_files = le32_to_cpu(es->s_inodes_count);
buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter);
buf->f_namelen = EXT4_NAME_LEN;
fsid = le64_to_cpup((void *)es->s_uuid) ^
le64_to_cpup((void *)es->s_uuid + sizeof(u64));
buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
#ifdef CONFIG_QUOTA
if (ext4_test_inode_flag(dentry->d_inode, EXT4_INODE_PROJINHERIT) &&
sb_has_quota_limits_enabled(sb, PRJQUOTA))
ext4_statfs_project(sb, EXT4_I(dentry->d_inode)->i_projid, buf);
#endif
return 0;
}
/* Helper function for writing quotas on sync - we need to start transaction
* before quota file is locked for write. Otherwise the are possible deadlocks:
* Process 1 Process 2
* ext4_create() quota_sync()
* jbd2_journal_start() write_dquot()
* dquot_initialize() down(dqio_mutex)
* down(dqio_mutex) jbd2_journal_start()
*
*/
#ifdef CONFIG_QUOTA
static inline struct inode *dquot_to_inode(struct dquot *dquot)
{
return sb_dqopt(dquot->dq_sb)->files[dquot->dq_id.type];
}
static int ext4_write_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
struct inode *inode;
inode = dquot_to_inode(dquot);
handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
EXT4_QUOTA_TRANS_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_commit(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_acquire_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
EXT4_QUOTA_INIT_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_acquire(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_release_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
EXT4_QUOTA_DEL_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle)) {
/* Release dquot anyway to avoid endless cycle in dqput() */
dquot_release(dquot);
return PTR_ERR(handle);
}
ret = dquot_release(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_mark_dquot_dirty(struct dquot *dquot)
{
struct super_block *sb = dquot->dq_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
/* Are we journaling quotas? */
if (ext4_has_feature_quota(sb) ||
sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
dquot_mark_dquot_dirty(dquot);
return ext4_write_dquot(dquot);
} else {
return dquot_mark_dquot_dirty(dquot);
}
}
static int ext4_write_info(struct super_block *sb, int type)
{
int ret, err;
handle_t *handle;
/* Data block + inode block */
handle = ext4_journal_start(d_inode(sb->s_root), EXT4_HT_QUOTA, 2);
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_commit_info(sb, type);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
/*
* Turn on quotas during mount time - we need to find
* the quota file and such...
*/
static int ext4_quota_on_mount(struct super_block *sb, int type)
{
return dquot_quota_on_mount(sb, EXT4_SB(sb)->s_qf_names[type],
EXT4_SB(sb)->s_jquota_fmt, type);
}
/*
* Standard function to be called on quota_on
*/
static int ext4_quota_on(struct super_block *sb, int type, int format_id,
struct path *path)
{
int err;
if (!test_opt(sb, QUOTA))
return -EINVAL;
/* Quotafile not on the same filesystem? */
if (path->dentry->d_sb != sb)
return -EXDEV;
/* Journaling quota? */
if (EXT4_SB(sb)->s_qf_names[type]) {
/* Quotafile not in fs root? */
if (path->dentry->d_parent != sb->s_root)
ext4_msg(sb, KERN_WARNING,
"Quota file not on filesystem root. "
"Journaled quota will not work");
}
/*
* When we journal data on quota file, we have to flush journal to see
* all updates to the file when we bypass pagecache...
*/
if (EXT4_SB(sb)->s_journal &&
ext4_should_journal_data(d_inode(path->dentry))) {
/*
* We don't need to lock updates but journal_flush() could
* otherwise be livelocked...
*/
jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
err = jbd2_journal_flush(EXT4_SB(sb)->s_journal);
jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
if (err)
return err;
}
return dquot_quota_on(sb, type, format_id, path);
}
static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
unsigned int flags)
{
int err;
struct inode *qf_inode;
unsigned long qf_inums[EXT4_MAXQUOTAS] = {
le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
};
BUG_ON(!ext4_has_feature_quota(sb));
if (!qf_inums[type])
return -EPERM;
qf_inode = ext4_iget(sb, qf_inums[type]);
if (IS_ERR(qf_inode)) {
ext4_error(sb, "Bad quota inode # %lu", qf_inums[type]);
return PTR_ERR(qf_inode);
}
/* Don't account quota for quota files to avoid recursion */
qf_inode->i_flags |= S_NOQUOTA;
err = dquot_enable(qf_inode, type, format_id, flags);
iput(qf_inode);
return err;
}
/* Enable usage tracking for all quota types. */
static int ext4_enable_quotas(struct super_block *sb)
{
int type, err = 0;
unsigned long qf_inums[EXT4_MAXQUOTAS] = {
le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
};
sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE;
for (type = 0; type < EXT4_MAXQUOTAS; type++) {
if (qf_inums[type]) {
err = ext4_quota_enable(sb, type, QFMT_VFS_V1,
DQUOT_USAGE_ENABLED);
if (err) {
ext4_warning(sb,
"Failed to enable quota tracking "
"(type=%d, err=%d). Please run "
"e2fsck to fix.", type, err);
return err;
}
}
}
return 0;
}
static int ext4_quota_off(struct super_block *sb, int type)
{
struct inode *inode = sb_dqopt(sb)->files[type];
handle_t *handle;
/* Force all delayed allocation blocks to be allocated.
* Caller already holds s_umount sem */
if (test_opt(sb, DELALLOC))
sync_filesystem(sb);
if (!inode)
goto out;
/* Update modification times of quota files when userspace can
* start looking at them */
handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1);
if (IS_ERR(handle))
goto out;
inode->i_mtime = inode->i_ctime = CURRENT_TIME;
ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
out:
return dquot_quota_off(sb, type);
}
/* Read data from quotafile - avoid pagecache and such because we cannot afford
* acquiring the locks... As quota files are never truncated and quota code
* itself serializes the operations (and no one else should touch the files)
* we don't have to be afraid of races */
static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
int offset = off & (sb->s_blocksize - 1);
int tocopy;
size_t toread;
struct buffer_head *bh;
loff_t i_size = i_size_read(inode);
if (off > i_size)
return 0;
if (off+len > i_size)
len = i_size-off;
toread = len;
while (toread > 0) {
tocopy = sb->s_blocksize - offset < toread ?
sb->s_blocksize - offset : toread;
bh = ext4_bread(NULL, inode, blk, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh) /* A hole? */
memset(data, 0, tocopy);
else
memcpy(data, bh->b_data+offset, tocopy);
brelse(bh);
offset = 0;
toread -= tocopy;
data += tocopy;
blk++;
}
return len;
}
/* Write to quotafile (we know the transaction is already started and has
* enough credits) */
static ssize_t ext4_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
int err, offset = off & (sb->s_blocksize - 1);
int retries = 0;
struct buffer_head *bh;
handle_t *handle = journal_current_handle();
if (EXT4_SB(sb)->s_journal && !handle) {
ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
" cancelled because transaction is not started",
(unsigned long long)off, (unsigned long long)len);
return -EIO;
}
/*
* Since we account only one data block in transaction credits,
* then it is impossible to cross a block boundary.
*/
if (sb->s_blocksize - offset < len) {
ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
" cancelled because not block aligned",
(unsigned long long)off, (unsigned long long)len);
return -EIO;
}
do {
bh = ext4_bread(handle, inode, blk,
EXT4_GET_BLOCKS_CREATE |
EXT4_GET_BLOCKS_METADATA_NOFAIL);
} while (IS_ERR(bh) && (PTR_ERR(bh) == -ENOSPC) &&
ext4_should_retry_alloc(inode->i_sb, &retries));
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh)
goto out;
BUFFER_TRACE(bh, "get write access");
err = ext4_journal_get_write_access(handle, bh);
if (err) {
brelse(bh);
return err;
}
lock_buffer(bh);
memcpy(bh->b_data+offset, data, len);
flush_dcache_page(bh->b_page);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, NULL, bh);
brelse(bh);
out:
if (inode->i_size < off + len) {
i_size_write(inode, off + len);
EXT4_I(inode)->i_disksize = inode->i_size;
ext4_mark_inode_dirty(handle, inode);
}
return len;
}
#endif
static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data)
{
return mount_bdev(fs_type, flags, dev_name, data, ext4_fill_super);
}
#if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
static inline void register_as_ext2(void)
{
int err = register_filesystem(&ext2_fs_type);
if (err)
printk(KERN_WARNING
"EXT4-fs: Unable to register as ext2 (%d)\n", err);
}
static inline void unregister_as_ext2(void)
{
unregister_filesystem(&ext2_fs_type);
}
static inline int ext2_feature_set_ok(struct super_block *sb)
{
if (ext4_has_unknown_ext2_incompat_features(sb))
return 0;
if (sb->s_flags & MS_RDONLY)
return 1;
if (ext4_has_unknown_ext2_ro_compat_features(sb))
return 0;
return 1;
}
#else
static inline void register_as_ext2(void) { }
static inline void unregister_as_ext2(void) { }
static inline int ext2_feature_set_ok(struct super_block *sb) { return 0; }
#endif
static inline void register_as_ext3(void)
{
int err = register_filesystem(&ext3_fs_type);
if (err)
printk(KERN_WARNING
"EXT4-fs: Unable to register as ext3 (%d)\n", err);
}
static inline void unregister_as_ext3(void)
{
unregister_filesystem(&ext3_fs_type);
}
static inline int ext3_feature_set_ok(struct super_block *sb)
{
if (ext4_has_unknown_ext3_incompat_features(sb))
return 0;
if (!ext4_has_feature_journal(sb))
return 0;
if (sb->s_flags & MS_RDONLY)
return 1;
if (ext4_has_unknown_ext3_ro_compat_features(sb))
return 0;
return 1;
}
static struct file_system_type ext4_fs_type = {
.owner = THIS_MODULE,
.name = "ext4",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext4");
/* Shared across all ext4 file systems */
wait_queue_head_t ext4__ioend_wq[EXT4_WQ_HASH_SZ];
struct mutex ext4__aio_mutex[EXT4_WQ_HASH_SZ];
static int __init ext4_init_fs(void)
{
int i, err;
ratelimit_state_init(&ext4_mount_msg_ratelimit, 30 * HZ, 64);
ext4_li_info = NULL;
mutex_init(&ext4_li_mtx);
/* Build-time check for flags consistency */
ext4_check_flag_values();
for (i = 0; i < EXT4_WQ_HASH_SZ; i++) {
mutex_init(&ext4__aio_mutex[i]);
init_waitqueue_head(&ext4__ioend_wq[i]);
}
err = ext4_init_es();
if (err)
return err;
err = ext4_init_pageio();
if (err)
goto out5;
err = ext4_init_system_zone();
if (err)
goto out4;
err = ext4_init_sysfs();
if (err)
goto out3;
err = ext4_init_mballoc();
if (err)
goto out2;
else
ext4_mballoc_ready = 1;
err = init_inodecache();
if (err)
goto out1;
register_as_ext3();
register_as_ext2();
err = register_filesystem(&ext4_fs_type);
if (err)
goto out;
return 0;
out:
unregister_as_ext2();
unregister_as_ext3();
destroy_inodecache();
out1:
ext4_mballoc_ready = 0;
ext4_exit_mballoc();
out2:
ext4_exit_sysfs();
out3:
ext4_exit_system_zone();
out4:
ext4_exit_pageio();
out5:
ext4_exit_es();
return err;
}
static void __exit ext4_exit_fs(void)
{
ext4_exit_crypto();
ext4_destroy_lazyinit_thread();
unregister_as_ext2();
unregister_as_ext3();
unregister_filesystem(&ext4_fs_type);
destroy_inodecache();
ext4_exit_mballoc();
ext4_exit_sysfs();
ext4_exit_system_zone();
ext4_exit_pageio();
ext4_exit_es();
}
MODULE_AUTHOR("Remy Card, Stephen Tweedie, Andrew Morton, Andreas Dilger, Theodore Ts'o and others");
MODULE_DESCRIPTION("Fourth Extended Filesystem");
MODULE_LICENSE("GPL");
module_init(ext4_init_fs)
module_exit(ext4_exit_fs)
| ./CrossVul/dataset_final_sorted/CWE-19/c/bad_1842_1 |
crossvul-cpp_data_bad_1453_1 | /*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* Copyright (c) 2013 Red Hat, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would 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 the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_shared.h"
#include "xfs_format.h"
#include "xfs_log_format.h"
#include "xfs_trans_resv.h"
#include "xfs_bit.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_da_format.h"
#include "xfs_da_btree.h"
#include "xfs_inode.h"
#include "xfs_trans.h"
#include "xfs_inode_item.h"
#include "xfs_bmap_btree.h"
#include "xfs_bmap.h"
#include "xfs_attr_sf.h"
#include "xfs_attr_remote.h"
#include "xfs_attr.h"
#include "xfs_attr_leaf.h"
#include "xfs_error.h"
#include "xfs_trace.h"
#include "xfs_buf_item.h"
#include "xfs_cksum.h"
#include "xfs_dinode.h"
#include "xfs_dir2.h"
/*
* xfs_attr_leaf.c
*
* Routines to implement leaf blocks of attributes as Btrees of hashed names.
*/
/*========================================================================
* Function prototypes for the kernel.
*========================================================================*/
/*
* Routines used for growing the Btree.
*/
STATIC int xfs_attr3_leaf_create(struct xfs_da_args *args,
xfs_dablk_t which_block, struct xfs_buf **bpp);
STATIC int xfs_attr3_leaf_add_work(struct xfs_buf *leaf_buffer,
struct xfs_attr3_icleaf_hdr *ichdr,
struct xfs_da_args *args, int freemap_index);
STATIC void xfs_attr3_leaf_compact(struct xfs_da_args *args,
struct xfs_attr3_icleaf_hdr *ichdr,
struct xfs_buf *leaf_buffer);
STATIC void xfs_attr3_leaf_rebalance(xfs_da_state_t *state,
xfs_da_state_blk_t *blk1,
xfs_da_state_blk_t *blk2);
STATIC int xfs_attr3_leaf_figure_balance(xfs_da_state_t *state,
xfs_da_state_blk_t *leaf_blk_1,
struct xfs_attr3_icleaf_hdr *ichdr1,
xfs_da_state_blk_t *leaf_blk_2,
struct xfs_attr3_icleaf_hdr *ichdr2,
int *number_entries_in_blk1,
int *number_usedbytes_in_blk1);
/*
* Utility routines.
*/
STATIC void xfs_attr3_leaf_moveents(struct xfs_attr_leafblock *src_leaf,
struct xfs_attr3_icleaf_hdr *src_ichdr, int src_start,
struct xfs_attr_leafblock *dst_leaf,
struct xfs_attr3_icleaf_hdr *dst_ichdr, int dst_start,
int move_count, struct xfs_mount *mp);
STATIC int xfs_attr_leaf_entsize(xfs_attr_leafblock_t *leaf, int index);
void
xfs_attr3_leaf_hdr_from_disk(
struct xfs_attr3_icleaf_hdr *to,
struct xfs_attr_leafblock *from)
{
int i;
ASSERT(from->hdr.info.magic == cpu_to_be16(XFS_ATTR_LEAF_MAGIC) ||
from->hdr.info.magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC));
if (from->hdr.info.magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC)) {
struct xfs_attr3_leaf_hdr *hdr3 = (struct xfs_attr3_leaf_hdr *)from;
to->forw = be32_to_cpu(hdr3->info.hdr.forw);
to->back = be32_to_cpu(hdr3->info.hdr.back);
to->magic = be16_to_cpu(hdr3->info.hdr.magic);
to->count = be16_to_cpu(hdr3->count);
to->usedbytes = be16_to_cpu(hdr3->usedbytes);
to->firstused = be16_to_cpu(hdr3->firstused);
to->holes = hdr3->holes;
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
to->freemap[i].base = be16_to_cpu(hdr3->freemap[i].base);
to->freemap[i].size = be16_to_cpu(hdr3->freemap[i].size);
}
return;
}
to->forw = be32_to_cpu(from->hdr.info.forw);
to->back = be32_to_cpu(from->hdr.info.back);
to->magic = be16_to_cpu(from->hdr.info.magic);
to->count = be16_to_cpu(from->hdr.count);
to->usedbytes = be16_to_cpu(from->hdr.usedbytes);
to->firstused = be16_to_cpu(from->hdr.firstused);
to->holes = from->hdr.holes;
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
to->freemap[i].base = be16_to_cpu(from->hdr.freemap[i].base);
to->freemap[i].size = be16_to_cpu(from->hdr.freemap[i].size);
}
}
void
xfs_attr3_leaf_hdr_to_disk(
struct xfs_attr_leafblock *to,
struct xfs_attr3_icleaf_hdr *from)
{
int i;
ASSERT(from->magic == XFS_ATTR_LEAF_MAGIC ||
from->magic == XFS_ATTR3_LEAF_MAGIC);
if (from->magic == XFS_ATTR3_LEAF_MAGIC) {
struct xfs_attr3_leaf_hdr *hdr3 = (struct xfs_attr3_leaf_hdr *)to;
hdr3->info.hdr.forw = cpu_to_be32(from->forw);
hdr3->info.hdr.back = cpu_to_be32(from->back);
hdr3->info.hdr.magic = cpu_to_be16(from->magic);
hdr3->count = cpu_to_be16(from->count);
hdr3->usedbytes = cpu_to_be16(from->usedbytes);
hdr3->firstused = cpu_to_be16(from->firstused);
hdr3->holes = from->holes;
hdr3->pad1 = 0;
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
hdr3->freemap[i].base = cpu_to_be16(from->freemap[i].base);
hdr3->freemap[i].size = cpu_to_be16(from->freemap[i].size);
}
return;
}
to->hdr.info.forw = cpu_to_be32(from->forw);
to->hdr.info.back = cpu_to_be32(from->back);
to->hdr.info.magic = cpu_to_be16(from->magic);
to->hdr.count = cpu_to_be16(from->count);
to->hdr.usedbytes = cpu_to_be16(from->usedbytes);
to->hdr.firstused = cpu_to_be16(from->firstused);
to->hdr.holes = from->holes;
to->hdr.pad1 = 0;
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
to->hdr.freemap[i].base = cpu_to_be16(from->freemap[i].base);
to->hdr.freemap[i].size = cpu_to_be16(from->freemap[i].size);
}
}
static bool
xfs_attr3_leaf_verify(
struct xfs_buf *bp)
{
struct xfs_mount *mp = bp->b_target->bt_mount;
struct xfs_attr_leafblock *leaf = bp->b_addr;
struct xfs_attr3_icleaf_hdr ichdr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
if (xfs_sb_version_hascrc(&mp->m_sb)) {
struct xfs_da3_node_hdr *hdr3 = bp->b_addr;
if (ichdr.magic != XFS_ATTR3_LEAF_MAGIC)
return false;
if (!uuid_equal(&hdr3->info.uuid, &mp->m_sb.sb_uuid))
return false;
if (be64_to_cpu(hdr3->info.blkno) != bp->b_bn)
return false;
} else {
if (ichdr.magic != XFS_ATTR_LEAF_MAGIC)
return false;
}
if (ichdr.count == 0)
return false;
/* XXX: need to range check rest of attr header values */
/* XXX: hash order check? */
return true;
}
static void
xfs_attr3_leaf_write_verify(
struct xfs_buf *bp)
{
struct xfs_mount *mp = bp->b_target->bt_mount;
struct xfs_buf_log_item *bip = bp->b_fspriv;
struct xfs_attr3_leaf_hdr *hdr3 = bp->b_addr;
if (!xfs_attr3_leaf_verify(bp)) {
xfs_buf_ioerror(bp, EFSCORRUPTED);
xfs_verifier_error(bp);
return;
}
if (!xfs_sb_version_hascrc(&mp->m_sb))
return;
if (bip)
hdr3->info.lsn = cpu_to_be64(bip->bli_item.li_lsn);
xfs_buf_update_cksum(bp, XFS_ATTR3_LEAF_CRC_OFF);
}
/*
* leaf/node format detection on trees is sketchy, so a node read can be done on
* leaf level blocks when detection identifies the tree as a node format tree
* incorrectly. In this case, we need to swap the verifier to match the correct
* format of the block being read.
*/
static void
xfs_attr3_leaf_read_verify(
struct xfs_buf *bp)
{
struct xfs_mount *mp = bp->b_target->bt_mount;
if (xfs_sb_version_hascrc(&mp->m_sb) &&
!xfs_buf_verify_cksum(bp, XFS_ATTR3_LEAF_CRC_OFF))
xfs_buf_ioerror(bp, EFSBADCRC);
else if (!xfs_attr3_leaf_verify(bp))
xfs_buf_ioerror(bp, EFSCORRUPTED);
if (bp->b_error)
xfs_verifier_error(bp);
}
const struct xfs_buf_ops xfs_attr3_leaf_buf_ops = {
.verify_read = xfs_attr3_leaf_read_verify,
.verify_write = xfs_attr3_leaf_write_verify,
};
int
xfs_attr3_leaf_read(
struct xfs_trans *tp,
struct xfs_inode *dp,
xfs_dablk_t bno,
xfs_daddr_t mappedbno,
struct xfs_buf **bpp)
{
int err;
err = xfs_da_read_buf(tp, dp, bno, mappedbno, bpp,
XFS_ATTR_FORK, &xfs_attr3_leaf_buf_ops);
if (!err && tp)
xfs_trans_buf_set_type(tp, *bpp, XFS_BLFT_ATTR_LEAF_BUF);
return err;
}
/*========================================================================
* Namespace helper routines
*========================================================================*/
/*
* If namespace bits don't match return 0.
* If all match then return 1.
*/
STATIC int
xfs_attr_namesp_match(int arg_flags, int ondisk_flags)
{
return XFS_ATTR_NSP_ONDISK(ondisk_flags) == XFS_ATTR_NSP_ARGS_TO_ONDISK(arg_flags);
}
/*========================================================================
* External routines when attribute fork size < XFS_LITINO(mp).
*========================================================================*/
/*
* Query whether the requested number of additional bytes of extended
* attribute space will be able to fit inline.
*
* Returns zero if not, else the di_forkoff fork offset to be used in the
* literal area for attribute data once the new bytes have been added.
*
* di_forkoff must be 8 byte aligned, hence is stored as a >>3 value;
* special case for dev/uuid inodes, they have fixed size data forks.
*/
int
xfs_attr_shortform_bytesfit(xfs_inode_t *dp, int bytes)
{
int offset;
int minforkoff; /* lower limit on valid forkoff locations */
int maxforkoff; /* upper limit on valid forkoff locations */
int dsize;
xfs_mount_t *mp = dp->i_mount;
/* rounded down */
offset = (XFS_LITINO(mp, dp->i_d.di_version) - bytes) >> 3;
switch (dp->i_d.di_format) {
case XFS_DINODE_FMT_DEV:
minforkoff = roundup(sizeof(xfs_dev_t), 8) >> 3;
return (offset >= minforkoff) ? minforkoff : 0;
case XFS_DINODE_FMT_UUID:
minforkoff = roundup(sizeof(uuid_t), 8) >> 3;
return (offset >= minforkoff) ? minforkoff : 0;
}
/*
* If the requested numbers of bytes is smaller or equal to the
* current attribute fork size we can always proceed.
*
* Note that if_bytes in the data fork might actually be larger than
* the current data fork size is due to delalloc extents. In that
* case either the extent count will go down when they are converted
* to real extents, or the delalloc conversion will take care of the
* literal area rebalancing.
*/
if (bytes <= XFS_IFORK_ASIZE(dp))
return dp->i_d.di_forkoff;
/*
* For attr2 we can try to move the forkoff if there is space in the
* literal area, but for the old format we are done if there is no
* space in the fixed attribute fork.
*/
if (!(mp->m_flags & XFS_MOUNT_ATTR2))
return 0;
dsize = dp->i_df.if_bytes;
switch (dp->i_d.di_format) {
case XFS_DINODE_FMT_EXTENTS:
/*
* If there is no attr fork and the data fork is extents,
* determine if creating the default attr fork will result
* in the extents form migrating to btree. If so, the
* minimum offset only needs to be the space required for
* the btree root.
*/
if (!dp->i_d.di_forkoff && dp->i_df.if_bytes >
xfs_default_attroffset(dp))
dsize = XFS_BMDR_SPACE_CALC(MINDBTPTRS);
break;
case XFS_DINODE_FMT_BTREE:
/*
* If we have a data btree then keep forkoff if we have one,
* otherwise we are adding a new attr, so then we set
* minforkoff to where the btree root can finish so we have
* plenty of room for attrs
*/
if (dp->i_d.di_forkoff) {
if (offset < dp->i_d.di_forkoff)
return 0;
return dp->i_d.di_forkoff;
}
dsize = XFS_BMAP_BROOT_SPACE(mp, dp->i_df.if_broot);
break;
}
/*
* A data fork btree root must have space for at least
* MINDBTPTRS key/ptr pairs if the data fork is small or empty.
*/
minforkoff = MAX(dsize, XFS_BMDR_SPACE_CALC(MINDBTPTRS));
minforkoff = roundup(minforkoff, 8) >> 3;
/* attr fork btree root can have at least this many key/ptr pairs */
maxforkoff = XFS_LITINO(mp, dp->i_d.di_version) -
XFS_BMDR_SPACE_CALC(MINABTPTRS);
maxforkoff = maxforkoff >> 3; /* rounded down */
if (offset >= maxforkoff)
return maxforkoff;
if (offset >= minforkoff)
return offset;
return 0;
}
/*
* Switch on the ATTR2 superblock bit (implies also FEATURES2)
*/
STATIC void
xfs_sbversion_add_attr2(xfs_mount_t *mp, xfs_trans_t *tp)
{
if ((mp->m_flags & XFS_MOUNT_ATTR2) &&
!(xfs_sb_version_hasattr2(&mp->m_sb))) {
spin_lock(&mp->m_sb_lock);
if (!xfs_sb_version_hasattr2(&mp->m_sb)) {
xfs_sb_version_addattr2(&mp->m_sb);
spin_unlock(&mp->m_sb_lock);
xfs_mod_sb(tp, XFS_SB_VERSIONNUM | XFS_SB_FEATURES2);
} else
spin_unlock(&mp->m_sb_lock);
}
}
/*
* Create the initial contents of a shortform attribute list.
*/
void
xfs_attr_shortform_create(xfs_da_args_t *args)
{
xfs_attr_sf_hdr_t *hdr;
xfs_inode_t *dp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_create(args);
dp = args->dp;
ASSERT(dp != NULL);
ifp = dp->i_afp;
ASSERT(ifp != NULL);
ASSERT(ifp->if_bytes == 0);
if (dp->i_d.di_aformat == XFS_DINODE_FMT_EXTENTS) {
ifp->if_flags &= ~XFS_IFEXTENTS; /* just in case */
dp->i_d.di_aformat = XFS_DINODE_FMT_LOCAL;
ifp->if_flags |= XFS_IFINLINE;
} else {
ASSERT(ifp->if_flags & XFS_IFINLINE);
}
xfs_idata_realloc(dp, sizeof(*hdr), XFS_ATTR_FORK);
hdr = (xfs_attr_sf_hdr_t *)ifp->if_u1.if_data;
hdr->count = 0;
hdr->totsize = cpu_to_be16(sizeof(*hdr));
xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_ADATA);
}
/*
* Add a name/value pair to the shortform attribute list.
* Overflow from the inode has already been checked for.
*/
void
xfs_attr_shortform_add(xfs_da_args_t *args, int forkoff)
{
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
int i, offset, size;
xfs_mount_t *mp;
xfs_inode_t *dp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_add(args);
dp = args->dp;
mp = dp->i_mount;
dp->i_d.di_forkoff = forkoff;
ifp = dp->i_afp;
ASSERT(ifp->if_flags & XFS_IFINLINE);
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count; sfe = XFS_ATTR_SF_NEXTENTRY(sfe), i++) {
#ifdef DEBUG
if (sfe->namelen != args->namelen)
continue;
if (memcmp(args->name, sfe->nameval, args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, sfe->flags))
continue;
ASSERT(0);
#endif
}
offset = (char *)sfe - (char *)sf;
size = XFS_ATTR_SF_ENTSIZE_BYNAME(args->namelen, args->valuelen);
xfs_idata_realloc(dp, size, XFS_ATTR_FORK);
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
sfe = (xfs_attr_sf_entry_t *)((char *)sf + offset);
sfe->namelen = args->namelen;
sfe->valuelen = args->valuelen;
sfe->flags = XFS_ATTR_NSP_ARGS_TO_ONDISK(args->flags);
memcpy(sfe->nameval, args->name, args->namelen);
memcpy(&sfe->nameval[args->namelen], args->value, args->valuelen);
sf->hdr.count++;
be16_add_cpu(&sf->hdr.totsize, size);
xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_ADATA);
xfs_sbversion_add_attr2(mp, args->trans);
}
/*
* After the last attribute is removed revert to original inode format,
* making all literal area available to the data fork once more.
*/
STATIC void
xfs_attr_fork_reset(
struct xfs_inode *ip,
struct xfs_trans *tp)
{
xfs_idestroy_fork(ip, XFS_ATTR_FORK);
ip->i_d.di_forkoff = 0;
ip->i_d.di_aformat = XFS_DINODE_FMT_EXTENTS;
ASSERT(ip->i_d.di_anextents == 0);
ASSERT(ip->i_afp == NULL);
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
}
/*
* Remove an attribute from the shortform attribute list structure.
*/
int
xfs_attr_shortform_remove(xfs_da_args_t *args)
{
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
int base, size=0, end, totsize, i;
xfs_mount_t *mp;
xfs_inode_t *dp;
trace_xfs_attr_sf_remove(args);
dp = args->dp;
mp = dp->i_mount;
base = sizeof(xfs_attr_sf_hdr_t);
sf = (xfs_attr_shortform_t *)dp->i_afp->if_u1.if_data;
sfe = &sf->list[0];
end = sf->hdr.count;
for (i = 0; i < end; sfe = XFS_ATTR_SF_NEXTENTRY(sfe),
base += size, i++) {
size = XFS_ATTR_SF_ENTSIZE(sfe);
if (sfe->namelen != args->namelen)
continue;
if (memcmp(sfe->nameval, args->name, args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, sfe->flags))
continue;
break;
}
if (i == end)
return(XFS_ERROR(ENOATTR));
/*
* Fix up the attribute fork data, covering the hole
*/
end = base + size;
totsize = be16_to_cpu(sf->hdr.totsize);
if (end != totsize)
memmove(&((char *)sf)[base], &((char *)sf)[end], totsize - end);
sf->hdr.count--;
be16_add_cpu(&sf->hdr.totsize, -size);
/*
* Fix up the start offset of the attribute fork
*/
totsize -= size;
if (totsize == sizeof(xfs_attr_sf_hdr_t) &&
(mp->m_flags & XFS_MOUNT_ATTR2) &&
(dp->i_d.di_format != XFS_DINODE_FMT_BTREE) &&
!(args->op_flags & XFS_DA_OP_ADDNAME)) {
xfs_attr_fork_reset(dp, args->trans);
} else {
xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
dp->i_d.di_forkoff = xfs_attr_shortform_bytesfit(dp, totsize);
ASSERT(dp->i_d.di_forkoff);
ASSERT(totsize > sizeof(xfs_attr_sf_hdr_t) ||
(args->op_flags & XFS_DA_OP_ADDNAME) ||
!(mp->m_flags & XFS_MOUNT_ATTR2) ||
dp->i_d.di_format == XFS_DINODE_FMT_BTREE);
xfs_trans_log_inode(args->trans, dp,
XFS_ILOG_CORE | XFS_ILOG_ADATA);
}
xfs_sbversion_add_attr2(mp, args->trans);
return(0);
}
/*
* Look up a name in a shortform attribute list structure.
*/
/*ARGSUSED*/
int
xfs_attr_shortform_lookup(xfs_da_args_t *args)
{
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
int i;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_lookup(args);
ifp = args->dp->i_afp;
ASSERT(ifp->if_flags & XFS_IFINLINE);
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe), i++) {
if (sfe->namelen != args->namelen)
continue;
if (memcmp(args->name, sfe->nameval, args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, sfe->flags))
continue;
return(XFS_ERROR(EEXIST));
}
return(XFS_ERROR(ENOATTR));
}
/*
* Look up a name in a shortform attribute list structure.
*/
/*ARGSUSED*/
int
xfs_attr_shortform_getvalue(xfs_da_args_t *args)
{
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
int i;
ASSERT(args->dp->i_afp->if_flags == XFS_IFINLINE);
sf = (xfs_attr_shortform_t *)args->dp->i_afp->if_u1.if_data;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe), i++) {
if (sfe->namelen != args->namelen)
continue;
if (memcmp(args->name, sfe->nameval, args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, sfe->flags))
continue;
if (args->flags & ATTR_KERNOVAL) {
args->valuelen = sfe->valuelen;
return(XFS_ERROR(EEXIST));
}
if (args->valuelen < sfe->valuelen) {
args->valuelen = sfe->valuelen;
return(XFS_ERROR(ERANGE));
}
args->valuelen = sfe->valuelen;
memcpy(args->value, &sfe->nameval[args->namelen],
args->valuelen);
return(XFS_ERROR(EEXIST));
}
return(XFS_ERROR(ENOATTR));
}
/*
* Convert from using the shortform to the leaf.
*/
int
xfs_attr_shortform_to_leaf(xfs_da_args_t *args)
{
xfs_inode_t *dp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_da_args_t nargs;
char *tmpbuffer;
int error, i, size;
xfs_dablk_t blkno;
struct xfs_buf *bp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_to_leaf(args);
dp = args->dp;
ifp = dp->i_afp;
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
size = be16_to_cpu(sf->hdr.totsize);
tmpbuffer = kmem_alloc(size, KM_SLEEP);
ASSERT(tmpbuffer != NULL);
memcpy(tmpbuffer, ifp->if_u1.if_data, size);
sf = (xfs_attr_shortform_t *)tmpbuffer;
xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
xfs_bmap_local_to_extents_empty(dp, XFS_ATTR_FORK);
bp = NULL;
error = xfs_da_grow_inode(args, &blkno);
if (error) {
/*
* If we hit an IO error middle of the transaction inside
* grow_inode(), we may have inconsistent data. Bail out.
*/
if (error == EIO)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
ASSERT(blkno == 0);
error = xfs_attr3_leaf_create(args, blkno, &bp);
if (error) {
error = xfs_da_shrink_inode(args, 0, bp);
bp = NULL;
if (error)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
memset((char *)&nargs, 0, sizeof(nargs));
nargs.dp = dp;
nargs.firstblock = args->firstblock;
nargs.flist = args->flist;
nargs.total = args->total;
nargs.whichfork = XFS_ATTR_FORK;
nargs.trans = args->trans;
nargs.op_flags = XFS_DA_OP_OKNOENT;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count; i++) {
nargs.name = sfe->nameval;
nargs.namelen = sfe->namelen;
nargs.value = &sfe->nameval[nargs.namelen];
nargs.valuelen = sfe->valuelen;
nargs.hashval = xfs_da_hashname(sfe->nameval,
sfe->namelen);
nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(sfe->flags);
error = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */
ASSERT(error == ENOATTR);
error = xfs_attr3_leaf_add(bp, &nargs);
ASSERT(error != ENOSPC);
if (error)
goto out;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
error = 0;
out:
kmem_free(tmpbuffer);
return(error);
}
/*
* Check a leaf attribute block to see if all the entries would fit into
* a shortform attribute list.
*/
int
xfs_attr_shortform_allfit(
struct xfs_buf *bp,
struct xfs_inode *dp)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
xfs_attr_leaf_name_local_t *name_loc;
struct xfs_attr3_icleaf_hdr leafhdr;
int bytes;
int i;
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&leafhdr, leaf);
entry = xfs_attr3_leaf_entryp(leaf);
bytes = sizeof(struct xfs_attr_sf_hdr);
for (i = 0; i < leafhdr.count; entry++, i++) {
if (entry->flags & XFS_ATTR_INCOMPLETE)
continue; /* don't copy partial entries */
if (!(entry->flags & XFS_ATTR_LOCAL))
return(0);
name_loc = xfs_attr3_leaf_name_local(leaf, i);
if (name_loc->namelen >= XFS_ATTR_SF_ENTSIZE_MAX)
return(0);
if (be16_to_cpu(name_loc->valuelen) >= XFS_ATTR_SF_ENTSIZE_MAX)
return(0);
bytes += sizeof(struct xfs_attr_sf_entry) - 1
+ name_loc->namelen
+ be16_to_cpu(name_loc->valuelen);
}
if ((dp->i_mount->m_flags & XFS_MOUNT_ATTR2) &&
(dp->i_d.di_format != XFS_DINODE_FMT_BTREE) &&
(bytes == sizeof(struct xfs_attr_sf_hdr)))
return -1;
return xfs_attr_shortform_bytesfit(dp, bytes);
}
/*
* Convert a leaf attribute list to shortform attribute list
*/
int
xfs_attr3_leaf_to_shortform(
struct xfs_buf *bp,
struct xfs_da_args *args,
int forkoff)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_da_args nargs;
struct xfs_inode *dp = args->dp;
char *tmpbuffer;
int error;
int i;
trace_xfs_attr_leaf_to_sf(args);
tmpbuffer = kmem_alloc(XFS_LBSIZE(dp->i_mount), KM_SLEEP);
if (!tmpbuffer)
return ENOMEM;
memcpy(tmpbuffer, bp->b_addr, XFS_LBSIZE(dp->i_mount));
leaf = (xfs_attr_leafblock_t *)tmpbuffer;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
entry = xfs_attr3_leaf_entryp(leaf);
/* XXX (dgc): buffer is about to be marked stale - why zero it? */
memset(bp->b_addr, 0, XFS_LBSIZE(dp->i_mount));
/*
* Clean out the prior contents of the attribute list.
*/
error = xfs_da_shrink_inode(args, 0, bp);
if (error)
goto out;
if (forkoff == -1) {
ASSERT(dp->i_mount->m_flags & XFS_MOUNT_ATTR2);
ASSERT(dp->i_d.di_format != XFS_DINODE_FMT_BTREE);
xfs_attr_fork_reset(dp, args->trans);
goto out;
}
xfs_attr_shortform_create(args);
/*
* Copy the attributes
*/
memset((char *)&nargs, 0, sizeof(nargs));
nargs.dp = dp;
nargs.firstblock = args->firstblock;
nargs.flist = args->flist;
nargs.total = args->total;
nargs.whichfork = XFS_ATTR_FORK;
nargs.trans = args->trans;
nargs.op_flags = XFS_DA_OP_OKNOENT;
for (i = 0; i < ichdr.count; entry++, i++) {
if (entry->flags & XFS_ATTR_INCOMPLETE)
continue; /* don't copy partial entries */
if (!entry->nameidx)
continue;
ASSERT(entry->flags & XFS_ATTR_LOCAL);
name_loc = xfs_attr3_leaf_name_local(leaf, i);
nargs.name = name_loc->nameval;
nargs.namelen = name_loc->namelen;
nargs.value = &name_loc->nameval[nargs.namelen];
nargs.valuelen = be16_to_cpu(name_loc->valuelen);
nargs.hashval = be32_to_cpu(entry->hashval);
nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(entry->flags);
xfs_attr_shortform_add(&nargs, forkoff);
}
error = 0;
out:
kmem_free(tmpbuffer);
return error;
}
/*
* Convert from using a single leaf to a root node and a leaf.
*/
int
xfs_attr3_leaf_to_node(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr icleafhdr;
struct xfs_attr_leaf_entry *entries;
struct xfs_da_node_entry *btree;
struct xfs_da3_icnode_hdr icnodehdr;
struct xfs_da_intnode *node;
struct xfs_inode *dp = args->dp;
struct xfs_mount *mp = dp->i_mount;
struct xfs_buf *bp1 = NULL;
struct xfs_buf *bp2 = NULL;
xfs_dablk_t blkno;
int error;
trace_xfs_attr_leaf_to_node(args);
error = xfs_da_grow_inode(args, &blkno);
if (error)
goto out;
error = xfs_attr3_leaf_read(args->trans, dp, 0, -1, &bp1);
if (error)
goto out;
error = xfs_da_get_buf(args->trans, dp, blkno, -1, &bp2, XFS_ATTR_FORK);
if (error)
goto out;
/* copy leaf to new buffer, update identifiers */
xfs_trans_buf_set_type(args->trans, bp2, XFS_BLFT_ATTR_LEAF_BUF);
bp2->b_ops = bp1->b_ops;
memcpy(bp2->b_addr, bp1->b_addr, XFS_LBSIZE(mp));
if (xfs_sb_version_hascrc(&mp->m_sb)) {
struct xfs_da3_blkinfo *hdr3 = bp2->b_addr;
hdr3->blkno = cpu_to_be64(bp2->b_bn);
}
xfs_trans_log_buf(args->trans, bp2, 0, XFS_LBSIZE(mp) - 1);
/*
* Set up the new root node.
*/
error = xfs_da3_node_create(args, 0, 1, &bp1, XFS_ATTR_FORK);
if (error)
goto out;
node = bp1->b_addr;
dp->d_ops->node_hdr_from_disk(&icnodehdr, node);
btree = dp->d_ops->node_tree_p(node);
leaf = bp2->b_addr;
xfs_attr3_leaf_hdr_from_disk(&icleafhdr, leaf);
entries = xfs_attr3_leaf_entryp(leaf);
/* both on-disk, don't endian-flip twice */
btree[0].hashval = entries[icleafhdr.count - 1].hashval;
btree[0].before = cpu_to_be32(blkno);
icnodehdr.count = 1;
dp->d_ops->node_hdr_to_disk(node, &icnodehdr);
xfs_trans_log_buf(args->trans, bp1, 0, XFS_LBSIZE(mp) - 1);
error = 0;
out:
return error;
}
/*========================================================================
* Routines used for growing the Btree.
*========================================================================*/
/*
* Create the initial contents of a leaf attribute list
* or a leaf in a node attribute list.
*/
STATIC int
xfs_attr3_leaf_create(
struct xfs_da_args *args,
xfs_dablk_t blkno,
struct xfs_buf **bpp)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_inode *dp = args->dp;
struct xfs_mount *mp = dp->i_mount;
struct xfs_buf *bp;
int error;
trace_xfs_attr_leaf_create(args);
error = xfs_da_get_buf(args->trans, args->dp, blkno, -1, &bp,
XFS_ATTR_FORK);
if (error)
return error;
bp->b_ops = &xfs_attr3_leaf_buf_ops;
xfs_trans_buf_set_type(args->trans, bp, XFS_BLFT_ATTR_LEAF_BUF);
leaf = bp->b_addr;
memset(leaf, 0, XFS_LBSIZE(mp));
memset(&ichdr, 0, sizeof(ichdr));
ichdr.firstused = XFS_LBSIZE(mp);
if (xfs_sb_version_hascrc(&mp->m_sb)) {
struct xfs_da3_blkinfo *hdr3 = bp->b_addr;
ichdr.magic = XFS_ATTR3_LEAF_MAGIC;
hdr3->blkno = cpu_to_be64(bp->b_bn);
hdr3->owner = cpu_to_be64(dp->i_ino);
uuid_copy(&hdr3->uuid, &mp->m_sb.sb_uuid);
ichdr.freemap[0].base = sizeof(struct xfs_attr3_leaf_hdr);
} else {
ichdr.magic = XFS_ATTR_LEAF_MAGIC;
ichdr.freemap[0].base = sizeof(struct xfs_attr_leaf_hdr);
}
ichdr.freemap[0].size = ichdr.firstused - ichdr.freemap[0].base;
xfs_attr3_leaf_hdr_to_disk(leaf, &ichdr);
xfs_trans_log_buf(args->trans, bp, 0, XFS_LBSIZE(mp) - 1);
*bpp = bp;
return 0;
}
/*
* Split the leaf node, rebalance, then add the new entry.
*/
int
xfs_attr3_leaf_split(
struct xfs_da_state *state,
struct xfs_da_state_blk *oldblk,
struct xfs_da_state_blk *newblk)
{
xfs_dablk_t blkno;
int error;
trace_xfs_attr_leaf_split(state->args);
/*
* Allocate space for a new leaf node.
*/
ASSERT(oldblk->magic == XFS_ATTR_LEAF_MAGIC);
error = xfs_da_grow_inode(state->args, &blkno);
if (error)
return(error);
error = xfs_attr3_leaf_create(state->args, blkno, &newblk->bp);
if (error)
return(error);
newblk->blkno = blkno;
newblk->magic = XFS_ATTR_LEAF_MAGIC;
/*
* Rebalance the entries across the two leaves.
* NOTE: rebalance() currently depends on the 2nd block being empty.
*/
xfs_attr3_leaf_rebalance(state, oldblk, newblk);
error = xfs_da3_blk_link(state, oldblk, newblk);
if (error)
return(error);
/*
* Save info on "old" attribute for "atomic rename" ops, leaf_add()
* modifies the index/blkno/rmtblk/rmtblkcnt fields to show the
* "new" attrs info. Will need the "old" info to remove it later.
*
* Insert the "new" entry in the correct block.
*/
if (state->inleaf) {
trace_xfs_attr_leaf_add_old(state->args);
error = xfs_attr3_leaf_add(oldblk->bp, state->args);
} else {
trace_xfs_attr_leaf_add_new(state->args);
error = xfs_attr3_leaf_add(newblk->bp, state->args);
}
/*
* Update last hashval in each block since we added the name.
*/
oldblk->hashval = xfs_attr_leaf_lasthash(oldblk->bp, NULL);
newblk->hashval = xfs_attr_leaf_lasthash(newblk->bp, NULL);
return(error);
}
/*
* Add a name to the leaf attribute list structure.
*/
int
xfs_attr3_leaf_add(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
int tablesize;
int entsize;
int sum;
int tmp;
int i;
trace_xfs_attr_leaf_add(args);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
ASSERT(args->index >= 0 && args->index <= ichdr.count);
entsize = xfs_attr_leaf_newentsize(args->namelen, args->valuelen,
args->trans->t_mountp->m_sb.sb_blocksize, NULL);
/*
* Search through freemap for first-fit on new name length.
* (may need to figure in size of entry struct too)
*/
tablesize = (ichdr.count + 1) * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf);
for (sum = 0, i = XFS_ATTR_LEAF_MAPSIZE - 1; i >= 0; i--) {
if (tablesize > ichdr.firstused) {
sum += ichdr.freemap[i].size;
continue;
}
if (!ichdr.freemap[i].size)
continue; /* no space in this map */
tmp = entsize;
if (ichdr.freemap[i].base < ichdr.firstused)
tmp += sizeof(xfs_attr_leaf_entry_t);
if (ichdr.freemap[i].size >= tmp) {
tmp = xfs_attr3_leaf_add_work(bp, &ichdr, args, i);
goto out_log_hdr;
}
sum += ichdr.freemap[i].size;
}
/*
* If there are no holes in the address space of the block,
* and we don't have enough freespace, then compaction will do us
* no good and we should just give up.
*/
if (!ichdr.holes && sum < entsize)
return XFS_ERROR(ENOSPC);
/*
* Compact the entries to coalesce free space.
* This may change the hdr->count via dropping INCOMPLETE entries.
*/
xfs_attr3_leaf_compact(args, &ichdr, bp);
/*
* After compaction, the block is guaranteed to have only one
* free region, in freemap[0]. If it is not big enough, give up.
*/
if (ichdr.freemap[0].size < (entsize + sizeof(xfs_attr_leaf_entry_t))) {
tmp = ENOSPC;
goto out_log_hdr;
}
tmp = xfs_attr3_leaf_add_work(bp, &ichdr, args, 0);
out_log_hdr:
xfs_attr3_leaf_hdr_to_disk(leaf, &ichdr);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, &leaf->hdr,
xfs_attr3_leaf_hdr_size(leaf)));
return tmp;
}
/*
* Add a name to a leaf attribute list structure.
*/
STATIC int
xfs_attr3_leaf_add_work(
struct xfs_buf *bp,
struct xfs_attr3_icleaf_hdr *ichdr,
struct xfs_da_args *args,
int mapindex)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_mount *mp;
int tmp;
int i;
trace_xfs_attr_leaf_add_work(args);
leaf = bp->b_addr;
ASSERT(mapindex >= 0 && mapindex < XFS_ATTR_LEAF_MAPSIZE);
ASSERT(args->index >= 0 && args->index <= ichdr->count);
/*
* Force open some space in the entry array and fill it in.
*/
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
if (args->index < ichdr->count) {
tmp = ichdr->count - args->index;
tmp *= sizeof(xfs_attr_leaf_entry_t);
memmove(entry + 1, entry, tmp);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(*entry)));
}
ichdr->count++;
/*
* Allocate space for the new string (at the end of the run).
*/
mp = args->trans->t_mountp;
ASSERT(ichdr->freemap[mapindex].base < XFS_LBSIZE(mp));
ASSERT((ichdr->freemap[mapindex].base & 0x3) == 0);
ASSERT(ichdr->freemap[mapindex].size >=
xfs_attr_leaf_newentsize(args->namelen, args->valuelen,
mp->m_sb.sb_blocksize, NULL));
ASSERT(ichdr->freemap[mapindex].size < XFS_LBSIZE(mp));
ASSERT((ichdr->freemap[mapindex].size & 0x3) == 0);
ichdr->freemap[mapindex].size -=
xfs_attr_leaf_newentsize(args->namelen, args->valuelen,
mp->m_sb.sb_blocksize, &tmp);
entry->nameidx = cpu_to_be16(ichdr->freemap[mapindex].base +
ichdr->freemap[mapindex].size);
entry->hashval = cpu_to_be32(args->hashval);
entry->flags = tmp ? XFS_ATTR_LOCAL : 0;
entry->flags |= XFS_ATTR_NSP_ARGS_TO_ONDISK(args->flags);
if (args->op_flags & XFS_DA_OP_RENAME) {
entry->flags |= XFS_ATTR_INCOMPLETE;
if ((args->blkno2 == args->blkno) &&
(args->index2 <= args->index)) {
args->index2++;
}
}
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
ASSERT((args->index == 0) ||
(be32_to_cpu(entry->hashval) >= be32_to_cpu((entry-1)->hashval)));
ASSERT((args->index == ichdr->count - 1) ||
(be32_to_cpu(entry->hashval) <= be32_to_cpu((entry+1)->hashval)));
/*
* For "remote" attribute values, simply note that we need to
* allocate space for the "remote" value. We can't actually
* allocate the extents in this transaction, and we can't decide
* which blocks they should be as we might allocate more blocks
* as part of this transaction (a split operation for example).
*/
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
name_loc->namelen = args->namelen;
name_loc->valuelen = cpu_to_be16(args->valuelen);
memcpy((char *)name_loc->nameval, args->name, args->namelen);
memcpy((char *)&name_loc->nameval[args->namelen], args->value,
be16_to_cpu(name_loc->valuelen));
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
name_rmt->namelen = args->namelen;
memcpy((char *)name_rmt->name, args->name, args->namelen);
entry->flags |= XFS_ATTR_INCOMPLETE;
/* just in case */
name_rmt->valuelen = 0;
name_rmt->valueblk = 0;
args->rmtblkno = 1;
args->rmtblkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen);
}
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index),
xfs_attr_leaf_entsize(leaf, args->index)));
/*
* Update the control info for this leaf node
*/
if (be16_to_cpu(entry->nameidx) < ichdr->firstused)
ichdr->firstused = be16_to_cpu(entry->nameidx);
ASSERT(ichdr->firstused >= ichdr->count * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf));
tmp = (ichdr->count - 1) * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf);
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
if (ichdr->freemap[i].base == tmp) {
ichdr->freemap[i].base += sizeof(xfs_attr_leaf_entry_t);
ichdr->freemap[i].size -= sizeof(xfs_attr_leaf_entry_t);
}
}
ichdr->usedbytes += xfs_attr_leaf_entsize(leaf, args->index);
return 0;
}
/*
* Garbage collect a leaf attribute list block by copying it to a new buffer.
*/
STATIC void
xfs_attr3_leaf_compact(
struct xfs_da_args *args,
struct xfs_attr3_icleaf_hdr *ichdr_dst,
struct xfs_buf *bp)
{
struct xfs_attr_leafblock *leaf_src;
struct xfs_attr_leafblock *leaf_dst;
struct xfs_attr3_icleaf_hdr ichdr_src;
struct xfs_trans *trans = args->trans;
struct xfs_mount *mp = trans->t_mountp;
char *tmpbuffer;
trace_xfs_attr_leaf_compact(args);
tmpbuffer = kmem_alloc(XFS_LBSIZE(mp), KM_SLEEP);
memcpy(tmpbuffer, bp->b_addr, XFS_LBSIZE(mp));
memset(bp->b_addr, 0, XFS_LBSIZE(mp));
leaf_src = (xfs_attr_leafblock_t *)tmpbuffer;
leaf_dst = bp->b_addr;
/*
* Copy the on-disk header back into the destination buffer to ensure
* all the information in the header that is not part of the incore
* header structure is preserved.
*/
memcpy(bp->b_addr, tmpbuffer, xfs_attr3_leaf_hdr_size(leaf_src));
/* Initialise the incore headers */
ichdr_src = *ichdr_dst; /* struct copy */
ichdr_dst->firstused = XFS_LBSIZE(mp);
ichdr_dst->usedbytes = 0;
ichdr_dst->count = 0;
ichdr_dst->holes = 0;
ichdr_dst->freemap[0].base = xfs_attr3_leaf_hdr_size(leaf_src);
ichdr_dst->freemap[0].size = ichdr_dst->firstused -
ichdr_dst->freemap[0].base;
/* write the header back to initialise the underlying buffer */
xfs_attr3_leaf_hdr_to_disk(leaf_dst, ichdr_dst);
/*
* Copy all entry's in the same (sorted) order,
* but allocate name/value pairs packed and in sequence.
*/
xfs_attr3_leaf_moveents(leaf_src, &ichdr_src, 0, leaf_dst, ichdr_dst, 0,
ichdr_src.count, mp);
/*
* this logs the entire buffer, but the caller must write the header
* back to the buffer when it is finished modifying it.
*/
xfs_trans_log_buf(trans, bp, 0, XFS_LBSIZE(mp) - 1);
kmem_free(tmpbuffer);
}
/*
* Compare two leaf blocks "order".
* Return 0 unless leaf2 should go before leaf1.
*/
static int
xfs_attr3_leaf_order(
struct xfs_buf *leaf1_bp,
struct xfs_attr3_icleaf_hdr *leaf1hdr,
struct xfs_buf *leaf2_bp,
struct xfs_attr3_icleaf_hdr *leaf2hdr)
{
struct xfs_attr_leaf_entry *entries1;
struct xfs_attr_leaf_entry *entries2;
entries1 = xfs_attr3_leaf_entryp(leaf1_bp->b_addr);
entries2 = xfs_attr3_leaf_entryp(leaf2_bp->b_addr);
if (leaf1hdr->count > 0 && leaf2hdr->count > 0 &&
((be32_to_cpu(entries2[0].hashval) <
be32_to_cpu(entries1[0].hashval)) ||
(be32_to_cpu(entries2[leaf2hdr->count - 1].hashval) <
be32_to_cpu(entries1[leaf1hdr->count - 1].hashval)))) {
return 1;
}
return 0;
}
int
xfs_attr_leaf_order(
struct xfs_buf *leaf1_bp,
struct xfs_buf *leaf2_bp)
{
struct xfs_attr3_icleaf_hdr ichdr1;
struct xfs_attr3_icleaf_hdr ichdr2;
xfs_attr3_leaf_hdr_from_disk(&ichdr1, leaf1_bp->b_addr);
xfs_attr3_leaf_hdr_from_disk(&ichdr2, leaf2_bp->b_addr);
return xfs_attr3_leaf_order(leaf1_bp, &ichdr1, leaf2_bp, &ichdr2);
}
/*
* Redistribute the attribute list entries between two leaf nodes,
* taking into account the size of the new entry.
*
* NOTE: if new block is empty, then it will get the upper half of the
* old block. At present, all (one) callers pass in an empty second block.
*
* This code adjusts the args->index/blkno and args->index2/blkno2 fields
* to match what it is doing in splitting the attribute leaf block. Those
* values are used in "atomic rename" operations on attributes. Note that
* the "new" and "old" values can end up in different blocks.
*/
STATIC void
xfs_attr3_leaf_rebalance(
struct xfs_da_state *state,
struct xfs_da_state_blk *blk1,
struct xfs_da_state_blk *blk2)
{
struct xfs_da_args *args;
struct xfs_attr_leafblock *leaf1;
struct xfs_attr_leafblock *leaf2;
struct xfs_attr3_icleaf_hdr ichdr1;
struct xfs_attr3_icleaf_hdr ichdr2;
struct xfs_attr_leaf_entry *entries1;
struct xfs_attr_leaf_entry *entries2;
int count;
int totallen;
int max;
int space;
int swap;
/*
* Set up environment.
*/
ASSERT(blk1->magic == XFS_ATTR_LEAF_MAGIC);
ASSERT(blk2->magic == XFS_ATTR_LEAF_MAGIC);
leaf1 = blk1->bp->b_addr;
leaf2 = blk2->bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr1, leaf1);
xfs_attr3_leaf_hdr_from_disk(&ichdr2, leaf2);
ASSERT(ichdr2.count == 0);
args = state->args;
trace_xfs_attr_leaf_rebalance(args);
/*
* Check ordering of blocks, reverse if it makes things simpler.
*
* NOTE: Given that all (current) callers pass in an empty
* second block, this code should never set "swap".
*/
swap = 0;
if (xfs_attr3_leaf_order(blk1->bp, &ichdr1, blk2->bp, &ichdr2)) {
struct xfs_da_state_blk *tmp_blk;
struct xfs_attr3_icleaf_hdr tmp_ichdr;
tmp_blk = blk1;
blk1 = blk2;
blk2 = tmp_blk;
/* struct copies to swap them rather than reconverting */
tmp_ichdr = ichdr1;
ichdr1 = ichdr2;
ichdr2 = tmp_ichdr;
leaf1 = blk1->bp->b_addr;
leaf2 = blk2->bp->b_addr;
swap = 1;
}
/*
* Examine entries until we reduce the absolute difference in
* byte usage between the two blocks to a minimum. Then get
* the direction to copy and the number of elements to move.
*
* "inleaf" is true if the new entry should be inserted into blk1.
* If "swap" is also true, then reverse the sense of "inleaf".
*/
state->inleaf = xfs_attr3_leaf_figure_balance(state, blk1, &ichdr1,
blk2, &ichdr2,
&count, &totallen);
if (swap)
state->inleaf = !state->inleaf;
/*
* Move any entries required from leaf to leaf:
*/
if (count < ichdr1.count) {
/*
* Figure the total bytes to be added to the destination leaf.
*/
/* number entries being moved */
count = ichdr1.count - count;
space = ichdr1.usedbytes - totallen;
space += count * sizeof(xfs_attr_leaf_entry_t);
/*
* leaf2 is the destination, compact it if it looks tight.
*/
max = ichdr2.firstused - xfs_attr3_leaf_hdr_size(leaf1);
max -= ichdr2.count * sizeof(xfs_attr_leaf_entry_t);
if (space > max)
xfs_attr3_leaf_compact(args, &ichdr2, blk2->bp);
/*
* Move high entries from leaf1 to low end of leaf2.
*/
xfs_attr3_leaf_moveents(leaf1, &ichdr1, ichdr1.count - count,
leaf2, &ichdr2, 0, count, state->mp);
} else if (count > ichdr1.count) {
/*
* I assert that since all callers pass in an empty
* second buffer, this code should never execute.
*/
ASSERT(0);
/*
* Figure the total bytes to be added to the destination leaf.
*/
/* number entries being moved */
count -= ichdr1.count;
space = totallen - ichdr1.usedbytes;
space += count * sizeof(xfs_attr_leaf_entry_t);
/*
* leaf1 is the destination, compact it if it looks tight.
*/
max = ichdr1.firstused - xfs_attr3_leaf_hdr_size(leaf1);
max -= ichdr1.count * sizeof(xfs_attr_leaf_entry_t);
if (space > max)
xfs_attr3_leaf_compact(args, &ichdr1, blk1->bp);
/*
* Move low entries from leaf2 to high end of leaf1.
*/
xfs_attr3_leaf_moveents(leaf2, &ichdr2, 0, leaf1, &ichdr1,
ichdr1.count, count, state->mp);
}
xfs_attr3_leaf_hdr_to_disk(leaf1, &ichdr1);
xfs_attr3_leaf_hdr_to_disk(leaf2, &ichdr2);
xfs_trans_log_buf(args->trans, blk1->bp, 0, state->blocksize-1);
xfs_trans_log_buf(args->trans, blk2->bp, 0, state->blocksize-1);
/*
* Copy out last hashval in each block for B-tree code.
*/
entries1 = xfs_attr3_leaf_entryp(leaf1);
entries2 = xfs_attr3_leaf_entryp(leaf2);
blk1->hashval = be32_to_cpu(entries1[ichdr1.count - 1].hashval);
blk2->hashval = be32_to_cpu(entries2[ichdr2.count - 1].hashval);
/*
* Adjust the expected index for insertion.
* NOTE: this code depends on the (current) situation that the
* second block was originally empty.
*
* If the insertion point moved to the 2nd block, we must adjust
* the index. We must also track the entry just following the
* new entry for use in an "atomic rename" operation, that entry
* is always the "old" entry and the "new" entry is what we are
* inserting. The index/blkno fields refer to the "old" entry,
* while the index2/blkno2 fields refer to the "new" entry.
*/
if (blk1->index > ichdr1.count) {
ASSERT(state->inleaf == 0);
blk2->index = blk1->index - ichdr1.count;
args->index = args->index2 = blk2->index;
args->blkno = args->blkno2 = blk2->blkno;
} else if (blk1->index == ichdr1.count) {
if (state->inleaf) {
args->index = blk1->index;
args->blkno = blk1->blkno;
args->index2 = 0;
args->blkno2 = blk2->blkno;
} else {
/*
* On a double leaf split, the original attr location
* is already stored in blkno2/index2, so don't
* overwrite it overwise we corrupt the tree.
*/
blk2->index = blk1->index - ichdr1.count;
args->index = blk2->index;
args->blkno = blk2->blkno;
if (!state->extravalid) {
/*
* set the new attr location to match the old
* one and let the higher level split code
* decide where in the leaf to place it.
*/
args->index2 = blk2->index;
args->blkno2 = blk2->blkno;
}
}
} else {
ASSERT(state->inleaf == 1);
args->index = args->index2 = blk1->index;
args->blkno = args->blkno2 = blk1->blkno;
}
}
/*
* Examine entries until we reduce the absolute difference in
* byte usage between the two blocks to a minimum.
* GROT: Is this really necessary? With other than a 512 byte blocksize,
* GROT: there will always be enough room in either block for a new entry.
* GROT: Do a double-split for this case?
*/
STATIC int
xfs_attr3_leaf_figure_balance(
struct xfs_da_state *state,
struct xfs_da_state_blk *blk1,
struct xfs_attr3_icleaf_hdr *ichdr1,
struct xfs_da_state_blk *blk2,
struct xfs_attr3_icleaf_hdr *ichdr2,
int *countarg,
int *usedbytesarg)
{
struct xfs_attr_leafblock *leaf1 = blk1->bp->b_addr;
struct xfs_attr_leafblock *leaf2 = blk2->bp->b_addr;
struct xfs_attr_leaf_entry *entry;
int count;
int max;
int index;
int totallen = 0;
int half;
int lastdelta;
int foundit = 0;
int tmp;
/*
* Examine entries until we reduce the absolute difference in
* byte usage between the two blocks to a minimum.
*/
max = ichdr1->count + ichdr2->count;
half = (max + 1) * sizeof(*entry);
half += ichdr1->usedbytes + ichdr2->usedbytes +
xfs_attr_leaf_newentsize(state->args->namelen,
state->args->valuelen,
state->blocksize, NULL);
half /= 2;
lastdelta = state->blocksize;
entry = xfs_attr3_leaf_entryp(leaf1);
for (count = index = 0; count < max; entry++, index++, count++) {
#define XFS_ATTR_ABS(A) (((A) < 0) ? -(A) : (A))
/*
* The new entry is in the first block, account for it.
*/
if (count == blk1->index) {
tmp = totallen + sizeof(*entry) +
xfs_attr_leaf_newentsize(
state->args->namelen,
state->args->valuelen,
state->blocksize, NULL);
if (XFS_ATTR_ABS(half - tmp) > lastdelta)
break;
lastdelta = XFS_ATTR_ABS(half - tmp);
totallen = tmp;
foundit = 1;
}
/*
* Wrap around into the second block if necessary.
*/
if (count == ichdr1->count) {
leaf1 = leaf2;
entry = xfs_attr3_leaf_entryp(leaf1);
index = 0;
}
/*
* Figure out if next leaf entry would be too much.
*/
tmp = totallen + sizeof(*entry) + xfs_attr_leaf_entsize(leaf1,
index);
if (XFS_ATTR_ABS(half - tmp) > lastdelta)
break;
lastdelta = XFS_ATTR_ABS(half - tmp);
totallen = tmp;
#undef XFS_ATTR_ABS
}
/*
* Calculate the number of usedbytes that will end up in lower block.
* If new entry not in lower block, fix up the count.
*/
totallen -= count * sizeof(*entry);
if (foundit) {
totallen -= sizeof(*entry) +
xfs_attr_leaf_newentsize(
state->args->namelen,
state->args->valuelen,
state->blocksize, NULL);
}
*countarg = count;
*usedbytesarg = totallen;
return foundit;
}
/*========================================================================
* Routines used for shrinking the Btree.
*========================================================================*/
/*
* Check a leaf block and its neighbors to see if the block should be
* collapsed into one or the other neighbor. Always keep the block
* with the smaller block number.
* If the current block is over 50% full, don't try to join it, return 0.
* If the block is empty, fill in the state structure and return 2.
* If it can be collapsed, fill in the state structure and return 1.
* If nothing can be done, return 0.
*
* GROT: allow for INCOMPLETE entries in calculation.
*/
int
xfs_attr3_leaf_toosmall(
struct xfs_da_state *state,
int *action)
{
struct xfs_attr_leafblock *leaf;
struct xfs_da_state_blk *blk;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_buf *bp;
xfs_dablk_t blkno;
int bytes;
int forward;
int error;
int retval;
int i;
trace_xfs_attr_leaf_toosmall(state->args);
/*
* Check for the degenerate case of the block being over 50% full.
* If so, it's not worth even looking to see if we might be able
* to coalesce with a sibling.
*/
blk = &state->path.blk[ state->path.active-1 ];
leaf = blk->bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
bytes = xfs_attr3_leaf_hdr_size(leaf) +
ichdr.count * sizeof(xfs_attr_leaf_entry_t) +
ichdr.usedbytes;
if (bytes > (state->blocksize >> 1)) {
*action = 0; /* blk over 50%, don't try to join */
return(0);
}
/*
* Check for the degenerate case of the block being empty.
* If the block is empty, we'll simply delete it, no need to
* coalesce it with a sibling block. We choose (arbitrarily)
* to merge with the forward block unless it is NULL.
*/
if (ichdr.count == 0) {
/*
* Make altpath point to the block we want to keep and
* path point to the block we want to drop (this one).
*/
forward = (ichdr.forw != 0);
memcpy(&state->altpath, &state->path, sizeof(state->path));
error = xfs_da3_path_shift(state, &state->altpath, forward,
0, &retval);
if (error)
return(error);
if (retval) {
*action = 0;
} else {
*action = 2;
}
return 0;
}
/*
* Examine each sibling block to see if we can coalesce with
* at least 25% free space to spare. We need to figure out
* whether to merge with the forward or the backward block.
* We prefer coalescing with the lower numbered sibling so as
* to shrink an attribute list over time.
*/
/* start with smaller blk num */
forward = ichdr.forw < ichdr.back;
for (i = 0; i < 2; forward = !forward, i++) {
struct xfs_attr3_icleaf_hdr ichdr2;
if (forward)
blkno = ichdr.forw;
else
blkno = ichdr.back;
if (blkno == 0)
continue;
error = xfs_attr3_leaf_read(state->args->trans, state->args->dp,
blkno, -1, &bp);
if (error)
return(error);
xfs_attr3_leaf_hdr_from_disk(&ichdr2, bp->b_addr);
bytes = state->blocksize - (state->blocksize >> 2) -
ichdr.usedbytes - ichdr2.usedbytes -
((ichdr.count + ichdr2.count) *
sizeof(xfs_attr_leaf_entry_t)) -
xfs_attr3_leaf_hdr_size(leaf);
xfs_trans_brelse(state->args->trans, bp);
if (bytes >= 0)
break; /* fits with at least 25% to spare */
}
if (i >= 2) {
*action = 0;
return(0);
}
/*
* Make altpath point to the block we want to keep (the lower
* numbered block) and path point to the block we want to drop.
*/
memcpy(&state->altpath, &state->path, sizeof(state->path));
if (blkno < blk->blkno) {
error = xfs_da3_path_shift(state, &state->altpath, forward,
0, &retval);
} else {
error = xfs_da3_path_shift(state, &state->path, forward,
0, &retval);
}
if (error)
return(error);
if (retval) {
*action = 0;
} else {
*action = 1;
}
return(0);
}
/*
* Remove a name from the leaf attribute list structure.
*
* Return 1 if leaf is less than 37% full, 0 if >= 37% full.
* If two leaves are 37% full, when combined they will leave 25% free.
*/
int
xfs_attr3_leaf_remove(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_mount *mp = args->trans->t_mountp;
int before;
int after;
int smallest;
int entsize;
int tablesize;
int tmp;
int i;
trace_xfs_attr_leaf_remove(args);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
ASSERT(ichdr.count > 0 && ichdr.count < XFS_LBSIZE(mp) / 8);
ASSERT(args->index >= 0 && args->index < ichdr.count);
ASSERT(ichdr.firstused >= ichdr.count * sizeof(*entry) +
xfs_attr3_leaf_hdr_size(leaf));
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
ASSERT(be16_to_cpu(entry->nameidx) >= ichdr.firstused);
ASSERT(be16_to_cpu(entry->nameidx) < XFS_LBSIZE(mp));
/*
* Scan through free region table:
* check for adjacency of free'd entry with an existing one,
* find smallest free region in case we need to replace it,
* adjust any map that borders the entry table,
*/
tablesize = ichdr.count * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf);
tmp = ichdr.freemap[0].size;
before = after = -1;
smallest = XFS_ATTR_LEAF_MAPSIZE - 1;
entsize = xfs_attr_leaf_entsize(leaf, args->index);
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
ASSERT(ichdr.freemap[i].base < XFS_LBSIZE(mp));
ASSERT(ichdr.freemap[i].size < XFS_LBSIZE(mp));
if (ichdr.freemap[i].base == tablesize) {
ichdr.freemap[i].base -= sizeof(xfs_attr_leaf_entry_t);
ichdr.freemap[i].size += sizeof(xfs_attr_leaf_entry_t);
}
if (ichdr.freemap[i].base + ichdr.freemap[i].size ==
be16_to_cpu(entry->nameidx)) {
before = i;
} else if (ichdr.freemap[i].base ==
(be16_to_cpu(entry->nameidx) + entsize)) {
after = i;
} else if (ichdr.freemap[i].size < tmp) {
tmp = ichdr.freemap[i].size;
smallest = i;
}
}
/*
* Coalesce adjacent freemap regions,
* or replace the smallest region.
*/
if ((before >= 0) || (after >= 0)) {
if ((before >= 0) && (after >= 0)) {
ichdr.freemap[before].size += entsize;
ichdr.freemap[before].size += ichdr.freemap[after].size;
ichdr.freemap[after].base = 0;
ichdr.freemap[after].size = 0;
} else if (before >= 0) {
ichdr.freemap[before].size += entsize;
} else {
ichdr.freemap[after].base = be16_to_cpu(entry->nameidx);
ichdr.freemap[after].size += entsize;
}
} else {
/*
* Replace smallest region (if it is smaller than free'd entry)
*/
if (ichdr.freemap[smallest].size < entsize) {
ichdr.freemap[smallest].base = be16_to_cpu(entry->nameidx);
ichdr.freemap[smallest].size = entsize;
}
}
/*
* Did we remove the first entry?
*/
if (be16_to_cpu(entry->nameidx) == ichdr.firstused)
smallest = 1;
else
smallest = 0;
/*
* Compress the remaining entries and zero out the removed stuff.
*/
memset(xfs_attr3_leaf_name(leaf, args->index), 0, entsize);
ichdr.usedbytes -= entsize;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index),
entsize));
tmp = (ichdr.count - args->index) * sizeof(xfs_attr_leaf_entry_t);
memmove(entry, entry + 1, tmp);
ichdr.count--;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(xfs_attr_leaf_entry_t)));
entry = &xfs_attr3_leaf_entryp(leaf)[ichdr.count];
memset(entry, 0, sizeof(xfs_attr_leaf_entry_t));
/*
* If we removed the first entry, re-find the first used byte
* in the name area. Note that if the entry was the "firstused",
* then we don't have a "hole" in our block resulting from
* removing the name.
*/
if (smallest) {
tmp = XFS_LBSIZE(mp);
entry = xfs_attr3_leaf_entryp(leaf);
for (i = ichdr.count - 1; i >= 0; entry++, i--) {
ASSERT(be16_to_cpu(entry->nameidx) >= ichdr.firstused);
ASSERT(be16_to_cpu(entry->nameidx) < XFS_LBSIZE(mp));
if (be16_to_cpu(entry->nameidx) < tmp)
tmp = be16_to_cpu(entry->nameidx);
}
ichdr.firstused = tmp;
if (!ichdr.firstused)
ichdr.firstused = tmp - XFS_ATTR_LEAF_NAME_ALIGN;
} else {
ichdr.holes = 1; /* mark as needing compaction */
}
xfs_attr3_leaf_hdr_to_disk(leaf, &ichdr);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, &leaf->hdr,
xfs_attr3_leaf_hdr_size(leaf)));
/*
* Check if leaf is less than 50% full, caller may want to
* "join" the leaf with a sibling if so.
*/
tmp = ichdr.usedbytes + xfs_attr3_leaf_hdr_size(leaf) +
ichdr.count * sizeof(xfs_attr_leaf_entry_t);
return tmp < mp->m_attr_magicpct; /* leaf is < 37% full */
}
/*
* Move all the attribute list entries from drop_leaf into save_leaf.
*/
void
xfs_attr3_leaf_unbalance(
struct xfs_da_state *state,
struct xfs_da_state_blk *drop_blk,
struct xfs_da_state_blk *save_blk)
{
struct xfs_attr_leafblock *drop_leaf = drop_blk->bp->b_addr;
struct xfs_attr_leafblock *save_leaf = save_blk->bp->b_addr;
struct xfs_attr3_icleaf_hdr drophdr;
struct xfs_attr3_icleaf_hdr savehdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_mount *mp = state->mp;
trace_xfs_attr_leaf_unbalance(state->args);
drop_leaf = drop_blk->bp->b_addr;
save_leaf = save_blk->bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&drophdr, drop_leaf);
xfs_attr3_leaf_hdr_from_disk(&savehdr, save_leaf);
entry = xfs_attr3_leaf_entryp(drop_leaf);
/*
* Save last hashval from dying block for later Btree fixup.
*/
drop_blk->hashval = be32_to_cpu(entry[drophdr.count - 1].hashval);
/*
* Check if we need a temp buffer, or can we do it in place.
* Note that we don't check "leaf" for holes because we will
* always be dropping it, toosmall() decided that for us already.
*/
if (savehdr.holes == 0) {
/*
* dest leaf has no holes, so we add there. May need
* to make some room in the entry array.
*/
if (xfs_attr3_leaf_order(save_blk->bp, &savehdr,
drop_blk->bp, &drophdr)) {
xfs_attr3_leaf_moveents(drop_leaf, &drophdr, 0,
save_leaf, &savehdr, 0,
drophdr.count, mp);
} else {
xfs_attr3_leaf_moveents(drop_leaf, &drophdr, 0,
save_leaf, &savehdr,
savehdr.count, drophdr.count, mp);
}
} else {
/*
* Destination has holes, so we make a temporary copy
* of the leaf and add them both to that.
*/
struct xfs_attr_leafblock *tmp_leaf;
struct xfs_attr3_icleaf_hdr tmphdr;
tmp_leaf = kmem_zalloc(state->blocksize, KM_SLEEP);
/*
* Copy the header into the temp leaf so that all the stuff
* not in the incore header is present and gets copied back in
* once we've moved all the entries.
*/
memcpy(tmp_leaf, save_leaf, xfs_attr3_leaf_hdr_size(save_leaf));
memset(&tmphdr, 0, sizeof(tmphdr));
tmphdr.magic = savehdr.magic;
tmphdr.forw = savehdr.forw;
tmphdr.back = savehdr.back;
tmphdr.firstused = state->blocksize;
/* write the header to the temp buffer to initialise it */
xfs_attr3_leaf_hdr_to_disk(tmp_leaf, &tmphdr);
if (xfs_attr3_leaf_order(save_blk->bp, &savehdr,
drop_blk->bp, &drophdr)) {
xfs_attr3_leaf_moveents(drop_leaf, &drophdr, 0,
tmp_leaf, &tmphdr, 0,
drophdr.count, mp);
xfs_attr3_leaf_moveents(save_leaf, &savehdr, 0,
tmp_leaf, &tmphdr, tmphdr.count,
savehdr.count, mp);
} else {
xfs_attr3_leaf_moveents(save_leaf, &savehdr, 0,
tmp_leaf, &tmphdr, 0,
savehdr.count, mp);
xfs_attr3_leaf_moveents(drop_leaf, &drophdr, 0,
tmp_leaf, &tmphdr, tmphdr.count,
drophdr.count, mp);
}
memcpy(save_leaf, tmp_leaf, state->blocksize);
savehdr = tmphdr; /* struct copy */
kmem_free(tmp_leaf);
}
xfs_attr3_leaf_hdr_to_disk(save_leaf, &savehdr);
xfs_trans_log_buf(state->args->trans, save_blk->bp, 0,
state->blocksize - 1);
/*
* Copy out last hashval in each block for B-tree code.
*/
entry = xfs_attr3_leaf_entryp(save_leaf);
save_blk->hashval = be32_to_cpu(entry[savehdr.count - 1].hashval);
}
/*========================================================================
* Routines used for finding things in the Btree.
*========================================================================*/
/*
* Look up a name in a leaf attribute list structure.
* This is the internal routine, it uses the caller's buffer.
*
* Note that duplicate keys are allowed, but only check within the
* current leaf node. The Btree code must check in adjacent leaf nodes.
*
* Return in args->index the index into the entry[] array of either
* the found entry, or where the entry should have been (insert before
* that entry).
*
* Don't change the args->value unless we find the attribute.
*/
int
xfs_attr3_leaf_lookup_int(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_entry *entries;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_attr_leaf_name_remote *name_rmt;
xfs_dahash_t hashval;
int probe;
int span;
trace_xfs_attr_leaf_lookup(args);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
entries = xfs_attr3_leaf_entryp(leaf);
ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8);
/*
* Binary search. (note: small blocks will skip this loop)
*/
hashval = args->hashval;
probe = span = ichdr.count / 2;
for (entry = &entries[probe]; span > 4; entry = &entries[probe]) {
span /= 2;
if (be32_to_cpu(entry->hashval) < hashval)
probe += span;
else if (be32_to_cpu(entry->hashval) > hashval)
probe -= span;
else
break;
}
ASSERT(probe >= 0 && (!ichdr.count || probe < ichdr.count));
ASSERT(span <= 4 || be32_to_cpu(entry->hashval) == hashval);
/*
* Since we may have duplicate hashval's, find the first matching
* hashval in the leaf.
*/
while (probe > 0 && be32_to_cpu(entry->hashval) >= hashval) {
entry--;
probe--;
}
while (probe < ichdr.count &&
be32_to_cpu(entry->hashval) < hashval) {
entry++;
probe++;
}
if (probe == ichdr.count || be32_to_cpu(entry->hashval) != hashval) {
args->index = probe;
return XFS_ERROR(ENOATTR);
}
/*
* Duplicate keys may be present, so search all of them for a match.
*/
for (; probe < ichdr.count && (be32_to_cpu(entry->hashval) == hashval);
entry++, probe++) {
/*
* GROT: Add code to remove incomplete entries.
*/
/*
* If we are looking for INCOMPLETE entries, show only those.
* If we are looking for complete entries, show only those.
*/
if ((args->flags & XFS_ATTR_INCOMPLETE) !=
(entry->flags & XFS_ATTR_INCOMPLETE)) {
continue;
}
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, probe);
if (name_loc->namelen != args->namelen)
continue;
if (memcmp(args->name, name_loc->nameval,
args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, entry->flags))
continue;
args->index = probe;
return XFS_ERROR(EEXIST);
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, probe);
if (name_rmt->namelen != args->namelen)
continue;
if (memcmp(args->name, name_rmt->name,
args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, entry->flags))
continue;
args->index = probe;
args->valuelen = be32_to_cpu(name_rmt->valuelen);
args->rmtblkno = be32_to_cpu(name_rmt->valueblk);
args->rmtblkcnt = xfs_attr3_rmt_blocks(
args->dp->i_mount,
args->valuelen);
return XFS_ERROR(EEXIST);
}
}
args->index = probe;
return XFS_ERROR(ENOATTR);
}
/*
* Get the value associated with an attribute name from a leaf attribute
* list structure.
*/
int
xfs_attr3_leaf_getvalue(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_attr_leaf_name_remote *name_rmt;
int valuelen;
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8);
ASSERT(args->index < ichdr.count);
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
ASSERT(name_loc->namelen == args->namelen);
ASSERT(memcmp(args->name, name_loc->nameval, args->namelen) == 0);
valuelen = be16_to_cpu(name_loc->valuelen);
if (args->flags & ATTR_KERNOVAL) {
args->valuelen = valuelen;
return 0;
}
if (args->valuelen < valuelen) {
args->valuelen = valuelen;
return XFS_ERROR(ERANGE);
}
args->valuelen = valuelen;
memcpy(args->value, &name_loc->nameval[args->namelen], valuelen);
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
ASSERT(name_rmt->namelen == args->namelen);
ASSERT(memcmp(args->name, name_rmt->name, args->namelen) == 0);
valuelen = be32_to_cpu(name_rmt->valuelen);
args->rmtblkno = be32_to_cpu(name_rmt->valueblk);
args->rmtblkcnt = xfs_attr3_rmt_blocks(args->dp->i_mount,
valuelen);
if (args->flags & ATTR_KERNOVAL) {
args->valuelen = valuelen;
return 0;
}
if (args->valuelen < valuelen) {
args->valuelen = valuelen;
return XFS_ERROR(ERANGE);
}
args->valuelen = valuelen;
}
return 0;
}
/*========================================================================
* Utility routines.
*========================================================================*/
/*
* Move the indicated entries from one leaf to another.
* NOTE: this routine modifies both source and destination leaves.
*/
/*ARGSUSED*/
STATIC void
xfs_attr3_leaf_moveents(
struct xfs_attr_leafblock *leaf_s,
struct xfs_attr3_icleaf_hdr *ichdr_s,
int start_s,
struct xfs_attr_leafblock *leaf_d,
struct xfs_attr3_icleaf_hdr *ichdr_d,
int start_d,
int count,
struct xfs_mount *mp)
{
struct xfs_attr_leaf_entry *entry_s;
struct xfs_attr_leaf_entry *entry_d;
int desti;
int tmp;
int i;
/*
* Check for nothing to do.
*/
if (count == 0)
return;
/*
* Set up environment.
*/
ASSERT(ichdr_s->magic == XFS_ATTR_LEAF_MAGIC ||
ichdr_s->magic == XFS_ATTR3_LEAF_MAGIC);
ASSERT(ichdr_s->magic == ichdr_d->magic);
ASSERT(ichdr_s->count > 0 && ichdr_s->count < XFS_LBSIZE(mp) / 8);
ASSERT(ichdr_s->firstused >= (ichdr_s->count * sizeof(*entry_s))
+ xfs_attr3_leaf_hdr_size(leaf_s));
ASSERT(ichdr_d->count < XFS_LBSIZE(mp) / 8);
ASSERT(ichdr_d->firstused >= (ichdr_d->count * sizeof(*entry_d))
+ xfs_attr3_leaf_hdr_size(leaf_d));
ASSERT(start_s < ichdr_s->count);
ASSERT(start_d <= ichdr_d->count);
ASSERT(count <= ichdr_s->count);
/*
* Move the entries in the destination leaf up to make a hole?
*/
if (start_d < ichdr_d->count) {
tmp = ichdr_d->count - start_d;
tmp *= sizeof(xfs_attr_leaf_entry_t);
entry_s = &xfs_attr3_leaf_entryp(leaf_d)[start_d];
entry_d = &xfs_attr3_leaf_entryp(leaf_d)[start_d + count];
memmove(entry_d, entry_s, tmp);
}
/*
* Copy all entry's in the same (sorted) order,
* but allocate attribute info packed and in sequence.
*/
entry_s = &xfs_attr3_leaf_entryp(leaf_s)[start_s];
entry_d = &xfs_attr3_leaf_entryp(leaf_d)[start_d];
desti = start_d;
for (i = 0; i < count; entry_s++, entry_d++, desti++, i++) {
ASSERT(be16_to_cpu(entry_s->nameidx) >= ichdr_s->firstused);
tmp = xfs_attr_leaf_entsize(leaf_s, start_s + i);
#ifdef GROT
/*
* Code to drop INCOMPLETE entries. Difficult to use as we
* may also need to change the insertion index. Code turned
* off for 6.2, should be revisited later.
*/
if (entry_s->flags & XFS_ATTR_INCOMPLETE) { /* skip partials? */
memset(xfs_attr3_leaf_name(leaf_s, start_s + i), 0, tmp);
ichdr_s->usedbytes -= tmp;
ichdr_s->count -= 1;
entry_d--; /* to compensate for ++ in loop hdr */
desti--;
if ((start_s + i) < offset)
result++; /* insertion index adjustment */
} else {
#endif /* GROT */
ichdr_d->firstused -= tmp;
/* both on-disk, don't endian flip twice */
entry_d->hashval = entry_s->hashval;
entry_d->nameidx = cpu_to_be16(ichdr_d->firstused);
entry_d->flags = entry_s->flags;
ASSERT(be16_to_cpu(entry_d->nameidx) + tmp
<= XFS_LBSIZE(mp));
memmove(xfs_attr3_leaf_name(leaf_d, desti),
xfs_attr3_leaf_name(leaf_s, start_s + i), tmp);
ASSERT(be16_to_cpu(entry_s->nameidx) + tmp
<= XFS_LBSIZE(mp));
memset(xfs_attr3_leaf_name(leaf_s, start_s + i), 0, tmp);
ichdr_s->usedbytes -= tmp;
ichdr_d->usedbytes += tmp;
ichdr_s->count -= 1;
ichdr_d->count += 1;
tmp = ichdr_d->count * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf_d);
ASSERT(ichdr_d->firstused >= tmp);
#ifdef GROT
}
#endif /* GROT */
}
/*
* Zero out the entries we just copied.
*/
if (start_s == ichdr_s->count) {
tmp = count * sizeof(xfs_attr_leaf_entry_t);
entry_s = &xfs_attr3_leaf_entryp(leaf_s)[start_s];
ASSERT(((char *)entry_s + tmp) <=
((char *)leaf_s + XFS_LBSIZE(mp)));
memset(entry_s, 0, tmp);
} else {
/*
* Move the remaining entries down to fill the hole,
* then zero the entries at the top.
*/
tmp = (ichdr_s->count - count) * sizeof(xfs_attr_leaf_entry_t);
entry_s = &xfs_attr3_leaf_entryp(leaf_s)[start_s + count];
entry_d = &xfs_attr3_leaf_entryp(leaf_s)[start_s];
memmove(entry_d, entry_s, tmp);
tmp = count * sizeof(xfs_attr_leaf_entry_t);
entry_s = &xfs_attr3_leaf_entryp(leaf_s)[ichdr_s->count];
ASSERT(((char *)entry_s + tmp) <=
((char *)leaf_s + XFS_LBSIZE(mp)));
memset(entry_s, 0, tmp);
}
/*
* Fill in the freemap information
*/
ichdr_d->freemap[0].base = xfs_attr3_leaf_hdr_size(leaf_d);
ichdr_d->freemap[0].base += ichdr_d->count * sizeof(xfs_attr_leaf_entry_t);
ichdr_d->freemap[0].size = ichdr_d->firstused - ichdr_d->freemap[0].base;
ichdr_d->freemap[1].base = 0;
ichdr_d->freemap[2].base = 0;
ichdr_d->freemap[1].size = 0;
ichdr_d->freemap[2].size = 0;
ichdr_s->holes = 1; /* leaf may not be compact */
}
/*
* Pick up the last hashvalue from a leaf block.
*/
xfs_dahash_t
xfs_attr_leaf_lasthash(
struct xfs_buf *bp,
int *count)
{
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entries;
xfs_attr3_leaf_hdr_from_disk(&ichdr, bp->b_addr);
entries = xfs_attr3_leaf_entryp(bp->b_addr);
if (count)
*count = ichdr.count;
if (!ichdr.count)
return 0;
return be32_to_cpu(entries[ichdr.count - 1].hashval);
}
/*
* Calculate the number of bytes used to store the indicated attribute
* (whether local or remote only calculate bytes in this block).
*/
STATIC int
xfs_attr_leaf_entsize(xfs_attr_leafblock_t *leaf, int index)
{
struct xfs_attr_leaf_entry *entries;
xfs_attr_leaf_name_local_t *name_loc;
xfs_attr_leaf_name_remote_t *name_rmt;
int size;
entries = xfs_attr3_leaf_entryp(leaf);
if (entries[index].flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, index);
size = xfs_attr_leaf_entsize_local(name_loc->namelen,
be16_to_cpu(name_loc->valuelen));
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, index);
size = xfs_attr_leaf_entsize_remote(name_rmt->namelen);
}
return size;
}
/*
* Calculate the number of bytes that would be required to store the new
* attribute (whether local or remote only calculate bytes in this block).
* This routine decides as a side effect whether the attribute will be
* a "local" or a "remote" attribute.
*/
int
xfs_attr_leaf_newentsize(int namelen, int valuelen, int blocksize, int *local)
{
int size;
size = xfs_attr_leaf_entsize_local(namelen, valuelen);
if (size < xfs_attr_leaf_entsize_local_max(blocksize)) {
if (local) {
*local = 1;
}
} else {
size = xfs_attr_leaf_entsize_remote(namelen);
if (local) {
*local = 0;
}
}
return size;
}
/*========================================================================
* Manage the INCOMPLETE flag in a leaf entry
*========================================================================*/
/*
* Clear the INCOMPLETE flag on an entry in a leaf block.
*/
int
xfs_attr3_leaf_clearflag(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_buf *bp;
int error;
#ifdef DEBUG
struct xfs_attr3_icleaf_hdr ichdr;
xfs_attr_leaf_name_local_t *name_loc;
int namelen;
char *name;
#endif /* DEBUG */
trace_xfs_attr_leaf_clearflag(args);
/*
* Set up the operation.
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return(error);
leaf = bp->b_addr;
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
ASSERT(entry->flags & XFS_ATTR_INCOMPLETE);
#ifdef DEBUG
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
ASSERT(args->index < ichdr.count);
ASSERT(args->index >= 0);
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
namelen = name_loc->namelen;
name = (char *)name_loc->nameval;
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
namelen = name_rmt->namelen;
name = (char *)name_rmt->name;
}
ASSERT(be32_to_cpu(entry->hashval) == args->hashval);
ASSERT(namelen == args->namelen);
ASSERT(memcmp(name, args->name, namelen) == 0);
#endif /* DEBUG */
entry->flags &= ~XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
if (args->rmtblkno) {
ASSERT((entry->flags & XFS_ATTR_LOCAL) == 0);
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
name_rmt->valueblk = cpu_to_be32(args->rmtblkno);
name_rmt->valuelen = cpu_to_be32(args->valuelen);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, name_rmt, sizeof(*name_rmt)));
}
/*
* Commit the flag value change and start the next trans in series.
*/
return xfs_trans_roll(&args->trans, args->dp);
}
/*
* Set the INCOMPLETE flag on an entry in a leaf block.
*/
int
xfs_attr3_leaf_setflag(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_buf *bp;
int error;
#ifdef DEBUG
struct xfs_attr3_icleaf_hdr ichdr;
#endif
trace_xfs_attr_leaf_setflag(args);
/*
* Set up the operation.
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return(error);
leaf = bp->b_addr;
#ifdef DEBUG
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
ASSERT(args->index < ichdr.count);
ASSERT(args->index >= 0);
#endif
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
ASSERT((entry->flags & XFS_ATTR_INCOMPLETE) == 0);
entry->flags |= XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
if ((entry->flags & XFS_ATTR_LOCAL) == 0) {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
name_rmt->valueblk = 0;
name_rmt->valuelen = 0;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, name_rmt, sizeof(*name_rmt)));
}
/*
* Commit the flag value change and start the next trans in series.
*/
return xfs_trans_roll(&args->trans, args->dp);
}
/*
* In a single transaction, clear the INCOMPLETE flag on the leaf entry
* given by args->blkno/index and set the INCOMPLETE flag on the leaf
* entry given by args->blkno2/index2.
*
* Note that they could be in different blocks, or in the same block.
*/
int
xfs_attr3_leaf_flipflags(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf1;
struct xfs_attr_leafblock *leaf2;
struct xfs_attr_leaf_entry *entry1;
struct xfs_attr_leaf_entry *entry2;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_buf *bp1;
struct xfs_buf *bp2;
int error;
#ifdef DEBUG
struct xfs_attr3_icleaf_hdr ichdr1;
struct xfs_attr3_icleaf_hdr ichdr2;
xfs_attr_leaf_name_local_t *name_loc;
int namelen1, namelen2;
char *name1, *name2;
#endif /* DEBUG */
trace_xfs_attr_leaf_flipflags(args);
/*
* Read the block containing the "old" attr
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp1);
if (error)
return error;
/*
* Read the block containing the "new" attr, if it is different
*/
if (args->blkno2 != args->blkno) {
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno2,
-1, &bp2);
if (error)
return error;
} else {
bp2 = bp1;
}
leaf1 = bp1->b_addr;
entry1 = &xfs_attr3_leaf_entryp(leaf1)[args->index];
leaf2 = bp2->b_addr;
entry2 = &xfs_attr3_leaf_entryp(leaf2)[args->index2];
#ifdef DEBUG
xfs_attr3_leaf_hdr_from_disk(&ichdr1, leaf1);
ASSERT(args->index < ichdr1.count);
ASSERT(args->index >= 0);
xfs_attr3_leaf_hdr_from_disk(&ichdr2, leaf2);
ASSERT(args->index2 < ichdr2.count);
ASSERT(args->index2 >= 0);
if (entry1->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf1, args->index);
namelen1 = name_loc->namelen;
name1 = (char *)name_loc->nameval;
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index);
namelen1 = name_rmt->namelen;
name1 = (char *)name_rmt->name;
}
if (entry2->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf2, args->index2);
namelen2 = name_loc->namelen;
name2 = (char *)name_loc->nameval;
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2);
namelen2 = name_rmt->namelen;
name2 = (char *)name_rmt->name;
}
ASSERT(be32_to_cpu(entry1->hashval) == be32_to_cpu(entry2->hashval));
ASSERT(namelen1 == namelen2);
ASSERT(memcmp(name1, name2, namelen1) == 0);
#endif /* DEBUG */
ASSERT(entry1->flags & XFS_ATTR_INCOMPLETE);
ASSERT((entry2->flags & XFS_ATTR_INCOMPLETE) == 0);
entry1->flags &= ~XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp1,
XFS_DA_LOGRANGE(leaf1, entry1, sizeof(*entry1)));
if (args->rmtblkno) {
ASSERT((entry1->flags & XFS_ATTR_LOCAL) == 0);
name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index);
name_rmt->valueblk = cpu_to_be32(args->rmtblkno);
name_rmt->valuelen = cpu_to_be32(args->valuelen);
xfs_trans_log_buf(args->trans, bp1,
XFS_DA_LOGRANGE(leaf1, name_rmt, sizeof(*name_rmt)));
}
entry2->flags |= XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp2,
XFS_DA_LOGRANGE(leaf2, entry2, sizeof(*entry2)));
if ((entry2->flags & XFS_ATTR_LOCAL) == 0) {
name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2);
name_rmt->valueblk = 0;
name_rmt->valuelen = 0;
xfs_trans_log_buf(args->trans, bp2,
XFS_DA_LOGRANGE(leaf2, name_rmt, sizeof(*name_rmt)));
}
/*
* Commit the flag value change and start the next trans in series.
*/
error = xfs_trans_roll(&args->trans, args->dp);
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-19/c/bad_1453_1 |
crossvul-cpp_data_good_1453_1 | /*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* Copyright (c) 2013 Red Hat, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would 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 the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_shared.h"
#include "xfs_format.h"
#include "xfs_log_format.h"
#include "xfs_trans_resv.h"
#include "xfs_bit.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_da_format.h"
#include "xfs_da_btree.h"
#include "xfs_inode.h"
#include "xfs_trans.h"
#include "xfs_inode_item.h"
#include "xfs_bmap_btree.h"
#include "xfs_bmap.h"
#include "xfs_attr_sf.h"
#include "xfs_attr_remote.h"
#include "xfs_attr.h"
#include "xfs_attr_leaf.h"
#include "xfs_error.h"
#include "xfs_trace.h"
#include "xfs_buf_item.h"
#include "xfs_cksum.h"
#include "xfs_dinode.h"
#include "xfs_dir2.h"
/*
* xfs_attr_leaf.c
*
* Routines to implement leaf blocks of attributes as Btrees of hashed names.
*/
/*========================================================================
* Function prototypes for the kernel.
*========================================================================*/
/*
* Routines used for growing the Btree.
*/
STATIC int xfs_attr3_leaf_create(struct xfs_da_args *args,
xfs_dablk_t which_block, struct xfs_buf **bpp);
STATIC int xfs_attr3_leaf_add_work(struct xfs_buf *leaf_buffer,
struct xfs_attr3_icleaf_hdr *ichdr,
struct xfs_da_args *args, int freemap_index);
STATIC void xfs_attr3_leaf_compact(struct xfs_da_args *args,
struct xfs_attr3_icleaf_hdr *ichdr,
struct xfs_buf *leaf_buffer);
STATIC void xfs_attr3_leaf_rebalance(xfs_da_state_t *state,
xfs_da_state_blk_t *blk1,
xfs_da_state_blk_t *blk2);
STATIC int xfs_attr3_leaf_figure_balance(xfs_da_state_t *state,
xfs_da_state_blk_t *leaf_blk_1,
struct xfs_attr3_icleaf_hdr *ichdr1,
xfs_da_state_blk_t *leaf_blk_2,
struct xfs_attr3_icleaf_hdr *ichdr2,
int *number_entries_in_blk1,
int *number_usedbytes_in_blk1);
/*
* Utility routines.
*/
STATIC void xfs_attr3_leaf_moveents(struct xfs_attr_leafblock *src_leaf,
struct xfs_attr3_icleaf_hdr *src_ichdr, int src_start,
struct xfs_attr_leafblock *dst_leaf,
struct xfs_attr3_icleaf_hdr *dst_ichdr, int dst_start,
int move_count, struct xfs_mount *mp);
STATIC int xfs_attr_leaf_entsize(xfs_attr_leafblock_t *leaf, int index);
void
xfs_attr3_leaf_hdr_from_disk(
struct xfs_attr3_icleaf_hdr *to,
struct xfs_attr_leafblock *from)
{
int i;
ASSERT(from->hdr.info.magic == cpu_to_be16(XFS_ATTR_LEAF_MAGIC) ||
from->hdr.info.magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC));
if (from->hdr.info.magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC)) {
struct xfs_attr3_leaf_hdr *hdr3 = (struct xfs_attr3_leaf_hdr *)from;
to->forw = be32_to_cpu(hdr3->info.hdr.forw);
to->back = be32_to_cpu(hdr3->info.hdr.back);
to->magic = be16_to_cpu(hdr3->info.hdr.magic);
to->count = be16_to_cpu(hdr3->count);
to->usedbytes = be16_to_cpu(hdr3->usedbytes);
to->firstused = be16_to_cpu(hdr3->firstused);
to->holes = hdr3->holes;
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
to->freemap[i].base = be16_to_cpu(hdr3->freemap[i].base);
to->freemap[i].size = be16_to_cpu(hdr3->freemap[i].size);
}
return;
}
to->forw = be32_to_cpu(from->hdr.info.forw);
to->back = be32_to_cpu(from->hdr.info.back);
to->magic = be16_to_cpu(from->hdr.info.magic);
to->count = be16_to_cpu(from->hdr.count);
to->usedbytes = be16_to_cpu(from->hdr.usedbytes);
to->firstused = be16_to_cpu(from->hdr.firstused);
to->holes = from->hdr.holes;
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
to->freemap[i].base = be16_to_cpu(from->hdr.freemap[i].base);
to->freemap[i].size = be16_to_cpu(from->hdr.freemap[i].size);
}
}
void
xfs_attr3_leaf_hdr_to_disk(
struct xfs_attr_leafblock *to,
struct xfs_attr3_icleaf_hdr *from)
{
int i;
ASSERT(from->magic == XFS_ATTR_LEAF_MAGIC ||
from->magic == XFS_ATTR3_LEAF_MAGIC);
if (from->magic == XFS_ATTR3_LEAF_MAGIC) {
struct xfs_attr3_leaf_hdr *hdr3 = (struct xfs_attr3_leaf_hdr *)to;
hdr3->info.hdr.forw = cpu_to_be32(from->forw);
hdr3->info.hdr.back = cpu_to_be32(from->back);
hdr3->info.hdr.magic = cpu_to_be16(from->magic);
hdr3->count = cpu_to_be16(from->count);
hdr3->usedbytes = cpu_to_be16(from->usedbytes);
hdr3->firstused = cpu_to_be16(from->firstused);
hdr3->holes = from->holes;
hdr3->pad1 = 0;
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
hdr3->freemap[i].base = cpu_to_be16(from->freemap[i].base);
hdr3->freemap[i].size = cpu_to_be16(from->freemap[i].size);
}
return;
}
to->hdr.info.forw = cpu_to_be32(from->forw);
to->hdr.info.back = cpu_to_be32(from->back);
to->hdr.info.magic = cpu_to_be16(from->magic);
to->hdr.count = cpu_to_be16(from->count);
to->hdr.usedbytes = cpu_to_be16(from->usedbytes);
to->hdr.firstused = cpu_to_be16(from->firstused);
to->hdr.holes = from->holes;
to->hdr.pad1 = 0;
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
to->hdr.freemap[i].base = cpu_to_be16(from->freemap[i].base);
to->hdr.freemap[i].size = cpu_to_be16(from->freemap[i].size);
}
}
static bool
xfs_attr3_leaf_verify(
struct xfs_buf *bp)
{
struct xfs_mount *mp = bp->b_target->bt_mount;
struct xfs_attr_leafblock *leaf = bp->b_addr;
struct xfs_attr3_icleaf_hdr ichdr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
if (xfs_sb_version_hascrc(&mp->m_sb)) {
struct xfs_da3_node_hdr *hdr3 = bp->b_addr;
if (ichdr.magic != XFS_ATTR3_LEAF_MAGIC)
return false;
if (!uuid_equal(&hdr3->info.uuid, &mp->m_sb.sb_uuid))
return false;
if (be64_to_cpu(hdr3->info.blkno) != bp->b_bn)
return false;
} else {
if (ichdr.magic != XFS_ATTR_LEAF_MAGIC)
return false;
}
if (ichdr.count == 0)
return false;
/* XXX: need to range check rest of attr header values */
/* XXX: hash order check? */
return true;
}
static void
xfs_attr3_leaf_write_verify(
struct xfs_buf *bp)
{
struct xfs_mount *mp = bp->b_target->bt_mount;
struct xfs_buf_log_item *bip = bp->b_fspriv;
struct xfs_attr3_leaf_hdr *hdr3 = bp->b_addr;
if (!xfs_attr3_leaf_verify(bp)) {
xfs_buf_ioerror(bp, EFSCORRUPTED);
xfs_verifier_error(bp);
return;
}
if (!xfs_sb_version_hascrc(&mp->m_sb))
return;
if (bip)
hdr3->info.lsn = cpu_to_be64(bip->bli_item.li_lsn);
xfs_buf_update_cksum(bp, XFS_ATTR3_LEAF_CRC_OFF);
}
/*
* leaf/node format detection on trees is sketchy, so a node read can be done on
* leaf level blocks when detection identifies the tree as a node format tree
* incorrectly. In this case, we need to swap the verifier to match the correct
* format of the block being read.
*/
static void
xfs_attr3_leaf_read_verify(
struct xfs_buf *bp)
{
struct xfs_mount *mp = bp->b_target->bt_mount;
if (xfs_sb_version_hascrc(&mp->m_sb) &&
!xfs_buf_verify_cksum(bp, XFS_ATTR3_LEAF_CRC_OFF))
xfs_buf_ioerror(bp, EFSBADCRC);
else if (!xfs_attr3_leaf_verify(bp))
xfs_buf_ioerror(bp, EFSCORRUPTED);
if (bp->b_error)
xfs_verifier_error(bp);
}
const struct xfs_buf_ops xfs_attr3_leaf_buf_ops = {
.verify_read = xfs_attr3_leaf_read_verify,
.verify_write = xfs_attr3_leaf_write_verify,
};
int
xfs_attr3_leaf_read(
struct xfs_trans *tp,
struct xfs_inode *dp,
xfs_dablk_t bno,
xfs_daddr_t mappedbno,
struct xfs_buf **bpp)
{
int err;
err = xfs_da_read_buf(tp, dp, bno, mappedbno, bpp,
XFS_ATTR_FORK, &xfs_attr3_leaf_buf_ops);
if (!err && tp)
xfs_trans_buf_set_type(tp, *bpp, XFS_BLFT_ATTR_LEAF_BUF);
return err;
}
/*========================================================================
* Namespace helper routines
*========================================================================*/
/*
* If namespace bits don't match return 0.
* If all match then return 1.
*/
STATIC int
xfs_attr_namesp_match(int arg_flags, int ondisk_flags)
{
return XFS_ATTR_NSP_ONDISK(ondisk_flags) == XFS_ATTR_NSP_ARGS_TO_ONDISK(arg_flags);
}
/*========================================================================
* External routines when attribute fork size < XFS_LITINO(mp).
*========================================================================*/
/*
* Query whether the requested number of additional bytes of extended
* attribute space will be able to fit inline.
*
* Returns zero if not, else the di_forkoff fork offset to be used in the
* literal area for attribute data once the new bytes have been added.
*
* di_forkoff must be 8 byte aligned, hence is stored as a >>3 value;
* special case for dev/uuid inodes, they have fixed size data forks.
*/
int
xfs_attr_shortform_bytesfit(xfs_inode_t *dp, int bytes)
{
int offset;
int minforkoff; /* lower limit on valid forkoff locations */
int maxforkoff; /* upper limit on valid forkoff locations */
int dsize;
xfs_mount_t *mp = dp->i_mount;
/* rounded down */
offset = (XFS_LITINO(mp, dp->i_d.di_version) - bytes) >> 3;
switch (dp->i_d.di_format) {
case XFS_DINODE_FMT_DEV:
minforkoff = roundup(sizeof(xfs_dev_t), 8) >> 3;
return (offset >= minforkoff) ? minforkoff : 0;
case XFS_DINODE_FMT_UUID:
minforkoff = roundup(sizeof(uuid_t), 8) >> 3;
return (offset >= minforkoff) ? minforkoff : 0;
}
/*
* If the requested numbers of bytes is smaller or equal to the
* current attribute fork size we can always proceed.
*
* Note that if_bytes in the data fork might actually be larger than
* the current data fork size is due to delalloc extents. In that
* case either the extent count will go down when they are converted
* to real extents, or the delalloc conversion will take care of the
* literal area rebalancing.
*/
if (bytes <= XFS_IFORK_ASIZE(dp))
return dp->i_d.di_forkoff;
/*
* For attr2 we can try to move the forkoff if there is space in the
* literal area, but for the old format we are done if there is no
* space in the fixed attribute fork.
*/
if (!(mp->m_flags & XFS_MOUNT_ATTR2))
return 0;
dsize = dp->i_df.if_bytes;
switch (dp->i_d.di_format) {
case XFS_DINODE_FMT_EXTENTS:
/*
* If there is no attr fork and the data fork is extents,
* determine if creating the default attr fork will result
* in the extents form migrating to btree. If so, the
* minimum offset only needs to be the space required for
* the btree root.
*/
if (!dp->i_d.di_forkoff && dp->i_df.if_bytes >
xfs_default_attroffset(dp))
dsize = XFS_BMDR_SPACE_CALC(MINDBTPTRS);
break;
case XFS_DINODE_FMT_BTREE:
/*
* If we have a data btree then keep forkoff if we have one,
* otherwise we are adding a new attr, so then we set
* minforkoff to where the btree root can finish so we have
* plenty of room for attrs
*/
if (dp->i_d.di_forkoff) {
if (offset < dp->i_d.di_forkoff)
return 0;
return dp->i_d.di_forkoff;
}
dsize = XFS_BMAP_BROOT_SPACE(mp, dp->i_df.if_broot);
break;
}
/*
* A data fork btree root must have space for at least
* MINDBTPTRS key/ptr pairs if the data fork is small or empty.
*/
minforkoff = MAX(dsize, XFS_BMDR_SPACE_CALC(MINDBTPTRS));
minforkoff = roundup(minforkoff, 8) >> 3;
/* attr fork btree root can have at least this many key/ptr pairs */
maxforkoff = XFS_LITINO(mp, dp->i_d.di_version) -
XFS_BMDR_SPACE_CALC(MINABTPTRS);
maxforkoff = maxforkoff >> 3; /* rounded down */
if (offset >= maxforkoff)
return maxforkoff;
if (offset >= minforkoff)
return offset;
return 0;
}
/*
* Switch on the ATTR2 superblock bit (implies also FEATURES2)
*/
STATIC void
xfs_sbversion_add_attr2(xfs_mount_t *mp, xfs_trans_t *tp)
{
if ((mp->m_flags & XFS_MOUNT_ATTR2) &&
!(xfs_sb_version_hasattr2(&mp->m_sb))) {
spin_lock(&mp->m_sb_lock);
if (!xfs_sb_version_hasattr2(&mp->m_sb)) {
xfs_sb_version_addattr2(&mp->m_sb);
spin_unlock(&mp->m_sb_lock);
xfs_mod_sb(tp, XFS_SB_VERSIONNUM | XFS_SB_FEATURES2);
} else
spin_unlock(&mp->m_sb_lock);
}
}
/*
* Create the initial contents of a shortform attribute list.
*/
void
xfs_attr_shortform_create(xfs_da_args_t *args)
{
xfs_attr_sf_hdr_t *hdr;
xfs_inode_t *dp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_create(args);
dp = args->dp;
ASSERT(dp != NULL);
ifp = dp->i_afp;
ASSERT(ifp != NULL);
ASSERT(ifp->if_bytes == 0);
if (dp->i_d.di_aformat == XFS_DINODE_FMT_EXTENTS) {
ifp->if_flags &= ~XFS_IFEXTENTS; /* just in case */
dp->i_d.di_aformat = XFS_DINODE_FMT_LOCAL;
ifp->if_flags |= XFS_IFINLINE;
} else {
ASSERT(ifp->if_flags & XFS_IFINLINE);
}
xfs_idata_realloc(dp, sizeof(*hdr), XFS_ATTR_FORK);
hdr = (xfs_attr_sf_hdr_t *)ifp->if_u1.if_data;
hdr->count = 0;
hdr->totsize = cpu_to_be16(sizeof(*hdr));
xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_ADATA);
}
/*
* Add a name/value pair to the shortform attribute list.
* Overflow from the inode has already been checked for.
*/
void
xfs_attr_shortform_add(xfs_da_args_t *args, int forkoff)
{
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
int i, offset, size;
xfs_mount_t *mp;
xfs_inode_t *dp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_add(args);
dp = args->dp;
mp = dp->i_mount;
dp->i_d.di_forkoff = forkoff;
ifp = dp->i_afp;
ASSERT(ifp->if_flags & XFS_IFINLINE);
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count; sfe = XFS_ATTR_SF_NEXTENTRY(sfe), i++) {
#ifdef DEBUG
if (sfe->namelen != args->namelen)
continue;
if (memcmp(args->name, sfe->nameval, args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, sfe->flags))
continue;
ASSERT(0);
#endif
}
offset = (char *)sfe - (char *)sf;
size = XFS_ATTR_SF_ENTSIZE_BYNAME(args->namelen, args->valuelen);
xfs_idata_realloc(dp, size, XFS_ATTR_FORK);
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
sfe = (xfs_attr_sf_entry_t *)((char *)sf + offset);
sfe->namelen = args->namelen;
sfe->valuelen = args->valuelen;
sfe->flags = XFS_ATTR_NSP_ARGS_TO_ONDISK(args->flags);
memcpy(sfe->nameval, args->name, args->namelen);
memcpy(&sfe->nameval[args->namelen], args->value, args->valuelen);
sf->hdr.count++;
be16_add_cpu(&sf->hdr.totsize, size);
xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_ADATA);
xfs_sbversion_add_attr2(mp, args->trans);
}
/*
* After the last attribute is removed revert to original inode format,
* making all literal area available to the data fork once more.
*/
STATIC void
xfs_attr_fork_reset(
struct xfs_inode *ip,
struct xfs_trans *tp)
{
xfs_idestroy_fork(ip, XFS_ATTR_FORK);
ip->i_d.di_forkoff = 0;
ip->i_d.di_aformat = XFS_DINODE_FMT_EXTENTS;
ASSERT(ip->i_d.di_anextents == 0);
ASSERT(ip->i_afp == NULL);
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
}
/*
* Remove an attribute from the shortform attribute list structure.
*/
int
xfs_attr_shortform_remove(xfs_da_args_t *args)
{
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
int base, size=0, end, totsize, i;
xfs_mount_t *mp;
xfs_inode_t *dp;
trace_xfs_attr_sf_remove(args);
dp = args->dp;
mp = dp->i_mount;
base = sizeof(xfs_attr_sf_hdr_t);
sf = (xfs_attr_shortform_t *)dp->i_afp->if_u1.if_data;
sfe = &sf->list[0];
end = sf->hdr.count;
for (i = 0; i < end; sfe = XFS_ATTR_SF_NEXTENTRY(sfe),
base += size, i++) {
size = XFS_ATTR_SF_ENTSIZE(sfe);
if (sfe->namelen != args->namelen)
continue;
if (memcmp(sfe->nameval, args->name, args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, sfe->flags))
continue;
break;
}
if (i == end)
return(XFS_ERROR(ENOATTR));
/*
* Fix up the attribute fork data, covering the hole
*/
end = base + size;
totsize = be16_to_cpu(sf->hdr.totsize);
if (end != totsize)
memmove(&((char *)sf)[base], &((char *)sf)[end], totsize - end);
sf->hdr.count--;
be16_add_cpu(&sf->hdr.totsize, -size);
/*
* Fix up the start offset of the attribute fork
*/
totsize -= size;
if (totsize == sizeof(xfs_attr_sf_hdr_t) &&
(mp->m_flags & XFS_MOUNT_ATTR2) &&
(dp->i_d.di_format != XFS_DINODE_FMT_BTREE) &&
!(args->op_flags & XFS_DA_OP_ADDNAME)) {
xfs_attr_fork_reset(dp, args->trans);
} else {
xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
dp->i_d.di_forkoff = xfs_attr_shortform_bytesfit(dp, totsize);
ASSERT(dp->i_d.di_forkoff);
ASSERT(totsize > sizeof(xfs_attr_sf_hdr_t) ||
(args->op_flags & XFS_DA_OP_ADDNAME) ||
!(mp->m_flags & XFS_MOUNT_ATTR2) ||
dp->i_d.di_format == XFS_DINODE_FMT_BTREE);
xfs_trans_log_inode(args->trans, dp,
XFS_ILOG_CORE | XFS_ILOG_ADATA);
}
xfs_sbversion_add_attr2(mp, args->trans);
return(0);
}
/*
* Look up a name in a shortform attribute list structure.
*/
/*ARGSUSED*/
int
xfs_attr_shortform_lookup(xfs_da_args_t *args)
{
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
int i;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_lookup(args);
ifp = args->dp->i_afp;
ASSERT(ifp->if_flags & XFS_IFINLINE);
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe), i++) {
if (sfe->namelen != args->namelen)
continue;
if (memcmp(args->name, sfe->nameval, args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, sfe->flags))
continue;
return(XFS_ERROR(EEXIST));
}
return(XFS_ERROR(ENOATTR));
}
/*
* Look up a name in a shortform attribute list structure.
*/
/*ARGSUSED*/
int
xfs_attr_shortform_getvalue(xfs_da_args_t *args)
{
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
int i;
ASSERT(args->dp->i_afp->if_flags == XFS_IFINLINE);
sf = (xfs_attr_shortform_t *)args->dp->i_afp->if_u1.if_data;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe), i++) {
if (sfe->namelen != args->namelen)
continue;
if (memcmp(args->name, sfe->nameval, args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, sfe->flags))
continue;
if (args->flags & ATTR_KERNOVAL) {
args->valuelen = sfe->valuelen;
return(XFS_ERROR(EEXIST));
}
if (args->valuelen < sfe->valuelen) {
args->valuelen = sfe->valuelen;
return(XFS_ERROR(ERANGE));
}
args->valuelen = sfe->valuelen;
memcpy(args->value, &sfe->nameval[args->namelen],
args->valuelen);
return(XFS_ERROR(EEXIST));
}
return(XFS_ERROR(ENOATTR));
}
/*
* Convert from using the shortform to the leaf.
*/
int
xfs_attr_shortform_to_leaf(xfs_da_args_t *args)
{
xfs_inode_t *dp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_da_args_t nargs;
char *tmpbuffer;
int error, i, size;
xfs_dablk_t blkno;
struct xfs_buf *bp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_to_leaf(args);
dp = args->dp;
ifp = dp->i_afp;
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
size = be16_to_cpu(sf->hdr.totsize);
tmpbuffer = kmem_alloc(size, KM_SLEEP);
ASSERT(tmpbuffer != NULL);
memcpy(tmpbuffer, ifp->if_u1.if_data, size);
sf = (xfs_attr_shortform_t *)tmpbuffer;
xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
xfs_bmap_local_to_extents_empty(dp, XFS_ATTR_FORK);
bp = NULL;
error = xfs_da_grow_inode(args, &blkno);
if (error) {
/*
* If we hit an IO error middle of the transaction inside
* grow_inode(), we may have inconsistent data. Bail out.
*/
if (error == EIO)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
ASSERT(blkno == 0);
error = xfs_attr3_leaf_create(args, blkno, &bp);
if (error) {
error = xfs_da_shrink_inode(args, 0, bp);
bp = NULL;
if (error)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
memset((char *)&nargs, 0, sizeof(nargs));
nargs.dp = dp;
nargs.firstblock = args->firstblock;
nargs.flist = args->flist;
nargs.total = args->total;
nargs.whichfork = XFS_ATTR_FORK;
nargs.trans = args->trans;
nargs.op_flags = XFS_DA_OP_OKNOENT;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count; i++) {
nargs.name = sfe->nameval;
nargs.namelen = sfe->namelen;
nargs.value = &sfe->nameval[nargs.namelen];
nargs.valuelen = sfe->valuelen;
nargs.hashval = xfs_da_hashname(sfe->nameval,
sfe->namelen);
nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(sfe->flags);
error = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */
ASSERT(error == ENOATTR);
error = xfs_attr3_leaf_add(bp, &nargs);
ASSERT(error != ENOSPC);
if (error)
goto out;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
error = 0;
out:
kmem_free(tmpbuffer);
return(error);
}
/*
* Check a leaf attribute block to see if all the entries would fit into
* a shortform attribute list.
*/
int
xfs_attr_shortform_allfit(
struct xfs_buf *bp,
struct xfs_inode *dp)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
xfs_attr_leaf_name_local_t *name_loc;
struct xfs_attr3_icleaf_hdr leafhdr;
int bytes;
int i;
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&leafhdr, leaf);
entry = xfs_attr3_leaf_entryp(leaf);
bytes = sizeof(struct xfs_attr_sf_hdr);
for (i = 0; i < leafhdr.count; entry++, i++) {
if (entry->flags & XFS_ATTR_INCOMPLETE)
continue; /* don't copy partial entries */
if (!(entry->flags & XFS_ATTR_LOCAL))
return(0);
name_loc = xfs_attr3_leaf_name_local(leaf, i);
if (name_loc->namelen >= XFS_ATTR_SF_ENTSIZE_MAX)
return(0);
if (be16_to_cpu(name_loc->valuelen) >= XFS_ATTR_SF_ENTSIZE_MAX)
return(0);
bytes += sizeof(struct xfs_attr_sf_entry) - 1
+ name_loc->namelen
+ be16_to_cpu(name_loc->valuelen);
}
if ((dp->i_mount->m_flags & XFS_MOUNT_ATTR2) &&
(dp->i_d.di_format != XFS_DINODE_FMT_BTREE) &&
(bytes == sizeof(struct xfs_attr_sf_hdr)))
return -1;
return xfs_attr_shortform_bytesfit(dp, bytes);
}
/*
* Convert a leaf attribute list to shortform attribute list
*/
int
xfs_attr3_leaf_to_shortform(
struct xfs_buf *bp,
struct xfs_da_args *args,
int forkoff)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_da_args nargs;
struct xfs_inode *dp = args->dp;
char *tmpbuffer;
int error;
int i;
trace_xfs_attr_leaf_to_sf(args);
tmpbuffer = kmem_alloc(XFS_LBSIZE(dp->i_mount), KM_SLEEP);
if (!tmpbuffer)
return ENOMEM;
memcpy(tmpbuffer, bp->b_addr, XFS_LBSIZE(dp->i_mount));
leaf = (xfs_attr_leafblock_t *)tmpbuffer;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
entry = xfs_attr3_leaf_entryp(leaf);
/* XXX (dgc): buffer is about to be marked stale - why zero it? */
memset(bp->b_addr, 0, XFS_LBSIZE(dp->i_mount));
/*
* Clean out the prior contents of the attribute list.
*/
error = xfs_da_shrink_inode(args, 0, bp);
if (error)
goto out;
if (forkoff == -1) {
ASSERT(dp->i_mount->m_flags & XFS_MOUNT_ATTR2);
ASSERT(dp->i_d.di_format != XFS_DINODE_FMT_BTREE);
xfs_attr_fork_reset(dp, args->trans);
goto out;
}
xfs_attr_shortform_create(args);
/*
* Copy the attributes
*/
memset((char *)&nargs, 0, sizeof(nargs));
nargs.dp = dp;
nargs.firstblock = args->firstblock;
nargs.flist = args->flist;
nargs.total = args->total;
nargs.whichfork = XFS_ATTR_FORK;
nargs.trans = args->trans;
nargs.op_flags = XFS_DA_OP_OKNOENT;
for (i = 0; i < ichdr.count; entry++, i++) {
if (entry->flags & XFS_ATTR_INCOMPLETE)
continue; /* don't copy partial entries */
if (!entry->nameidx)
continue;
ASSERT(entry->flags & XFS_ATTR_LOCAL);
name_loc = xfs_attr3_leaf_name_local(leaf, i);
nargs.name = name_loc->nameval;
nargs.namelen = name_loc->namelen;
nargs.value = &name_loc->nameval[nargs.namelen];
nargs.valuelen = be16_to_cpu(name_loc->valuelen);
nargs.hashval = be32_to_cpu(entry->hashval);
nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(entry->flags);
xfs_attr_shortform_add(&nargs, forkoff);
}
error = 0;
out:
kmem_free(tmpbuffer);
return error;
}
/*
* Convert from using a single leaf to a root node and a leaf.
*/
int
xfs_attr3_leaf_to_node(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr icleafhdr;
struct xfs_attr_leaf_entry *entries;
struct xfs_da_node_entry *btree;
struct xfs_da3_icnode_hdr icnodehdr;
struct xfs_da_intnode *node;
struct xfs_inode *dp = args->dp;
struct xfs_mount *mp = dp->i_mount;
struct xfs_buf *bp1 = NULL;
struct xfs_buf *bp2 = NULL;
xfs_dablk_t blkno;
int error;
trace_xfs_attr_leaf_to_node(args);
error = xfs_da_grow_inode(args, &blkno);
if (error)
goto out;
error = xfs_attr3_leaf_read(args->trans, dp, 0, -1, &bp1);
if (error)
goto out;
error = xfs_da_get_buf(args->trans, dp, blkno, -1, &bp2, XFS_ATTR_FORK);
if (error)
goto out;
/* copy leaf to new buffer, update identifiers */
xfs_trans_buf_set_type(args->trans, bp2, XFS_BLFT_ATTR_LEAF_BUF);
bp2->b_ops = bp1->b_ops;
memcpy(bp2->b_addr, bp1->b_addr, XFS_LBSIZE(mp));
if (xfs_sb_version_hascrc(&mp->m_sb)) {
struct xfs_da3_blkinfo *hdr3 = bp2->b_addr;
hdr3->blkno = cpu_to_be64(bp2->b_bn);
}
xfs_trans_log_buf(args->trans, bp2, 0, XFS_LBSIZE(mp) - 1);
/*
* Set up the new root node.
*/
error = xfs_da3_node_create(args, 0, 1, &bp1, XFS_ATTR_FORK);
if (error)
goto out;
node = bp1->b_addr;
dp->d_ops->node_hdr_from_disk(&icnodehdr, node);
btree = dp->d_ops->node_tree_p(node);
leaf = bp2->b_addr;
xfs_attr3_leaf_hdr_from_disk(&icleafhdr, leaf);
entries = xfs_attr3_leaf_entryp(leaf);
/* both on-disk, don't endian-flip twice */
btree[0].hashval = entries[icleafhdr.count - 1].hashval;
btree[0].before = cpu_to_be32(blkno);
icnodehdr.count = 1;
dp->d_ops->node_hdr_to_disk(node, &icnodehdr);
xfs_trans_log_buf(args->trans, bp1, 0, XFS_LBSIZE(mp) - 1);
error = 0;
out:
return error;
}
/*========================================================================
* Routines used for growing the Btree.
*========================================================================*/
/*
* Create the initial contents of a leaf attribute list
* or a leaf in a node attribute list.
*/
STATIC int
xfs_attr3_leaf_create(
struct xfs_da_args *args,
xfs_dablk_t blkno,
struct xfs_buf **bpp)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_inode *dp = args->dp;
struct xfs_mount *mp = dp->i_mount;
struct xfs_buf *bp;
int error;
trace_xfs_attr_leaf_create(args);
error = xfs_da_get_buf(args->trans, args->dp, blkno, -1, &bp,
XFS_ATTR_FORK);
if (error)
return error;
bp->b_ops = &xfs_attr3_leaf_buf_ops;
xfs_trans_buf_set_type(args->trans, bp, XFS_BLFT_ATTR_LEAF_BUF);
leaf = bp->b_addr;
memset(leaf, 0, XFS_LBSIZE(mp));
memset(&ichdr, 0, sizeof(ichdr));
ichdr.firstused = XFS_LBSIZE(mp);
if (xfs_sb_version_hascrc(&mp->m_sb)) {
struct xfs_da3_blkinfo *hdr3 = bp->b_addr;
ichdr.magic = XFS_ATTR3_LEAF_MAGIC;
hdr3->blkno = cpu_to_be64(bp->b_bn);
hdr3->owner = cpu_to_be64(dp->i_ino);
uuid_copy(&hdr3->uuid, &mp->m_sb.sb_uuid);
ichdr.freemap[0].base = sizeof(struct xfs_attr3_leaf_hdr);
} else {
ichdr.magic = XFS_ATTR_LEAF_MAGIC;
ichdr.freemap[0].base = sizeof(struct xfs_attr_leaf_hdr);
}
ichdr.freemap[0].size = ichdr.firstused - ichdr.freemap[0].base;
xfs_attr3_leaf_hdr_to_disk(leaf, &ichdr);
xfs_trans_log_buf(args->trans, bp, 0, XFS_LBSIZE(mp) - 1);
*bpp = bp;
return 0;
}
/*
* Split the leaf node, rebalance, then add the new entry.
*/
int
xfs_attr3_leaf_split(
struct xfs_da_state *state,
struct xfs_da_state_blk *oldblk,
struct xfs_da_state_blk *newblk)
{
xfs_dablk_t blkno;
int error;
trace_xfs_attr_leaf_split(state->args);
/*
* Allocate space for a new leaf node.
*/
ASSERT(oldblk->magic == XFS_ATTR_LEAF_MAGIC);
error = xfs_da_grow_inode(state->args, &blkno);
if (error)
return(error);
error = xfs_attr3_leaf_create(state->args, blkno, &newblk->bp);
if (error)
return(error);
newblk->blkno = blkno;
newblk->magic = XFS_ATTR_LEAF_MAGIC;
/*
* Rebalance the entries across the two leaves.
* NOTE: rebalance() currently depends on the 2nd block being empty.
*/
xfs_attr3_leaf_rebalance(state, oldblk, newblk);
error = xfs_da3_blk_link(state, oldblk, newblk);
if (error)
return(error);
/*
* Save info on "old" attribute for "atomic rename" ops, leaf_add()
* modifies the index/blkno/rmtblk/rmtblkcnt fields to show the
* "new" attrs info. Will need the "old" info to remove it later.
*
* Insert the "new" entry in the correct block.
*/
if (state->inleaf) {
trace_xfs_attr_leaf_add_old(state->args);
error = xfs_attr3_leaf_add(oldblk->bp, state->args);
} else {
trace_xfs_attr_leaf_add_new(state->args);
error = xfs_attr3_leaf_add(newblk->bp, state->args);
}
/*
* Update last hashval in each block since we added the name.
*/
oldblk->hashval = xfs_attr_leaf_lasthash(oldblk->bp, NULL);
newblk->hashval = xfs_attr_leaf_lasthash(newblk->bp, NULL);
return(error);
}
/*
* Add a name to the leaf attribute list structure.
*/
int
xfs_attr3_leaf_add(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
int tablesize;
int entsize;
int sum;
int tmp;
int i;
trace_xfs_attr_leaf_add(args);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
ASSERT(args->index >= 0 && args->index <= ichdr.count);
entsize = xfs_attr_leaf_newentsize(args->namelen, args->valuelen,
args->trans->t_mountp->m_sb.sb_blocksize, NULL);
/*
* Search through freemap for first-fit on new name length.
* (may need to figure in size of entry struct too)
*/
tablesize = (ichdr.count + 1) * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf);
for (sum = 0, i = XFS_ATTR_LEAF_MAPSIZE - 1; i >= 0; i--) {
if (tablesize > ichdr.firstused) {
sum += ichdr.freemap[i].size;
continue;
}
if (!ichdr.freemap[i].size)
continue; /* no space in this map */
tmp = entsize;
if (ichdr.freemap[i].base < ichdr.firstused)
tmp += sizeof(xfs_attr_leaf_entry_t);
if (ichdr.freemap[i].size >= tmp) {
tmp = xfs_attr3_leaf_add_work(bp, &ichdr, args, i);
goto out_log_hdr;
}
sum += ichdr.freemap[i].size;
}
/*
* If there are no holes in the address space of the block,
* and we don't have enough freespace, then compaction will do us
* no good and we should just give up.
*/
if (!ichdr.holes && sum < entsize)
return XFS_ERROR(ENOSPC);
/*
* Compact the entries to coalesce free space.
* This may change the hdr->count via dropping INCOMPLETE entries.
*/
xfs_attr3_leaf_compact(args, &ichdr, bp);
/*
* After compaction, the block is guaranteed to have only one
* free region, in freemap[0]. If it is not big enough, give up.
*/
if (ichdr.freemap[0].size < (entsize + sizeof(xfs_attr_leaf_entry_t))) {
tmp = ENOSPC;
goto out_log_hdr;
}
tmp = xfs_attr3_leaf_add_work(bp, &ichdr, args, 0);
out_log_hdr:
xfs_attr3_leaf_hdr_to_disk(leaf, &ichdr);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, &leaf->hdr,
xfs_attr3_leaf_hdr_size(leaf)));
return tmp;
}
/*
* Add a name to a leaf attribute list structure.
*/
STATIC int
xfs_attr3_leaf_add_work(
struct xfs_buf *bp,
struct xfs_attr3_icleaf_hdr *ichdr,
struct xfs_da_args *args,
int mapindex)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_mount *mp;
int tmp;
int i;
trace_xfs_attr_leaf_add_work(args);
leaf = bp->b_addr;
ASSERT(mapindex >= 0 && mapindex < XFS_ATTR_LEAF_MAPSIZE);
ASSERT(args->index >= 0 && args->index <= ichdr->count);
/*
* Force open some space in the entry array and fill it in.
*/
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
if (args->index < ichdr->count) {
tmp = ichdr->count - args->index;
tmp *= sizeof(xfs_attr_leaf_entry_t);
memmove(entry + 1, entry, tmp);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(*entry)));
}
ichdr->count++;
/*
* Allocate space for the new string (at the end of the run).
*/
mp = args->trans->t_mountp;
ASSERT(ichdr->freemap[mapindex].base < XFS_LBSIZE(mp));
ASSERT((ichdr->freemap[mapindex].base & 0x3) == 0);
ASSERT(ichdr->freemap[mapindex].size >=
xfs_attr_leaf_newentsize(args->namelen, args->valuelen,
mp->m_sb.sb_blocksize, NULL));
ASSERT(ichdr->freemap[mapindex].size < XFS_LBSIZE(mp));
ASSERT((ichdr->freemap[mapindex].size & 0x3) == 0);
ichdr->freemap[mapindex].size -=
xfs_attr_leaf_newentsize(args->namelen, args->valuelen,
mp->m_sb.sb_blocksize, &tmp);
entry->nameidx = cpu_to_be16(ichdr->freemap[mapindex].base +
ichdr->freemap[mapindex].size);
entry->hashval = cpu_to_be32(args->hashval);
entry->flags = tmp ? XFS_ATTR_LOCAL : 0;
entry->flags |= XFS_ATTR_NSP_ARGS_TO_ONDISK(args->flags);
if (args->op_flags & XFS_DA_OP_RENAME) {
entry->flags |= XFS_ATTR_INCOMPLETE;
if ((args->blkno2 == args->blkno) &&
(args->index2 <= args->index)) {
args->index2++;
}
}
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
ASSERT((args->index == 0) ||
(be32_to_cpu(entry->hashval) >= be32_to_cpu((entry-1)->hashval)));
ASSERT((args->index == ichdr->count - 1) ||
(be32_to_cpu(entry->hashval) <= be32_to_cpu((entry+1)->hashval)));
/*
* For "remote" attribute values, simply note that we need to
* allocate space for the "remote" value. We can't actually
* allocate the extents in this transaction, and we can't decide
* which blocks they should be as we might allocate more blocks
* as part of this transaction (a split operation for example).
*/
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
name_loc->namelen = args->namelen;
name_loc->valuelen = cpu_to_be16(args->valuelen);
memcpy((char *)name_loc->nameval, args->name, args->namelen);
memcpy((char *)&name_loc->nameval[args->namelen], args->value,
be16_to_cpu(name_loc->valuelen));
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
name_rmt->namelen = args->namelen;
memcpy((char *)name_rmt->name, args->name, args->namelen);
entry->flags |= XFS_ATTR_INCOMPLETE;
/* just in case */
name_rmt->valuelen = 0;
name_rmt->valueblk = 0;
args->rmtblkno = 1;
args->rmtblkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen);
args->rmtvaluelen = args->valuelen;
}
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index),
xfs_attr_leaf_entsize(leaf, args->index)));
/*
* Update the control info for this leaf node
*/
if (be16_to_cpu(entry->nameidx) < ichdr->firstused)
ichdr->firstused = be16_to_cpu(entry->nameidx);
ASSERT(ichdr->firstused >= ichdr->count * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf));
tmp = (ichdr->count - 1) * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf);
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
if (ichdr->freemap[i].base == tmp) {
ichdr->freemap[i].base += sizeof(xfs_attr_leaf_entry_t);
ichdr->freemap[i].size -= sizeof(xfs_attr_leaf_entry_t);
}
}
ichdr->usedbytes += xfs_attr_leaf_entsize(leaf, args->index);
return 0;
}
/*
* Garbage collect a leaf attribute list block by copying it to a new buffer.
*/
STATIC void
xfs_attr3_leaf_compact(
struct xfs_da_args *args,
struct xfs_attr3_icleaf_hdr *ichdr_dst,
struct xfs_buf *bp)
{
struct xfs_attr_leafblock *leaf_src;
struct xfs_attr_leafblock *leaf_dst;
struct xfs_attr3_icleaf_hdr ichdr_src;
struct xfs_trans *trans = args->trans;
struct xfs_mount *mp = trans->t_mountp;
char *tmpbuffer;
trace_xfs_attr_leaf_compact(args);
tmpbuffer = kmem_alloc(XFS_LBSIZE(mp), KM_SLEEP);
memcpy(tmpbuffer, bp->b_addr, XFS_LBSIZE(mp));
memset(bp->b_addr, 0, XFS_LBSIZE(mp));
leaf_src = (xfs_attr_leafblock_t *)tmpbuffer;
leaf_dst = bp->b_addr;
/*
* Copy the on-disk header back into the destination buffer to ensure
* all the information in the header that is not part of the incore
* header structure is preserved.
*/
memcpy(bp->b_addr, tmpbuffer, xfs_attr3_leaf_hdr_size(leaf_src));
/* Initialise the incore headers */
ichdr_src = *ichdr_dst; /* struct copy */
ichdr_dst->firstused = XFS_LBSIZE(mp);
ichdr_dst->usedbytes = 0;
ichdr_dst->count = 0;
ichdr_dst->holes = 0;
ichdr_dst->freemap[0].base = xfs_attr3_leaf_hdr_size(leaf_src);
ichdr_dst->freemap[0].size = ichdr_dst->firstused -
ichdr_dst->freemap[0].base;
/* write the header back to initialise the underlying buffer */
xfs_attr3_leaf_hdr_to_disk(leaf_dst, ichdr_dst);
/*
* Copy all entry's in the same (sorted) order,
* but allocate name/value pairs packed and in sequence.
*/
xfs_attr3_leaf_moveents(leaf_src, &ichdr_src, 0, leaf_dst, ichdr_dst, 0,
ichdr_src.count, mp);
/*
* this logs the entire buffer, but the caller must write the header
* back to the buffer when it is finished modifying it.
*/
xfs_trans_log_buf(trans, bp, 0, XFS_LBSIZE(mp) - 1);
kmem_free(tmpbuffer);
}
/*
* Compare two leaf blocks "order".
* Return 0 unless leaf2 should go before leaf1.
*/
static int
xfs_attr3_leaf_order(
struct xfs_buf *leaf1_bp,
struct xfs_attr3_icleaf_hdr *leaf1hdr,
struct xfs_buf *leaf2_bp,
struct xfs_attr3_icleaf_hdr *leaf2hdr)
{
struct xfs_attr_leaf_entry *entries1;
struct xfs_attr_leaf_entry *entries2;
entries1 = xfs_attr3_leaf_entryp(leaf1_bp->b_addr);
entries2 = xfs_attr3_leaf_entryp(leaf2_bp->b_addr);
if (leaf1hdr->count > 0 && leaf2hdr->count > 0 &&
((be32_to_cpu(entries2[0].hashval) <
be32_to_cpu(entries1[0].hashval)) ||
(be32_to_cpu(entries2[leaf2hdr->count - 1].hashval) <
be32_to_cpu(entries1[leaf1hdr->count - 1].hashval)))) {
return 1;
}
return 0;
}
int
xfs_attr_leaf_order(
struct xfs_buf *leaf1_bp,
struct xfs_buf *leaf2_bp)
{
struct xfs_attr3_icleaf_hdr ichdr1;
struct xfs_attr3_icleaf_hdr ichdr2;
xfs_attr3_leaf_hdr_from_disk(&ichdr1, leaf1_bp->b_addr);
xfs_attr3_leaf_hdr_from_disk(&ichdr2, leaf2_bp->b_addr);
return xfs_attr3_leaf_order(leaf1_bp, &ichdr1, leaf2_bp, &ichdr2);
}
/*
* Redistribute the attribute list entries between two leaf nodes,
* taking into account the size of the new entry.
*
* NOTE: if new block is empty, then it will get the upper half of the
* old block. At present, all (one) callers pass in an empty second block.
*
* This code adjusts the args->index/blkno and args->index2/blkno2 fields
* to match what it is doing in splitting the attribute leaf block. Those
* values are used in "atomic rename" operations on attributes. Note that
* the "new" and "old" values can end up in different blocks.
*/
STATIC void
xfs_attr3_leaf_rebalance(
struct xfs_da_state *state,
struct xfs_da_state_blk *blk1,
struct xfs_da_state_blk *blk2)
{
struct xfs_da_args *args;
struct xfs_attr_leafblock *leaf1;
struct xfs_attr_leafblock *leaf2;
struct xfs_attr3_icleaf_hdr ichdr1;
struct xfs_attr3_icleaf_hdr ichdr2;
struct xfs_attr_leaf_entry *entries1;
struct xfs_attr_leaf_entry *entries2;
int count;
int totallen;
int max;
int space;
int swap;
/*
* Set up environment.
*/
ASSERT(blk1->magic == XFS_ATTR_LEAF_MAGIC);
ASSERT(blk2->magic == XFS_ATTR_LEAF_MAGIC);
leaf1 = blk1->bp->b_addr;
leaf2 = blk2->bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr1, leaf1);
xfs_attr3_leaf_hdr_from_disk(&ichdr2, leaf2);
ASSERT(ichdr2.count == 0);
args = state->args;
trace_xfs_attr_leaf_rebalance(args);
/*
* Check ordering of blocks, reverse if it makes things simpler.
*
* NOTE: Given that all (current) callers pass in an empty
* second block, this code should never set "swap".
*/
swap = 0;
if (xfs_attr3_leaf_order(blk1->bp, &ichdr1, blk2->bp, &ichdr2)) {
struct xfs_da_state_blk *tmp_blk;
struct xfs_attr3_icleaf_hdr tmp_ichdr;
tmp_blk = blk1;
blk1 = blk2;
blk2 = tmp_blk;
/* struct copies to swap them rather than reconverting */
tmp_ichdr = ichdr1;
ichdr1 = ichdr2;
ichdr2 = tmp_ichdr;
leaf1 = blk1->bp->b_addr;
leaf2 = blk2->bp->b_addr;
swap = 1;
}
/*
* Examine entries until we reduce the absolute difference in
* byte usage between the two blocks to a minimum. Then get
* the direction to copy and the number of elements to move.
*
* "inleaf" is true if the new entry should be inserted into blk1.
* If "swap" is also true, then reverse the sense of "inleaf".
*/
state->inleaf = xfs_attr3_leaf_figure_balance(state, blk1, &ichdr1,
blk2, &ichdr2,
&count, &totallen);
if (swap)
state->inleaf = !state->inleaf;
/*
* Move any entries required from leaf to leaf:
*/
if (count < ichdr1.count) {
/*
* Figure the total bytes to be added to the destination leaf.
*/
/* number entries being moved */
count = ichdr1.count - count;
space = ichdr1.usedbytes - totallen;
space += count * sizeof(xfs_attr_leaf_entry_t);
/*
* leaf2 is the destination, compact it if it looks tight.
*/
max = ichdr2.firstused - xfs_attr3_leaf_hdr_size(leaf1);
max -= ichdr2.count * sizeof(xfs_attr_leaf_entry_t);
if (space > max)
xfs_attr3_leaf_compact(args, &ichdr2, blk2->bp);
/*
* Move high entries from leaf1 to low end of leaf2.
*/
xfs_attr3_leaf_moveents(leaf1, &ichdr1, ichdr1.count - count,
leaf2, &ichdr2, 0, count, state->mp);
} else if (count > ichdr1.count) {
/*
* I assert that since all callers pass in an empty
* second buffer, this code should never execute.
*/
ASSERT(0);
/*
* Figure the total bytes to be added to the destination leaf.
*/
/* number entries being moved */
count -= ichdr1.count;
space = totallen - ichdr1.usedbytes;
space += count * sizeof(xfs_attr_leaf_entry_t);
/*
* leaf1 is the destination, compact it if it looks tight.
*/
max = ichdr1.firstused - xfs_attr3_leaf_hdr_size(leaf1);
max -= ichdr1.count * sizeof(xfs_attr_leaf_entry_t);
if (space > max)
xfs_attr3_leaf_compact(args, &ichdr1, blk1->bp);
/*
* Move low entries from leaf2 to high end of leaf1.
*/
xfs_attr3_leaf_moveents(leaf2, &ichdr2, 0, leaf1, &ichdr1,
ichdr1.count, count, state->mp);
}
xfs_attr3_leaf_hdr_to_disk(leaf1, &ichdr1);
xfs_attr3_leaf_hdr_to_disk(leaf2, &ichdr2);
xfs_trans_log_buf(args->trans, blk1->bp, 0, state->blocksize-1);
xfs_trans_log_buf(args->trans, blk2->bp, 0, state->blocksize-1);
/*
* Copy out last hashval in each block for B-tree code.
*/
entries1 = xfs_attr3_leaf_entryp(leaf1);
entries2 = xfs_attr3_leaf_entryp(leaf2);
blk1->hashval = be32_to_cpu(entries1[ichdr1.count - 1].hashval);
blk2->hashval = be32_to_cpu(entries2[ichdr2.count - 1].hashval);
/*
* Adjust the expected index for insertion.
* NOTE: this code depends on the (current) situation that the
* second block was originally empty.
*
* If the insertion point moved to the 2nd block, we must adjust
* the index. We must also track the entry just following the
* new entry for use in an "atomic rename" operation, that entry
* is always the "old" entry and the "new" entry is what we are
* inserting. The index/blkno fields refer to the "old" entry,
* while the index2/blkno2 fields refer to the "new" entry.
*/
if (blk1->index > ichdr1.count) {
ASSERT(state->inleaf == 0);
blk2->index = blk1->index - ichdr1.count;
args->index = args->index2 = blk2->index;
args->blkno = args->blkno2 = blk2->blkno;
} else if (blk1->index == ichdr1.count) {
if (state->inleaf) {
args->index = blk1->index;
args->blkno = blk1->blkno;
args->index2 = 0;
args->blkno2 = blk2->blkno;
} else {
/*
* On a double leaf split, the original attr location
* is already stored in blkno2/index2, so don't
* overwrite it overwise we corrupt the tree.
*/
blk2->index = blk1->index - ichdr1.count;
args->index = blk2->index;
args->blkno = blk2->blkno;
if (!state->extravalid) {
/*
* set the new attr location to match the old
* one and let the higher level split code
* decide where in the leaf to place it.
*/
args->index2 = blk2->index;
args->blkno2 = blk2->blkno;
}
}
} else {
ASSERT(state->inleaf == 1);
args->index = args->index2 = blk1->index;
args->blkno = args->blkno2 = blk1->blkno;
}
}
/*
* Examine entries until we reduce the absolute difference in
* byte usage between the two blocks to a minimum.
* GROT: Is this really necessary? With other than a 512 byte blocksize,
* GROT: there will always be enough room in either block for a new entry.
* GROT: Do a double-split for this case?
*/
STATIC int
xfs_attr3_leaf_figure_balance(
struct xfs_da_state *state,
struct xfs_da_state_blk *blk1,
struct xfs_attr3_icleaf_hdr *ichdr1,
struct xfs_da_state_blk *blk2,
struct xfs_attr3_icleaf_hdr *ichdr2,
int *countarg,
int *usedbytesarg)
{
struct xfs_attr_leafblock *leaf1 = blk1->bp->b_addr;
struct xfs_attr_leafblock *leaf2 = blk2->bp->b_addr;
struct xfs_attr_leaf_entry *entry;
int count;
int max;
int index;
int totallen = 0;
int half;
int lastdelta;
int foundit = 0;
int tmp;
/*
* Examine entries until we reduce the absolute difference in
* byte usage between the two blocks to a minimum.
*/
max = ichdr1->count + ichdr2->count;
half = (max + 1) * sizeof(*entry);
half += ichdr1->usedbytes + ichdr2->usedbytes +
xfs_attr_leaf_newentsize(state->args->namelen,
state->args->valuelen,
state->blocksize, NULL);
half /= 2;
lastdelta = state->blocksize;
entry = xfs_attr3_leaf_entryp(leaf1);
for (count = index = 0; count < max; entry++, index++, count++) {
#define XFS_ATTR_ABS(A) (((A) < 0) ? -(A) : (A))
/*
* The new entry is in the first block, account for it.
*/
if (count == blk1->index) {
tmp = totallen + sizeof(*entry) +
xfs_attr_leaf_newentsize(
state->args->namelen,
state->args->valuelen,
state->blocksize, NULL);
if (XFS_ATTR_ABS(half - tmp) > lastdelta)
break;
lastdelta = XFS_ATTR_ABS(half - tmp);
totallen = tmp;
foundit = 1;
}
/*
* Wrap around into the second block if necessary.
*/
if (count == ichdr1->count) {
leaf1 = leaf2;
entry = xfs_attr3_leaf_entryp(leaf1);
index = 0;
}
/*
* Figure out if next leaf entry would be too much.
*/
tmp = totallen + sizeof(*entry) + xfs_attr_leaf_entsize(leaf1,
index);
if (XFS_ATTR_ABS(half - tmp) > lastdelta)
break;
lastdelta = XFS_ATTR_ABS(half - tmp);
totallen = tmp;
#undef XFS_ATTR_ABS
}
/*
* Calculate the number of usedbytes that will end up in lower block.
* If new entry not in lower block, fix up the count.
*/
totallen -= count * sizeof(*entry);
if (foundit) {
totallen -= sizeof(*entry) +
xfs_attr_leaf_newentsize(
state->args->namelen,
state->args->valuelen,
state->blocksize, NULL);
}
*countarg = count;
*usedbytesarg = totallen;
return foundit;
}
/*========================================================================
* Routines used for shrinking the Btree.
*========================================================================*/
/*
* Check a leaf block and its neighbors to see if the block should be
* collapsed into one or the other neighbor. Always keep the block
* with the smaller block number.
* If the current block is over 50% full, don't try to join it, return 0.
* If the block is empty, fill in the state structure and return 2.
* If it can be collapsed, fill in the state structure and return 1.
* If nothing can be done, return 0.
*
* GROT: allow for INCOMPLETE entries in calculation.
*/
int
xfs_attr3_leaf_toosmall(
struct xfs_da_state *state,
int *action)
{
struct xfs_attr_leafblock *leaf;
struct xfs_da_state_blk *blk;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_buf *bp;
xfs_dablk_t blkno;
int bytes;
int forward;
int error;
int retval;
int i;
trace_xfs_attr_leaf_toosmall(state->args);
/*
* Check for the degenerate case of the block being over 50% full.
* If so, it's not worth even looking to see if we might be able
* to coalesce with a sibling.
*/
blk = &state->path.blk[ state->path.active-1 ];
leaf = blk->bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
bytes = xfs_attr3_leaf_hdr_size(leaf) +
ichdr.count * sizeof(xfs_attr_leaf_entry_t) +
ichdr.usedbytes;
if (bytes > (state->blocksize >> 1)) {
*action = 0; /* blk over 50%, don't try to join */
return(0);
}
/*
* Check for the degenerate case of the block being empty.
* If the block is empty, we'll simply delete it, no need to
* coalesce it with a sibling block. We choose (arbitrarily)
* to merge with the forward block unless it is NULL.
*/
if (ichdr.count == 0) {
/*
* Make altpath point to the block we want to keep and
* path point to the block we want to drop (this one).
*/
forward = (ichdr.forw != 0);
memcpy(&state->altpath, &state->path, sizeof(state->path));
error = xfs_da3_path_shift(state, &state->altpath, forward,
0, &retval);
if (error)
return(error);
if (retval) {
*action = 0;
} else {
*action = 2;
}
return 0;
}
/*
* Examine each sibling block to see if we can coalesce with
* at least 25% free space to spare. We need to figure out
* whether to merge with the forward or the backward block.
* We prefer coalescing with the lower numbered sibling so as
* to shrink an attribute list over time.
*/
/* start with smaller blk num */
forward = ichdr.forw < ichdr.back;
for (i = 0; i < 2; forward = !forward, i++) {
struct xfs_attr3_icleaf_hdr ichdr2;
if (forward)
blkno = ichdr.forw;
else
blkno = ichdr.back;
if (blkno == 0)
continue;
error = xfs_attr3_leaf_read(state->args->trans, state->args->dp,
blkno, -1, &bp);
if (error)
return(error);
xfs_attr3_leaf_hdr_from_disk(&ichdr2, bp->b_addr);
bytes = state->blocksize - (state->blocksize >> 2) -
ichdr.usedbytes - ichdr2.usedbytes -
((ichdr.count + ichdr2.count) *
sizeof(xfs_attr_leaf_entry_t)) -
xfs_attr3_leaf_hdr_size(leaf);
xfs_trans_brelse(state->args->trans, bp);
if (bytes >= 0)
break; /* fits with at least 25% to spare */
}
if (i >= 2) {
*action = 0;
return(0);
}
/*
* Make altpath point to the block we want to keep (the lower
* numbered block) and path point to the block we want to drop.
*/
memcpy(&state->altpath, &state->path, sizeof(state->path));
if (blkno < blk->blkno) {
error = xfs_da3_path_shift(state, &state->altpath, forward,
0, &retval);
} else {
error = xfs_da3_path_shift(state, &state->path, forward,
0, &retval);
}
if (error)
return(error);
if (retval) {
*action = 0;
} else {
*action = 1;
}
return(0);
}
/*
* Remove a name from the leaf attribute list structure.
*
* Return 1 if leaf is less than 37% full, 0 if >= 37% full.
* If two leaves are 37% full, when combined they will leave 25% free.
*/
int
xfs_attr3_leaf_remove(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_mount *mp = args->trans->t_mountp;
int before;
int after;
int smallest;
int entsize;
int tablesize;
int tmp;
int i;
trace_xfs_attr_leaf_remove(args);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
ASSERT(ichdr.count > 0 && ichdr.count < XFS_LBSIZE(mp) / 8);
ASSERT(args->index >= 0 && args->index < ichdr.count);
ASSERT(ichdr.firstused >= ichdr.count * sizeof(*entry) +
xfs_attr3_leaf_hdr_size(leaf));
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
ASSERT(be16_to_cpu(entry->nameidx) >= ichdr.firstused);
ASSERT(be16_to_cpu(entry->nameidx) < XFS_LBSIZE(mp));
/*
* Scan through free region table:
* check for adjacency of free'd entry with an existing one,
* find smallest free region in case we need to replace it,
* adjust any map that borders the entry table,
*/
tablesize = ichdr.count * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf);
tmp = ichdr.freemap[0].size;
before = after = -1;
smallest = XFS_ATTR_LEAF_MAPSIZE - 1;
entsize = xfs_attr_leaf_entsize(leaf, args->index);
for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
ASSERT(ichdr.freemap[i].base < XFS_LBSIZE(mp));
ASSERT(ichdr.freemap[i].size < XFS_LBSIZE(mp));
if (ichdr.freemap[i].base == tablesize) {
ichdr.freemap[i].base -= sizeof(xfs_attr_leaf_entry_t);
ichdr.freemap[i].size += sizeof(xfs_attr_leaf_entry_t);
}
if (ichdr.freemap[i].base + ichdr.freemap[i].size ==
be16_to_cpu(entry->nameidx)) {
before = i;
} else if (ichdr.freemap[i].base ==
(be16_to_cpu(entry->nameidx) + entsize)) {
after = i;
} else if (ichdr.freemap[i].size < tmp) {
tmp = ichdr.freemap[i].size;
smallest = i;
}
}
/*
* Coalesce adjacent freemap regions,
* or replace the smallest region.
*/
if ((before >= 0) || (after >= 0)) {
if ((before >= 0) && (after >= 0)) {
ichdr.freemap[before].size += entsize;
ichdr.freemap[before].size += ichdr.freemap[after].size;
ichdr.freemap[after].base = 0;
ichdr.freemap[after].size = 0;
} else if (before >= 0) {
ichdr.freemap[before].size += entsize;
} else {
ichdr.freemap[after].base = be16_to_cpu(entry->nameidx);
ichdr.freemap[after].size += entsize;
}
} else {
/*
* Replace smallest region (if it is smaller than free'd entry)
*/
if (ichdr.freemap[smallest].size < entsize) {
ichdr.freemap[smallest].base = be16_to_cpu(entry->nameidx);
ichdr.freemap[smallest].size = entsize;
}
}
/*
* Did we remove the first entry?
*/
if (be16_to_cpu(entry->nameidx) == ichdr.firstused)
smallest = 1;
else
smallest = 0;
/*
* Compress the remaining entries and zero out the removed stuff.
*/
memset(xfs_attr3_leaf_name(leaf, args->index), 0, entsize);
ichdr.usedbytes -= entsize;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index),
entsize));
tmp = (ichdr.count - args->index) * sizeof(xfs_attr_leaf_entry_t);
memmove(entry, entry + 1, tmp);
ichdr.count--;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(xfs_attr_leaf_entry_t)));
entry = &xfs_attr3_leaf_entryp(leaf)[ichdr.count];
memset(entry, 0, sizeof(xfs_attr_leaf_entry_t));
/*
* If we removed the first entry, re-find the first used byte
* in the name area. Note that if the entry was the "firstused",
* then we don't have a "hole" in our block resulting from
* removing the name.
*/
if (smallest) {
tmp = XFS_LBSIZE(mp);
entry = xfs_attr3_leaf_entryp(leaf);
for (i = ichdr.count - 1; i >= 0; entry++, i--) {
ASSERT(be16_to_cpu(entry->nameidx) >= ichdr.firstused);
ASSERT(be16_to_cpu(entry->nameidx) < XFS_LBSIZE(mp));
if (be16_to_cpu(entry->nameidx) < tmp)
tmp = be16_to_cpu(entry->nameidx);
}
ichdr.firstused = tmp;
if (!ichdr.firstused)
ichdr.firstused = tmp - XFS_ATTR_LEAF_NAME_ALIGN;
} else {
ichdr.holes = 1; /* mark as needing compaction */
}
xfs_attr3_leaf_hdr_to_disk(leaf, &ichdr);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, &leaf->hdr,
xfs_attr3_leaf_hdr_size(leaf)));
/*
* Check if leaf is less than 50% full, caller may want to
* "join" the leaf with a sibling if so.
*/
tmp = ichdr.usedbytes + xfs_attr3_leaf_hdr_size(leaf) +
ichdr.count * sizeof(xfs_attr_leaf_entry_t);
return tmp < mp->m_attr_magicpct; /* leaf is < 37% full */
}
/*
* Move all the attribute list entries from drop_leaf into save_leaf.
*/
void
xfs_attr3_leaf_unbalance(
struct xfs_da_state *state,
struct xfs_da_state_blk *drop_blk,
struct xfs_da_state_blk *save_blk)
{
struct xfs_attr_leafblock *drop_leaf = drop_blk->bp->b_addr;
struct xfs_attr_leafblock *save_leaf = save_blk->bp->b_addr;
struct xfs_attr3_icleaf_hdr drophdr;
struct xfs_attr3_icleaf_hdr savehdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_mount *mp = state->mp;
trace_xfs_attr_leaf_unbalance(state->args);
drop_leaf = drop_blk->bp->b_addr;
save_leaf = save_blk->bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&drophdr, drop_leaf);
xfs_attr3_leaf_hdr_from_disk(&savehdr, save_leaf);
entry = xfs_attr3_leaf_entryp(drop_leaf);
/*
* Save last hashval from dying block for later Btree fixup.
*/
drop_blk->hashval = be32_to_cpu(entry[drophdr.count - 1].hashval);
/*
* Check if we need a temp buffer, or can we do it in place.
* Note that we don't check "leaf" for holes because we will
* always be dropping it, toosmall() decided that for us already.
*/
if (savehdr.holes == 0) {
/*
* dest leaf has no holes, so we add there. May need
* to make some room in the entry array.
*/
if (xfs_attr3_leaf_order(save_blk->bp, &savehdr,
drop_blk->bp, &drophdr)) {
xfs_attr3_leaf_moveents(drop_leaf, &drophdr, 0,
save_leaf, &savehdr, 0,
drophdr.count, mp);
} else {
xfs_attr3_leaf_moveents(drop_leaf, &drophdr, 0,
save_leaf, &savehdr,
savehdr.count, drophdr.count, mp);
}
} else {
/*
* Destination has holes, so we make a temporary copy
* of the leaf and add them both to that.
*/
struct xfs_attr_leafblock *tmp_leaf;
struct xfs_attr3_icleaf_hdr tmphdr;
tmp_leaf = kmem_zalloc(state->blocksize, KM_SLEEP);
/*
* Copy the header into the temp leaf so that all the stuff
* not in the incore header is present and gets copied back in
* once we've moved all the entries.
*/
memcpy(tmp_leaf, save_leaf, xfs_attr3_leaf_hdr_size(save_leaf));
memset(&tmphdr, 0, sizeof(tmphdr));
tmphdr.magic = savehdr.magic;
tmphdr.forw = savehdr.forw;
tmphdr.back = savehdr.back;
tmphdr.firstused = state->blocksize;
/* write the header to the temp buffer to initialise it */
xfs_attr3_leaf_hdr_to_disk(tmp_leaf, &tmphdr);
if (xfs_attr3_leaf_order(save_blk->bp, &savehdr,
drop_blk->bp, &drophdr)) {
xfs_attr3_leaf_moveents(drop_leaf, &drophdr, 0,
tmp_leaf, &tmphdr, 0,
drophdr.count, mp);
xfs_attr3_leaf_moveents(save_leaf, &savehdr, 0,
tmp_leaf, &tmphdr, tmphdr.count,
savehdr.count, mp);
} else {
xfs_attr3_leaf_moveents(save_leaf, &savehdr, 0,
tmp_leaf, &tmphdr, 0,
savehdr.count, mp);
xfs_attr3_leaf_moveents(drop_leaf, &drophdr, 0,
tmp_leaf, &tmphdr, tmphdr.count,
drophdr.count, mp);
}
memcpy(save_leaf, tmp_leaf, state->blocksize);
savehdr = tmphdr; /* struct copy */
kmem_free(tmp_leaf);
}
xfs_attr3_leaf_hdr_to_disk(save_leaf, &savehdr);
xfs_trans_log_buf(state->args->trans, save_blk->bp, 0,
state->blocksize - 1);
/*
* Copy out last hashval in each block for B-tree code.
*/
entry = xfs_attr3_leaf_entryp(save_leaf);
save_blk->hashval = be32_to_cpu(entry[savehdr.count - 1].hashval);
}
/*========================================================================
* Routines used for finding things in the Btree.
*========================================================================*/
/*
* Look up a name in a leaf attribute list structure.
* This is the internal routine, it uses the caller's buffer.
*
* Note that duplicate keys are allowed, but only check within the
* current leaf node. The Btree code must check in adjacent leaf nodes.
*
* Return in args->index the index into the entry[] array of either
* the found entry, or where the entry should have been (insert before
* that entry).
*
* Don't change the args->value unless we find the attribute.
*/
int
xfs_attr3_leaf_lookup_int(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_entry *entries;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_attr_leaf_name_remote *name_rmt;
xfs_dahash_t hashval;
int probe;
int span;
trace_xfs_attr_leaf_lookup(args);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
entries = xfs_attr3_leaf_entryp(leaf);
ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8);
/*
* Binary search. (note: small blocks will skip this loop)
*/
hashval = args->hashval;
probe = span = ichdr.count / 2;
for (entry = &entries[probe]; span > 4; entry = &entries[probe]) {
span /= 2;
if (be32_to_cpu(entry->hashval) < hashval)
probe += span;
else if (be32_to_cpu(entry->hashval) > hashval)
probe -= span;
else
break;
}
ASSERT(probe >= 0 && (!ichdr.count || probe < ichdr.count));
ASSERT(span <= 4 || be32_to_cpu(entry->hashval) == hashval);
/*
* Since we may have duplicate hashval's, find the first matching
* hashval in the leaf.
*/
while (probe > 0 && be32_to_cpu(entry->hashval) >= hashval) {
entry--;
probe--;
}
while (probe < ichdr.count &&
be32_to_cpu(entry->hashval) < hashval) {
entry++;
probe++;
}
if (probe == ichdr.count || be32_to_cpu(entry->hashval) != hashval) {
args->index = probe;
return XFS_ERROR(ENOATTR);
}
/*
* Duplicate keys may be present, so search all of them for a match.
*/
for (; probe < ichdr.count && (be32_to_cpu(entry->hashval) == hashval);
entry++, probe++) {
/*
* GROT: Add code to remove incomplete entries.
*/
/*
* If we are looking for INCOMPLETE entries, show only those.
* If we are looking for complete entries, show only those.
*/
if ((args->flags & XFS_ATTR_INCOMPLETE) !=
(entry->flags & XFS_ATTR_INCOMPLETE)) {
continue;
}
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, probe);
if (name_loc->namelen != args->namelen)
continue;
if (memcmp(args->name, name_loc->nameval,
args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, entry->flags))
continue;
args->index = probe;
return XFS_ERROR(EEXIST);
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, probe);
if (name_rmt->namelen != args->namelen)
continue;
if (memcmp(args->name, name_rmt->name,
args->namelen) != 0)
continue;
if (!xfs_attr_namesp_match(args->flags, entry->flags))
continue;
args->index = probe;
args->rmtvaluelen = be32_to_cpu(name_rmt->valuelen);
args->rmtblkno = be32_to_cpu(name_rmt->valueblk);
args->rmtblkcnt = xfs_attr3_rmt_blocks(
args->dp->i_mount,
args->rmtvaluelen);
return XFS_ERROR(EEXIST);
}
}
args->index = probe;
return XFS_ERROR(ENOATTR);
}
/*
* Get the value associated with an attribute name from a leaf attribute
* list structure.
*/
int
xfs_attr3_leaf_getvalue(
struct xfs_buf *bp,
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_local *name_loc;
struct xfs_attr_leaf_name_remote *name_rmt;
int valuelen;
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8);
ASSERT(args->index < ichdr.count);
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
ASSERT(name_loc->namelen == args->namelen);
ASSERT(memcmp(args->name, name_loc->nameval, args->namelen) == 0);
valuelen = be16_to_cpu(name_loc->valuelen);
if (args->flags & ATTR_KERNOVAL) {
args->valuelen = valuelen;
return 0;
}
if (args->valuelen < valuelen) {
args->valuelen = valuelen;
return XFS_ERROR(ERANGE);
}
args->valuelen = valuelen;
memcpy(args->value, &name_loc->nameval[args->namelen], valuelen);
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
ASSERT(name_rmt->namelen == args->namelen);
ASSERT(memcmp(args->name, name_rmt->name, args->namelen) == 0);
args->rmtvaluelen = be32_to_cpu(name_rmt->valuelen);
args->rmtblkno = be32_to_cpu(name_rmt->valueblk);
args->rmtblkcnt = xfs_attr3_rmt_blocks(args->dp->i_mount,
args->rmtvaluelen);
if (args->flags & ATTR_KERNOVAL) {
args->valuelen = args->rmtvaluelen;
return 0;
}
if (args->valuelen < args->rmtvaluelen) {
args->valuelen = args->rmtvaluelen;
return XFS_ERROR(ERANGE);
}
args->valuelen = args->rmtvaluelen;
}
return 0;
}
/*========================================================================
* Utility routines.
*========================================================================*/
/*
* Move the indicated entries from one leaf to another.
* NOTE: this routine modifies both source and destination leaves.
*/
/*ARGSUSED*/
STATIC void
xfs_attr3_leaf_moveents(
struct xfs_attr_leafblock *leaf_s,
struct xfs_attr3_icleaf_hdr *ichdr_s,
int start_s,
struct xfs_attr_leafblock *leaf_d,
struct xfs_attr3_icleaf_hdr *ichdr_d,
int start_d,
int count,
struct xfs_mount *mp)
{
struct xfs_attr_leaf_entry *entry_s;
struct xfs_attr_leaf_entry *entry_d;
int desti;
int tmp;
int i;
/*
* Check for nothing to do.
*/
if (count == 0)
return;
/*
* Set up environment.
*/
ASSERT(ichdr_s->magic == XFS_ATTR_LEAF_MAGIC ||
ichdr_s->magic == XFS_ATTR3_LEAF_MAGIC);
ASSERT(ichdr_s->magic == ichdr_d->magic);
ASSERT(ichdr_s->count > 0 && ichdr_s->count < XFS_LBSIZE(mp) / 8);
ASSERT(ichdr_s->firstused >= (ichdr_s->count * sizeof(*entry_s))
+ xfs_attr3_leaf_hdr_size(leaf_s));
ASSERT(ichdr_d->count < XFS_LBSIZE(mp) / 8);
ASSERT(ichdr_d->firstused >= (ichdr_d->count * sizeof(*entry_d))
+ xfs_attr3_leaf_hdr_size(leaf_d));
ASSERT(start_s < ichdr_s->count);
ASSERT(start_d <= ichdr_d->count);
ASSERT(count <= ichdr_s->count);
/*
* Move the entries in the destination leaf up to make a hole?
*/
if (start_d < ichdr_d->count) {
tmp = ichdr_d->count - start_d;
tmp *= sizeof(xfs_attr_leaf_entry_t);
entry_s = &xfs_attr3_leaf_entryp(leaf_d)[start_d];
entry_d = &xfs_attr3_leaf_entryp(leaf_d)[start_d + count];
memmove(entry_d, entry_s, tmp);
}
/*
* Copy all entry's in the same (sorted) order,
* but allocate attribute info packed and in sequence.
*/
entry_s = &xfs_attr3_leaf_entryp(leaf_s)[start_s];
entry_d = &xfs_attr3_leaf_entryp(leaf_d)[start_d];
desti = start_d;
for (i = 0; i < count; entry_s++, entry_d++, desti++, i++) {
ASSERT(be16_to_cpu(entry_s->nameidx) >= ichdr_s->firstused);
tmp = xfs_attr_leaf_entsize(leaf_s, start_s + i);
#ifdef GROT
/*
* Code to drop INCOMPLETE entries. Difficult to use as we
* may also need to change the insertion index. Code turned
* off for 6.2, should be revisited later.
*/
if (entry_s->flags & XFS_ATTR_INCOMPLETE) { /* skip partials? */
memset(xfs_attr3_leaf_name(leaf_s, start_s + i), 0, tmp);
ichdr_s->usedbytes -= tmp;
ichdr_s->count -= 1;
entry_d--; /* to compensate for ++ in loop hdr */
desti--;
if ((start_s + i) < offset)
result++; /* insertion index adjustment */
} else {
#endif /* GROT */
ichdr_d->firstused -= tmp;
/* both on-disk, don't endian flip twice */
entry_d->hashval = entry_s->hashval;
entry_d->nameidx = cpu_to_be16(ichdr_d->firstused);
entry_d->flags = entry_s->flags;
ASSERT(be16_to_cpu(entry_d->nameidx) + tmp
<= XFS_LBSIZE(mp));
memmove(xfs_attr3_leaf_name(leaf_d, desti),
xfs_attr3_leaf_name(leaf_s, start_s + i), tmp);
ASSERT(be16_to_cpu(entry_s->nameidx) + tmp
<= XFS_LBSIZE(mp));
memset(xfs_attr3_leaf_name(leaf_s, start_s + i), 0, tmp);
ichdr_s->usedbytes -= tmp;
ichdr_d->usedbytes += tmp;
ichdr_s->count -= 1;
ichdr_d->count += 1;
tmp = ichdr_d->count * sizeof(xfs_attr_leaf_entry_t)
+ xfs_attr3_leaf_hdr_size(leaf_d);
ASSERT(ichdr_d->firstused >= tmp);
#ifdef GROT
}
#endif /* GROT */
}
/*
* Zero out the entries we just copied.
*/
if (start_s == ichdr_s->count) {
tmp = count * sizeof(xfs_attr_leaf_entry_t);
entry_s = &xfs_attr3_leaf_entryp(leaf_s)[start_s];
ASSERT(((char *)entry_s + tmp) <=
((char *)leaf_s + XFS_LBSIZE(mp)));
memset(entry_s, 0, tmp);
} else {
/*
* Move the remaining entries down to fill the hole,
* then zero the entries at the top.
*/
tmp = (ichdr_s->count - count) * sizeof(xfs_attr_leaf_entry_t);
entry_s = &xfs_attr3_leaf_entryp(leaf_s)[start_s + count];
entry_d = &xfs_attr3_leaf_entryp(leaf_s)[start_s];
memmove(entry_d, entry_s, tmp);
tmp = count * sizeof(xfs_attr_leaf_entry_t);
entry_s = &xfs_attr3_leaf_entryp(leaf_s)[ichdr_s->count];
ASSERT(((char *)entry_s + tmp) <=
((char *)leaf_s + XFS_LBSIZE(mp)));
memset(entry_s, 0, tmp);
}
/*
* Fill in the freemap information
*/
ichdr_d->freemap[0].base = xfs_attr3_leaf_hdr_size(leaf_d);
ichdr_d->freemap[0].base += ichdr_d->count * sizeof(xfs_attr_leaf_entry_t);
ichdr_d->freemap[0].size = ichdr_d->firstused - ichdr_d->freemap[0].base;
ichdr_d->freemap[1].base = 0;
ichdr_d->freemap[2].base = 0;
ichdr_d->freemap[1].size = 0;
ichdr_d->freemap[2].size = 0;
ichdr_s->holes = 1; /* leaf may not be compact */
}
/*
* Pick up the last hashvalue from a leaf block.
*/
xfs_dahash_t
xfs_attr_leaf_lasthash(
struct xfs_buf *bp,
int *count)
{
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entries;
xfs_attr3_leaf_hdr_from_disk(&ichdr, bp->b_addr);
entries = xfs_attr3_leaf_entryp(bp->b_addr);
if (count)
*count = ichdr.count;
if (!ichdr.count)
return 0;
return be32_to_cpu(entries[ichdr.count - 1].hashval);
}
/*
* Calculate the number of bytes used to store the indicated attribute
* (whether local or remote only calculate bytes in this block).
*/
STATIC int
xfs_attr_leaf_entsize(xfs_attr_leafblock_t *leaf, int index)
{
struct xfs_attr_leaf_entry *entries;
xfs_attr_leaf_name_local_t *name_loc;
xfs_attr_leaf_name_remote_t *name_rmt;
int size;
entries = xfs_attr3_leaf_entryp(leaf);
if (entries[index].flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, index);
size = xfs_attr_leaf_entsize_local(name_loc->namelen,
be16_to_cpu(name_loc->valuelen));
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, index);
size = xfs_attr_leaf_entsize_remote(name_rmt->namelen);
}
return size;
}
/*
* Calculate the number of bytes that would be required to store the new
* attribute (whether local or remote only calculate bytes in this block).
* This routine decides as a side effect whether the attribute will be
* a "local" or a "remote" attribute.
*/
int
xfs_attr_leaf_newentsize(int namelen, int valuelen, int blocksize, int *local)
{
int size;
size = xfs_attr_leaf_entsize_local(namelen, valuelen);
if (size < xfs_attr_leaf_entsize_local_max(blocksize)) {
if (local) {
*local = 1;
}
} else {
size = xfs_attr_leaf_entsize_remote(namelen);
if (local) {
*local = 0;
}
}
return size;
}
/*========================================================================
* Manage the INCOMPLETE flag in a leaf entry
*========================================================================*/
/*
* Clear the INCOMPLETE flag on an entry in a leaf block.
*/
int
xfs_attr3_leaf_clearflag(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_buf *bp;
int error;
#ifdef DEBUG
struct xfs_attr3_icleaf_hdr ichdr;
xfs_attr_leaf_name_local_t *name_loc;
int namelen;
char *name;
#endif /* DEBUG */
trace_xfs_attr_leaf_clearflag(args);
/*
* Set up the operation.
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return(error);
leaf = bp->b_addr;
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
ASSERT(entry->flags & XFS_ATTR_INCOMPLETE);
#ifdef DEBUG
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
ASSERT(args->index < ichdr.count);
ASSERT(args->index >= 0);
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
namelen = name_loc->namelen;
name = (char *)name_loc->nameval;
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
namelen = name_rmt->namelen;
name = (char *)name_rmt->name;
}
ASSERT(be32_to_cpu(entry->hashval) == args->hashval);
ASSERT(namelen == args->namelen);
ASSERT(memcmp(name, args->name, namelen) == 0);
#endif /* DEBUG */
entry->flags &= ~XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
if (args->rmtblkno) {
ASSERT((entry->flags & XFS_ATTR_LOCAL) == 0);
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
name_rmt->valueblk = cpu_to_be32(args->rmtblkno);
name_rmt->valuelen = cpu_to_be32(args->rmtvaluelen);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, name_rmt, sizeof(*name_rmt)));
}
/*
* Commit the flag value change and start the next trans in series.
*/
return xfs_trans_roll(&args->trans, args->dp);
}
/*
* Set the INCOMPLETE flag on an entry in a leaf block.
*/
int
xfs_attr3_leaf_setflag(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_buf *bp;
int error;
#ifdef DEBUG
struct xfs_attr3_icleaf_hdr ichdr;
#endif
trace_xfs_attr_leaf_setflag(args);
/*
* Set up the operation.
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return(error);
leaf = bp->b_addr;
#ifdef DEBUG
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
ASSERT(args->index < ichdr.count);
ASSERT(args->index >= 0);
#endif
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
ASSERT((entry->flags & XFS_ATTR_INCOMPLETE) == 0);
entry->flags |= XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
if ((entry->flags & XFS_ATTR_LOCAL) == 0) {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
name_rmt->valueblk = 0;
name_rmt->valuelen = 0;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, name_rmt, sizeof(*name_rmt)));
}
/*
* Commit the flag value change and start the next trans in series.
*/
return xfs_trans_roll(&args->trans, args->dp);
}
/*
* In a single transaction, clear the INCOMPLETE flag on the leaf entry
* given by args->blkno/index and set the INCOMPLETE flag on the leaf
* entry given by args->blkno2/index2.
*
* Note that they could be in different blocks, or in the same block.
*/
int
xfs_attr3_leaf_flipflags(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf1;
struct xfs_attr_leafblock *leaf2;
struct xfs_attr_leaf_entry *entry1;
struct xfs_attr_leaf_entry *entry2;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_buf *bp1;
struct xfs_buf *bp2;
int error;
#ifdef DEBUG
struct xfs_attr3_icleaf_hdr ichdr1;
struct xfs_attr3_icleaf_hdr ichdr2;
xfs_attr_leaf_name_local_t *name_loc;
int namelen1, namelen2;
char *name1, *name2;
#endif /* DEBUG */
trace_xfs_attr_leaf_flipflags(args);
/*
* Read the block containing the "old" attr
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp1);
if (error)
return error;
/*
* Read the block containing the "new" attr, if it is different
*/
if (args->blkno2 != args->blkno) {
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno2,
-1, &bp2);
if (error)
return error;
} else {
bp2 = bp1;
}
leaf1 = bp1->b_addr;
entry1 = &xfs_attr3_leaf_entryp(leaf1)[args->index];
leaf2 = bp2->b_addr;
entry2 = &xfs_attr3_leaf_entryp(leaf2)[args->index2];
#ifdef DEBUG
xfs_attr3_leaf_hdr_from_disk(&ichdr1, leaf1);
ASSERT(args->index < ichdr1.count);
ASSERT(args->index >= 0);
xfs_attr3_leaf_hdr_from_disk(&ichdr2, leaf2);
ASSERT(args->index2 < ichdr2.count);
ASSERT(args->index2 >= 0);
if (entry1->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf1, args->index);
namelen1 = name_loc->namelen;
name1 = (char *)name_loc->nameval;
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index);
namelen1 = name_rmt->namelen;
name1 = (char *)name_rmt->name;
}
if (entry2->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf2, args->index2);
namelen2 = name_loc->namelen;
name2 = (char *)name_loc->nameval;
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2);
namelen2 = name_rmt->namelen;
name2 = (char *)name_rmt->name;
}
ASSERT(be32_to_cpu(entry1->hashval) == be32_to_cpu(entry2->hashval));
ASSERT(namelen1 == namelen2);
ASSERT(memcmp(name1, name2, namelen1) == 0);
#endif /* DEBUG */
ASSERT(entry1->flags & XFS_ATTR_INCOMPLETE);
ASSERT((entry2->flags & XFS_ATTR_INCOMPLETE) == 0);
entry1->flags &= ~XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp1,
XFS_DA_LOGRANGE(leaf1, entry1, sizeof(*entry1)));
if (args->rmtblkno) {
ASSERT((entry1->flags & XFS_ATTR_LOCAL) == 0);
name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index);
name_rmt->valueblk = cpu_to_be32(args->rmtblkno);
name_rmt->valuelen = cpu_to_be32(args->rmtvaluelen);
xfs_trans_log_buf(args->trans, bp1,
XFS_DA_LOGRANGE(leaf1, name_rmt, sizeof(*name_rmt)));
}
entry2->flags |= XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp2,
XFS_DA_LOGRANGE(leaf2, entry2, sizeof(*entry2)));
if ((entry2->flags & XFS_ATTR_LOCAL) == 0) {
name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2);
name_rmt->valueblk = 0;
name_rmt->valuelen = 0;
xfs_trans_log_buf(args->trans, bp2,
XFS_DA_LOGRANGE(leaf2, name_rmt, sizeof(*name_rmt)));
}
/*
* Commit the flag value change and start the next trans in series.
*/
error = xfs_trans_roll(&args->trans, args->dp);
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-19/c/good_1453_1 |
crossvul-cpp_data_bad_1842_2 | /*
* linux/fs/ext4/xattr.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
*
* Fix by Harrison Xing <harrison@mountainviewdata.com>.
* Ext4 code with a lot of help from Eric Jarman <ejarman@acm.org>.
* Extended attributes for symlinks and special files added per
* suggestion of Luka Renko <luka.renko@hermes.si>.
* xattr consolidation Copyright (c) 2004 James Morris <jmorris@redhat.com>,
* Red Hat Inc.
* ea-in-inode support by Alex Tomas <alex@clusterfs.com> aka bzzz
* and Andreas Gruenbacher <agruen@suse.de>.
*/
/*
* Extended attributes are stored directly in inodes (on file systems with
* inodes bigger than 128 bytes) and on additional disk blocks. The i_file_acl
* field contains the block number if an inode uses an additional block. All
* attributes must fit in the inode and one additional block. Blocks that
* contain the identical set of attributes may be shared among several inodes.
* Identical blocks are detected by keeping a cache of blocks that have
* recently been accessed.
*
* The attributes in inodes and on blocks have a different header; the entries
* are stored in the same format:
*
* +------------------+
* | header |
* | entry 1 | |
* | entry 2 | | growing downwards
* | entry 3 | v
* | four null bytes |
* | . . . |
* | value 1 | ^
* | value 3 | | growing upwards
* | value 2 | |
* +------------------+
*
* The header is followed by multiple entry descriptors. In disk blocks, the
* entry descriptors are kept sorted. In inodes, they are unsorted. The
* attribute values are aligned to the end of the block in no specific order.
*
* Locking strategy
* ----------------
* EXT4_I(inode)->i_file_acl is protected by EXT4_I(inode)->xattr_sem.
* EA blocks are only changed if they are exclusive to an inode, so
* holding xattr_sem also means that nothing but the EA block's reference
* count can change. Multiple writers to the same block are synchronized
* by the buffer lock.
*/
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/mbcache.h>
#include <linux/quotaops.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
#include "acl.h"
#ifdef EXT4_XATTR_DEBUG
# define ea_idebug(inode, f...) do { \
printk(KERN_DEBUG "inode %s:%lu: ", \
inode->i_sb->s_id, inode->i_ino); \
printk(f); \
printk("\n"); \
} while (0)
# define ea_bdebug(bh, f...) do { \
printk(KERN_DEBUG "block %pg:%lu: ", \
bh->b_bdev, (unsigned long) bh->b_blocknr); \
printk(f); \
printk("\n"); \
} while (0)
#else
# define ea_idebug(inode, fmt, ...) no_printk(fmt, ##__VA_ARGS__)
# define ea_bdebug(bh, fmt, ...) no_printk(fmt, ##__VA_ARGS__)
#endif
static void ext4_xattr_cache_insert(struct mb_cache *, struct buffer_head *);
static struct buffer_head *ext4_xattr_cache_find(struct inode *,
struct ext4_xattr_header *,
struct mb_cache_entry **);
static void ext4_xattr_rehash(struct ext4_xattr_header *,
struct ext4_xattr_entry *);
static int ext4_xattr_list(struct dentry *dentry, char *buffer,
size_t buffer_size);
static const struct xattr_handler *ext4_xattr_handler_map[] = {
[EXT4_XATTR_INDEX_USER] = &ext4_xattr_user_handler,
#ifdef CONFIG_EXT4_FS_POSIX_ACL
[EXT4_XATTR_INDEX_POSIX_ACL_ACCESS] = &posix_acl_access_xattr_handler,
[EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT] = &posix_acl_default_xattr_handler,
#endif
[EXT4_XATTR_INDEX_TRUSTED] = &ext4_xattr_trusted_handler,
#ifdef CONFIG_EXT4_FS_SECURITY
[EXT4_XATTR_INDEX_SECURITY] = &ext4_xattr_security_handler,
#endif
};
const struct xattr_handler *ext4_xattr_handlers[] = {
&ext4_xattr_user_handler,
&ext4_xattr_trusted_handler,
#ifdef CONFIG_EXT4_FS_POSIX_ACL
&posix_acl_access_xattr_handler,
&posix_acl_default_xattr_handler,
#endif
#ifdef CONFIG_EXT4_FS_SECURITY
&ext4_xattr_security_handler,
#endif
NULL
};
#define EXT4_GET_MB_CACHE(inode) (((struct ext4_sb_info *) \
inode->i_sb->s_fs_info)->s_mb_cache)
static __le32 ext4_xattr_block_csum(struct inode *inode,
sector_t block_nr,
struct ext4_xattr_header *hdr)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
__u32 csum;
__le32 save_csum;
__le64 dsk_block_nr = cpu_to_le64(block_nr);
save_csum = hdr->h_checksum;
hdr->h_checksum = 0;
csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&dsk_block_nr,
sizeof(dsk_block_nr));
csum = ext4_chksum(sbi, csum, (__u8 *)hdr,
EXT4_BLOCK_SIZE(inode->i_sb));
hdr->h_checksum = save_csum;
return cpu_to_le32(csum);
}
static int ext4_xattr_block_csum_verify(struct inode *inode,
sector_t block_nr,
struct ext4_xattr_header *hdr)
{
if (ext4_has_metadata_csum(inode->i_sb) &&
(hdr->h_checksum != ext4_xattr_block_csum(inode, block_nr, hdr)))
return 0;
return 1;
}
static void ext4_xattr_block_csum_set(struct inode *inode,
sector_t block_nr,
struct ext4_xattr_header *hdr)
{
if (!ext4_has_metadata_csum(inode->i_sb))
return;
hdr->h_checksum = ext4_xattr_block_csum(inode, block_nr, hdr);
}
static inline int ext4_handle_dirty_xattr_block(handle_t *handle,
struct inode *inode,
struct buffer_head *bh)
{
ext4_xattr_block_csum_set(inode, bh->b_blocknr, BHDR(bh));
return ext4_handle_dirty_metadata(handle, inode, bh);
}
static inline const struct xattr_handler *
ext4_xattr_handler(int name_index)
{
const struct xattr_handler *handler = NULL;
if (name_index > 0 && name_index < ARRAY_SIZE(ext4_xattr_handler_map))
handler = ext4_xattr_handler_map[name_index];
return handler;
}
/*
* Inode operation listxattr()
*
* d_inode(dentry)->i_mutex: don't care
*/
ssize_t
ext4_listxattr(struct dentry *dentry, char *buffer, size_t size)
{
return ext4_xattr_list(dentry, buffer, size);
}
static int
ext4_xattr_check_names(struct ext4_xattr_entry *entry, void *end,
void *value_start)
{
struct ext4_xattr_entry *e = entry;
while (!IS_LAST_ENTRY(e)) {
struct ext4_xattr_entry *next = EXT4_XATTR_NEXT(e);
if ((void *)next >= end)
return -EFSCORRUPTED;
e = next;
}
while (!IS_LAST_ENTRY(entry)) {
if (entry->e_value_size != 0 &&
(value_start + le16_to_cpu(entry->e_value_offs) <
(void *)e + sizeof(__u32) ||
value_start + le16_to_cpu(entry->e_value_offs) +
le32_to_cpu(entry->e_value_size) > end))
return -EFSCORRUPTED;
entry = EXT4_XATTR_NEXT(entry);
}
return 0;
}
static inline int
ext4_xattr_check_block(struct inode *inode, struct buffer_head *bh)
{
int error;
if (buffer_verified(bh))
return 0;
if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
BHDR(bh)->h_blocks != cpu_to_le32(1))
return -EFSCORRUPTED;
if (!ext4_xattr_block_csum_verify(inode, bh->b_blocknr, BHDR(bh)))
return -EFSBADCRC;
error = ext4_xattr_check_names(BFIRST(bh), bh->b_data + bh->b_size,
bh->b_data);
if (!error)
set_buffer_verified(bh);
return error;
}
static inline int
ext4_xattr_check_entry(struct ext4_xattr_entry *entry, size_t size)
{
size_t value_size = le32_to_cpu(entry->e_value_size);
if (entry->e_value_block != 0 || value_size > size ||
le16_to_cpu(entry->e_value_offs) + value_size > size)
return -EFSCORRUPTED;
return 0;
}
static int
ext4_xattr_find_entry(struct ext4_xattr_entry **pentry, int name_index,
const char *name, size_t size, int sorted)
{
struct ext4_xattr_entry *entry;
size_t name_len;
int cmp = 1;
if (name == NULL)
return -EINVAL;
name_len = strlen(name);
entry = *pentry;
for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
cmp = name_index - entry->e_name_index;
if (!cmp)
cmp = name_len - entry->e_name_len;
if (!cmp)
cmp = memcmp(name, entry->e_name, name_len);
if (cmp <= 0 && (sorted || cmp == 0))
break;
}
*pentry = entry;
if (!cmp && ext4_xattr_check_entry(entry, size))
return -EFSCORRUPTED;
return cmp ? -ENODATA : 0;
}
static int
ext4_xattr_block_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct buffer_head *bh = NULL;
struct ext4_xattr_entry *entry;
size_t size;
int error;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld",
name_index, name, buffer, (long)buffer_size);
error = -ENODATA;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (ext4_xattr_check_block(inode, bh)) {
bad_block:
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EFSCORRUPTED;
goto cleanup;
}
ext4_xattr_cache_insert(ext4_mb_cache, bh);
entry = BFIRST(bh);
error = ext4_xattr_find_entry(&entry, name_index, name, bh->b_size, 1);
if (error == -EFSCORRUPTED)
goto bad_block;
if (error)
goto cleanup;
size = le32_to_cpu(entry->e_value_size);
if (buffer) {
error = -ERANGE;
if (size > buffer_size)
goto cleanup;
memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs),
size);
}
error = size;
cleanup:
brelse(bh);
return error;
}
int
ext4_xattr_ibody_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_entry *entry;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
size_t size;
void *end;
int error;
if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR))
return -ENODATA;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext4_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
entry = IFIRST(header);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
error = ext4_xattr_check_names(entry, end, entry);
if (error)
goto cleanup;
error = ext4_xattr_find_entry(&entry, name_index, name,
end - (void *)entry, 0);
if (error)
goto cleanup;
size = le32_to_cpu(entry->e_value_size);
if (buffer) {
error = -ERANGE;
if (size > buffer_size)
goto cleanup;
memcpy(buffer, (void *)IFIRST(header) +
le16_to_cpu(entry->e_value_offs), size);
}
error = size;
cleanup:
brelse(iloc.bh);
return error;
}
/*
* ext4_xattr_get()
*
* Copy an extended attribute into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
int
ext4_xattr_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
int error;
if (strlen(name) > 255)
return -ERANGE;
down_read(&EXT4_I(inode)->xattr_sem);
error = ext4_xattr_ibody_get(inode, name_index, name, buffer,
buffer_size);
if (error == -ENODATA)
error = ext4_xattr_block_get(inode, name_index, name, buffer,
buffer_size);
up_read(&EXT4_I(inode)->xattr_sem);
return error;
}
static int
ext4_xattr_list_entries(struct dentry *dentry, struct ext4_xattr_entry *entry,
char *buffer, size_t buffer_size)
{
size_t rest = buffer_size;
for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
const struct xattr_handler *handler =
ext4_xattr_handler(entry->e_name_index);
if (handler && (!handler->list || handler->list(dentry))) {
const char *prefix = handler->prefix ?: handler->name;
size_t prefix_len = strlen(prefix);
size_t size = prefix_len + entry->e_name_len + 1;
if (buffer) {
if (size > rest)
return -ERANGE;
memcpy(buffer, prefix, prefix_len);
buffer += prefix_len;
memcpy(buffer, entry->e_name, entry->e_name_len);
buffer += entry->e_name_len;
*buffer++ = 0;
}
rest -= size;
}
}
return buffer_size - rest; /* total size */
}
static int
ext4_xattr_block_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = d_inode(dentry);
struct buffer_head *bh = NULL;
int error;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
ea_idebug(inode, "buffer=%p, buffer_size=%ld",
buffer, (long)buffer_size);
error = 0;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (ext4_xattr_check_block(inode, bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EFSCORRUPTED;
goto cleanup;
}
ext4_xattr_cache_insert(ext4_mb_cache, bh);
error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer, buffer_size);
cleanup:
brelse(bh);
return error;
}
static int
ext4_xattr_ibody_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = d_inode(dentry);
struct ext4_xattr_ibody_header *header;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
void *end;
int error;
if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR))
return 0;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext4_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
error = ext4_xattr_check_names(IFIRST(header), end, IFIRST(header));
if (error)
goto cleanup;
error = ext4_xattr_list_entries(dentry, IFIRST(header),
buffer, buffer_size);
cleanup:
brelse(iloc.bh);
return error;
}
/*
* ext4_xattr_list()
*
* Copy a list of attribute names into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
static int
ext4_xattr_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
int ret, ret2;
down_read(&EXT4_I(d_inode(dentry))->xattr_sem);
ret = ret2 = ext4_xattr_ibody_list(dentry, buffer, buffer_size);
if (ret < 0)
goto errout;
if (buffer) {
buffer += ret;
buffer_size -= ret;
}
ret = ext4_xattr_block_list(dentry, buffer, buffer_size);
if (ret < 0)
goto errout;
ret += ret2;
errout:
up_read(&EXT4_I(d_inode(dentry))->xattr_sem);
return ret;
}
/*
* If the EXT4_FEATURE_COMPAT_EXT_ATTR feature of this file system is
* not set, set it.
*/
static void ext4_xattr_update_super_block(handle_t *handle,
struct super_block *sb)
{
if (ext4_has_feature_xattr(sb))
return;
BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access");
if (ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh) == 0) {
ext4_set_feature_xattr(sb);
ext4_handle_dirty_super(handle, sb);
}
}
/*
* Release the xattr block BH: If the reference count is > 1, decrement it;
* otherwise free the block.
*/
static void
ext4_xattr_release_block(handle_t *handle, struct inode *inode,
struct buffer_head *bh)
{
struct mb_cache_entry *ce = NULL;
int error = 0;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
ce = mb_cache_entry_get(ext4_mb_cache, bh->b_bdev, bh->b_blocknr);
BUFFER_TRACE(bh, "get_write_access");
error = ext4_journal_get_write_access(handle, bh);
if (error)
goto out;
lock_buffer(bh);
if (BHDR(bh)->h_refcount == cpu_to_le32(1)) {
ea_bdebug(bh, "refcount now=0; freeing");
if (ce)
mb_cache_entry_free(ce);
get_bh(bh);
unlock_buffer(bh);
ext4_free_blocks(handle, inode, bh, 0, 1,
EXT4_FREE_BLOCKS_METADATA |
EXT4_FREE_BLOCKS_FORGET);
} else {
le32_add_cpu(&BHDR(bh)->h_refcount, -1);
if (ce)
mb_cache_entry_release(ce);
/*
* Beware of this ugliness: Releasing of xattr block references
* from different inodes can race and so we have to protect
* from a race where someone else frees the block (and releases
* its journal_head) before we are done dirtying the buffer. In
* nojournal mode this race is harmless and we actually cannot
* call ext4_handle_dirty_xattr_block() with locked buffer as
* that function can call sync_dirty_buffer() so for that case
* we handle the dirtying after unlocking the buffer.
*/
if (ext4_handle_valid(handle))
error = ext4_handle_dirty_xattr_block(handle, inode,
bh);
unlock_buffer(bh);
if (!ext4_handle_valid(handle))
error = ext4_handle_dirty_xattr_block(handle, inode,
bh);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
dquot_free_block(inode, EXT4_C2B(EXT4_SB(inode->i_sb), 1));
ea_bdebug(bh, "refcount now=%d; releasing",
le32_to_cpu(BHDR(bh)->h_refcount));
}
out:
ext4_std_error(inode->i_sb, error);
return;
}
/*
* Find the available free space for EAs. This also returns the total number of
* bytes used by EA entries.
*/
static size_t ext4_xattr_free_space(struct ext4_xattr_entry *last,
size_t *min_offs, void *base, int *total)
{
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < *min_offs)
*min_offs = offs;
}
if (total)
*total += EXT4_XATTR_LEN(last->e_name_len);
}
return (*min_offs - ((void *)last - base) - sizeof(__u32));
}
static int
ext4_xattr_set_entry(struct ext4_xattr_info *i, struct ext4_xattr_search *s)
{
struct ext4_xattr_entry *last;
size_t free, min_offs = s->end - s->base, name_len = strlen(i->name);
/* Compute min_offs and last. */
last = s->first;
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < min_offs)
min_offs = offs;
}
}
free = min_offs - ((void *)last - s->base) - sizeof(__u32);
if (!s->not_found) {
if (!s->here->e_value_block && s->here->e_value_size) {
size_t size = le32_to_cpu(s->here->e_value_size);
free += EXT4_XATTR_SIZE(size);
}
free += EXT4_XATTR_LEN(name_len);
}
if (i->value) {
if (free < EXT4_XATTR_LEN(name_len) +
EXT4_XATTR_SIZE(i->value_len))
return -ENOSPC;
}
if (i->value && s->not_found) {
/* Insert the new name. */
size_t size = EXT4_XATTR_LEN(name_len);
size_t rest = (void *)last - (void *)s->here + sizeof(__u32);
memmove((void *)s->here + size, s->here, rest);
memset(s->here, 0, size);
s->here->e_name_index = i->name_index;
s->here->e_name_len = name_len;
memcpy(s->here->e_name, i->name, name_len);
} else {
if (!s->here->e_value_block && s->here->e_value_size) {
void *first_val = s->base + min_offs;
size_t offs = le16_to_cpu(s->here->e_value_offs);
void *val = s->base + offs;
size_t size = EXT4_XATTR_SIZE(
le32_to_cpu(s->here->e_value_size));
if (i->value && size == EXT4_XATTR_SIZE(i->value_len)) {
/* The old and the new value have the same
size. Just replace. */
s->here->e_value_size =
cpu_to_le32(i->value_len);
if (i->value == EXT4_ZERO_XATTR_VALUE) {
memset(val, 0, size);
} else {
/* Clear pad bytes first. */
memset(val + size - EXT4_XATTR_PAD, 0,
EXT4_XATTR_PAD);
memcpy(val, i->value, i->value_len);
}
return 0;
}
/* Remove the old value. */
memmove(first_val + size, first_val, val - first_val);
memset(first_val, 0, size);
s->here->e_value_size = 0;
s->here->e_value_offs = 0;
min_offs += size;
/* Adjust all value offsets. */
last = s->first;
while (!IS_LAST_ENTRY(last)) {
size_t o = le16_to_cpu(last->e_value_offs);
if (!last->e_value_block &&
last->e_value_size && o < offs)
last->e_value_offs =
cpu_to_le16(o + size);
last = EXT4_XATTR_NEXT(last);
}
}
if (!i->value) {
/* Remove the old name. */
size_t size = EXT4_XATTR_LEN(name_len);
last = ENTRY((void *)last - size);
memmove(s->here, (void *)s->here + size,
(void *)last - (void *)s->here + sizeof(__u32));
memset(last, 0, size);
}
}
if (i->value) {
/* Insert the new value. */
s->here->e_value_size = cpu_to_le32(i->value_len);
if (i->value_len) {
size_t size = EXT4_XATTR_SIZE(i->value_len);
void *val = s->base + min_offs - size;
s->here->e_value_offs = cpu_to_le16(min_offs - size);
if (i->value == EXT4_ZERO_XATTR_VALUE) {
memset(val, 0, size);
} else {
/* Clear the pad bytes first. */
memset(val + size - EXT4_XATTR_PAD, 0,
EXT4_XATTR_PAD);
memcpy(val, i->value, i->value_len);
}
}
}
return 0;
}
struct ext4_xattr_block_find {
struct ext4_xattr_search s;
struct buffer_head *bh;
};
static int
ext4_xattr_block_find(struct inode *inode, struct ext4_xattr_info *i,
struct ext4_xattr_block_find *bs)
{
struct super_block *sb = inode->i_sb;
int error;
ea_idebug(inode, "name=%d.%s, value=%p, value_len=%ld",
i->name_index, i->name, i->value, (long)i->value_len);
if (EXT4_I(inode)->i_file_acl) {
/* The inode already has an extended attribute block. */
bs->bh = sb_bread(sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bs->bh)
goto cleanup;
ea_bdebug(bs->bh, "b_count=%d, refcount=%d",
atomic_read(&(bs->bh->b_count)),
le32_to_cpu(BHDR(bs->bh)->h_refcount));
if (ext4_xattr_check_block(inode, bs->bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EFSCORRUPTED;
goto cleanup;
}
/* Find the named attribute. */
bs->s.base = BHDR(bs->bh);
bs->s.first = BFIRST(bs->bh);
bs->s.end = bs->bh->b_data + bs->bh->b_size;
bs->s.here = bs->s.first;
error = ext4_xattr_find_entry(&bs->s.here, i->name_index,
i->name, bs->bh->b_size, 1);
if (error && error != -ENODATA)
goto cleanup;
bs->s.not_found = error;
}
error = 0;
cleanup:
return error;
}
static int
ext4_xattr_block_set(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct ext4_xattr_block_find *bs)
{
struct super_block *sb = inode->i_sb;
struct buffer_head *new_bh = NULL;
struct ext4_xattr_search *s = &bs->s;
struct mb_cache_entry *ce = NULL;
int error = 0;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
#define header(x) ((struct ext4_xattr_header *)(x))
if (i->value && i->value_len > sb->s_blocksize)
return -ENOSPC;
if (s->base) {
ce = mb_cache_entry_get(ext4_mb_cache, bs->bh->b_bdev,
bs->bh->b_blocknr);
BUFFER_TRACE(bs->bh, "get_write_access");
error = ext4_journal_get_write_access(handle, bs->bh);
if (error)
goto cleanup;
lock_buffer(bs->bh);
if (header(s->base)->h_refcount == cpu_to_le32(1)) {
if (ce) {
mb_cache_entry_free(ce);
ce = NULL;
}
ea_bdebug(bs->bh, "modifying in-place");
error = ext4_xattr_set_entry(i, s);
if (!error) {
if (!IS_LAST_ENTRY(s->first))
ext4_xattr_rehash(header(s->base),
s->here);
ext4_xattr_cache_insert(ext4_mb_cache,
bs->bh);
}
unlock_buffer(bs->bh);
if (error == -EFSCORRUPTED)
goto bad_block;
if (!error)
error = ext4_handle_dirty_xattr_block(handle,
inode,
bs->bh);
if (error)
goto cleanup;
goto inserted;
} else {
int offset = (char *)s->here - bs->bh->b_data;
unlock_buffer(bs->bh);
if (ce) {
mb_cache_entry_release(ce);
ce = NULL;
}
ea_bdebug(bs->bh, "cloning");
s->base = kmalloc(bs->bh->b_size, GFP_NOFS);
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
memcpy(s->base, BHDR(bs->bh), bs->bh->b_size);
s->first = ENTRY(header(s->base)+1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->here = ENTRY(s->base + offset);
s->end = s->base + bs->bh->b_size;
}
} else {
/* Allocate a buffer where we construct the new block. */
s->base = kzalloc(sb->s_blocksize, GFP_NOFS);
/* assert(header == s->base) */
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
header(s->base)->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
header(s->base)->h_blocks = cpu_to_le32(1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->first = ENTRY(header(s->base)+1);
s->here = ENTRY(header(s->base)+1);
s->end = s->base + sb->s_blocksize;
}
error = ext4_xattr_set_entry(i, s);
if (error == -EFSCORRUPTED)
goto bad_block;
if (error)
goto cleanup;
if (!IS_LAST_ENTRY(s->first))
ext4_xattr_rehash(header(s->base), s->here);
inserted:
if (!IS_LAST_ENTRY(s->first)) {
new_bh = ext4_xattr_cache_find(inode, header(s->base), &ce);
if (new_bh) {
/* We found an identical block in the cache. */
if (new_bh == bs->bh)
ea_bdebug(new_bh, "keeping");
else {
/* The old block is released after updating
the inode. */
error = dquot_alloc_block(inode,
EXT4_C2B(EXT4_SB(sb), 1));
if (error)
goto cleanup;
BUFFER_TRACE(new_bh, "get_write_access");
error = ext4_journal_get_write_access(handle,
new_bh);
if (error)
goto cleanup_dquot;
lock_buffer(new_bh);
le32_add_cpu(&BHDR(new_bh)->h_refcount, 1);
ea_bdebug(new_bh, "reusing; refcount now=%d",
le32_to_cpu(BHDR(new_bh)->h_refcount));
unlock_buffer(new_bh);
error = ext4_handle_dirty_xattr_block(handle,
inode,
new_bh);
if (error)
goto cleanup_dquot;
}
mb_cache_entry_release(ce);
ce = NULL;
} else if (bs->bh && s->base == bs->bh->b_data) {
/* We were modifying this block in-place. */
ea_bdebug(bs->bh, "keeping this block");
new_bh = bs->bh;
get_bh(new_bh);
} else {
/* We need to allocate a new block */
ext4_fsblk_t goal, block;
goal = ext4_group_first_block_no(sb,
EXT4_I(inode)->i_block_group);
/* non-extent files can't have physical blocks past 2^32 */
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
block = ext4_new_meta_blocks(handle, inode, goal, 0,
NULL, &error);
if (error)
goto cleanup;
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
BUG_ON(block > EXT4_MAX_BLOCK_FILE_PHYS);
ea_idebug(inode, "creating block %llu",
(unsigned long long)block);
new_bh = sb_getblk(sb, block);
if (unlikely(!new_bh)) {
error = -ENOMEM;
getblk_failed:
ext4_free_blocks(handle, inode, NULL, block, 1,
EXT4_FREE_BLOCKS_METADATA);
goto cleanup;
}
lock_buffer(new_bh);
error = ext4_journal_get_create_access(handle, new_bh);
if (error) {
unlock_buffer(new_bh);
error = -EIO;
goto getblk_failed;
}
memcpy(new_bh->b_data, s->base, new_bh->b_size);
set_buffer_uptodate(new_bh);
unlock_buffer(new_bh);
ext4_xattr_cache_insert(ext4_mb_cache, new_bh);
error = ext4_handle_dirty_xattr_block(handle,
inode, new_bh);
if (error)
goto cleanup;
}
}
/* Update the inode. */
EXT4_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
/* Drop the previous xattr block. */
if (bs->bh && bs->bh != new_bh)
ext4_xattr_release_block(handle, inode, bs->bh);
error = 0;
cleanup:
if (ce)
mb_cache_entry_release(ce);
brelse(new_bh);
if (!(bs->bh && s->base == bs->bh->b_data))
kfree(s->base);
return error;
cleanup_dquot:
dquot_free_block(inode, EXT4_C2B(EXT4_SB(sb), 1));
goto cleanup;
bad_block:
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
goto cleanup;
#undef header
}
int ext4_xattr_ibody_find(struct inode *inode, struct ext4_xattr_info *i,
struct ext4_xattr_ibody_find *is)
{
struct ext4_xattr_ibody_header *header;
struct ext4_inode *raw_inode;
int error;
if (EXT4_I(inode)->i_extra_isize == 0)
return 0;
raw_inode = ext4_raw_inode(&is->iloc);
header = IHDR(inode, raw_inode);
is->s.base = is->s.first = IFIRST(header);
is->s.here = is->s.first;
is->s.end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
error = ext4_xattr_check_names(IFIRST(header), is->s.end,
IFIRST(header));
if (error)
return error;
/* Find the named attribute. */
error = ext4_xattr_find_entry(&is->s.here, i->name_index,
i->name, is->s.end -
(void *)is->s.base, 0);
if (error && error != -ENODATA)
return error;
is->s.not_found = error;
}
return 0;
}
int ext4_xattr_ibody_inline_set(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct ext4_xattr_ibody_find *is)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_search *s = &is->s;
int error;
if (EXT4_I(inode)->i_extra_isize == 0)
return -ENOSPC;
error = ext4_xattr_set_entry(i, s);
if (error) {
if (error == -ENOSPC &&
ext4_has_inline_data(inode)) {
error = ext4_try_to_evict_inline_data(handle, inode,
EXT4_XATTR_LEN(strlen(i->name) +
EXT4_XATTR_SIZE(i->value_len)));
if (error)
return error;
error = ext4_xattr_ibody_find(inode, i, is);
if (error)
return error;
error = ext4_xattr_set_entry(i, s);
}
if (error)
return error;
}
header = IHDR(inode, ext4_raw_inode(&is->iloc));
if (!IS_LAST_ENTRY(s->first)) {
header->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
ext4_set_inode_state(inode, EXT4_STATE_XATTR);
} else {
header->h_magic = cpu_to_le32(0);
ext4_clear_inode_state(inode, EXT4_STATE_XATTR);
}
return 0;
}
static int ext4_xattr_ibody_set(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct ext4_xattr_ibody_find *is)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_search *s = &is->s;
int error;
if (EXT4_I(inode)->i_extra_isize == 0)
return -ENOSPC;
error = ext4_xattr_set_entry(i, s);
if (error)
return error;
header = IHDR(inode, ext4_raw_inode(&is->iloc));
if (!IS_LAST_ENTRY(s->first)) {
header->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
ext4_set_inode_state(inode, EXT4_STATE_XATTR);
} else {
header->h_magic = cpu_to_le32(0);
ext4_clear_inode_state(inode, EXT4_STATE_XATTR);
}
return 0;
}
/*
* ext4_xattr_set_handle()
*
* Create, replace or remove an extended attribute for this inode. Value
* is NULL to remove an existing extended attribute, and non-NULL to
* either replace an existing extended attribute, or create a new extended
* attribute. The flags XATTR_REPLACE and XATTR_CREATE
* specify that an extended attribute must exist and must not exist
* previous to the call, respectively.
*
* Returns 0, or a negative error number on failure.
*/
int
ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
const char *name, const void *value, size_t value_len,
int flags)
{
struct ext4_xattr_info i = {
.name_index = name_index,
.name = name,
.value = value,
.value_len = value_len,
};
struct ext4_xattr_ibody_find is = {
.s = { .not_found = -ENODATA, },
};
struct ext4_xattr_block_find bs = {
.s = { .not_found = -ENODATA, },
};
unsigned long no_expand;
int error;
if (!name)
return -EINVAL;
if (strlen(name) > 255)
return -ERANGE;
down_write(&EXT4_I(inode)->xattr_sem);
no_expand = ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND);
ext4_set_inode_state(inode, EXT4_STATE_NO_EXPAND);
error = ext4_reserve_inode_write(handle, inode, &is.iloc);
if (error)
goto cleanup;
if (ext4_test_inode_state(inode, EXT4_STATE_NEW)) {
struct ext4_inode *raw_inode = ext4_raw_inode(&is.iloc);
memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
ext4_clear_inode_state(inode, EXT4_STATE_NEW);
}
error = ext4_xattr_ibody_find(inode, &i, &is);
if (error)
goto cleanup;
if (is.s.not_found)
error = ext4_xattr_block_find(inode, &i, &bs);
if (error)
goto cleanup;
if (is.s.not_found && bs.s.not_found) {
error = -ENODATA;
if (flags & XATTR_REPLACE)
goto cleanup;
error = 0;
if (!value)
goto cleanup;
} else {
error = -EEXIST;
if (flags & XATTR_CREATE)
goto cleanup;
}
if (!value) {
if (!is.s.not_found)
error = ext4_xattr_ibody_set(handle, inode, &i, &is);
else if (!bs.s.not_found)
error = ext4_xattr_block_set(handle, inode, &i, &bs);
} else {
error = ext4_xattr_ibody_set(handle, inode, &i, &is);
if (!error && !bs.s.not_found) {
i.value = NULL;
error = ext4_xattr_block_set(handle, inode, &i, &bs);
} else if (error == -ENOSPC) {
if (EXT4_I(inode)->i_file_acl && !bs.s.base) {
error = ext4_xattr_block_find(inode, &i, &bs);
if (error)
goto cleanup;
}
error = ext4_xattr_block_set(handle, inode, &i, &bs);
if (error)
goto cleanup;
if (!is.s.not_found) {
i.value = NULL;
error = ext4_xattr_ibody_set(handle, inode, &i,
&is);
}
}
}
if (!error) {
ext4_xattr_update_super_block(handle, inode->i_sb);
inode->i_ctime = ext4_current_time(inode);
if (!value)
ext4_clear_inode_state(inode, EXT4_STATE_NO_EXPAND);
error = ext4_mark_iloc_dirty(handle, inode, &is.iloc);
/*
* The bh is consumed by ext4_mark_iloc_dirty, even with
* error != 0.
*/
is.iloc.bh = NULL;
if (IS_SYNC(inode))
ext4_handle_sync(handle);
}
cleanup:
brelse(is.iloc.bh);
brelse(bs.bh);
if (no_expand == 0)
ext4_clear_inode_state(inode, EXT4_STATE_NO_EXPAND);
up_write(&EXT4_I(inode)->xattr_sem);
return error;
}
/*
* ext4_xattr_set()
*
* Like ext4_xattr_set_handle, but start from an inode. This extended
* attribute modification is a filesystem transaction by itself.
*
* Returns 0, or a negative error number on failure.
*/
int
ext4_xattr_set(struct inode *inode, int name_index, const char *name,
const void *value, size_t value_len, int flags)
{
handle_t *handle;
int error, retries = 0;
int credits = ext4_jbd2_credits_xattr(inode);
retry:
handle = ext4_journal_start(inode, EXT4_HT_XATTR, credits);
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
} else {
int error2;
error = ext4_xattr_set_handle(handle, inode, name_index, name,
value, value_len, flags);
error2 = ext4_journal_stop(handle);
if (error == -ENOSPC &&
ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
if (error == 0)
error = error2;
}
return error;
}
/*
* Shift the EA entries in the inode to create space for the increased
* i_extra_isize.
*/
static void ext4_xattr_shift_entries(struct ext4_xattr_entry *entry,
int value_offs_shift, void *to,
void *from, size_t n, int blocksize)
{
struct ext4_xattr_entry *last = entry;
int new_offs;
/* Adjust the value offsets of the entries */
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
new_offs = le16_to_cpu(last->e_value_offs) +
value_offs_shift;
BUG_ON(new_offs + le32_to_cpu(last->e_value_size)
> blocksize);
last->e_value_offs = cpu_to_le16(new_offs);
}
}
/* Shift the entries by n bytes */
memmove(to, from, n);
}
/*
* Expand an inode by new_extra_isize bytes when EAs are present.
* Returns 0 on success or negative error number on failure.
*/
int ext4_expand_extra_isize_ea(struct inode *inode, int new_extra_isize,
struct ext4_inode *raw_inode, handle_t *handle)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_entry *entry, *last, *first;
struct buffer_head *bh = NULL;
struct ext4_xattr_ibody_find *is = NULL;
struct ext4_xattr_block_find *bs = NULL;
char *buffer = NULL, *b_entry_name = NULL;
size_t min_offs, free;
int total_ino;
void *base, *start, *end;
int extra_isize = 0, error = 0, tried_min_extra_isize = 0;
int s_min_extra_isize = le16_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_min_extra_isize);
down_write(&EXT4_I(inode)->xattr_sem);
retry:
if (EXT4_I(inode)->i_extra_isize >= new_extra_isize) {
up_write(&EXT4_I(inode)->xattr_sem);
return 0;
}
header = IHDR(inode, raw_inode);
entry = IFIRST(header);
/*
* Check if enough free space is available in the inode to shift the
* entries ahead by new_extra_isize.
*/
base = start = entry;
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
min_offs = end - base;
last = entry;
total_ino = sizeof(struct ext4_xattr_ibody_header);
free = ext4_xattr_free_space(last, &min_offs, base, &total_ino);
if (free >= new_extra_isize) {
entry = IFIRST(header);
ext4_xattr_shift_entries(entry, EXT4_I(inode)->i_extra_isize
- new_extra_isize, (void *)raw_inode +
EXT4_GOOD_OLD_INODE_SIZE + new_extra_isize,
(void *)header, total_ino,
inode->i_sb->s_blocksize);
EXT4_I(inode)->i_extra_isize = new_extra_isize;
error = 0;
goto cleanup;
}
/*
* Enough free space isn't available in the inode, check if
* EA block can hold new_extra_isize bytes.
*/
if (EXT4_I(inode)->i_file_acl) {
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
if (ext4_xattr_check_block(inode, bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EFSCORRUPTED;
goto cleanup;
}
base = BHDR(bh);
first = BFIRST(bh);
end = bh->b_data + bh->b_size;
min_offs = end - base;
free = ext4_xattr_free_space(first, &min_offs, base, NULL);
if (free < new_extra_isize) {
if (!tried_min_extra_isize && s_min_extra_isize) {
tried_min_extra_isize++;
new_extra_isize = s_min_extra_isize;
brelse(bh);
goto retry;
}
error = -1;
goto cleanup;
}
} else {
free = inode->i_sb->s_blocksize;
}
while (new_extra_isize > 0) {
size_t offs, size, entry_size;
struct ext4_xattr_entry *small_entry = NULL;
struct ext4_xattr_info i = {
.value = NULL,
.value_len = 0,
};
unsigned int total_size; /* EA entry size + value size */
unsigned int shift_bytes; /* No. of bytes to shift EAs by? */
unsigned int min_total_size = ~0U;
is = kzalloc(sizeof(struct ext4_xattr_ibody_find), GFP_NOFS);
bs = kzalloc(sizeof(struct ext4_xattr_block_find), GFP_NOFS);
if (!is || !bs) {
error = -ENOMEM;
goto cleanup;
}
is->s.not_found = -ENODATA;
bs->s.not_found = -ENODATA;
is->iloc.bh = NULL;
bs->bh = NULL;
last = IFIRST(header);
/* Find the entry best suited to be pushed into EA block */
entry = NULL;
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
total_size =
EXT4_XATTR_SIZE(le32_to_cpu(last->e_value_size)) +
EXT4_XATTR_LEN(last->e_name_len);
if (total_size <= free && total_size < min_total_size) {
if (total_size < new_extra_isize) {
small_entry = last;
} else {
entry = last;
min_total_size = total_size;
}
}
}
if (entry == NULL) {
if (small_entry) {
entry = small_entry;
} else {
if (!tried_min_extra_isize &&
s_min_extra_isize) {
tried_min_extra_isize++;
new_extra_isize = s_min_extra_isize;
kfree(is); is = NULL;
kfree(bs); bs = NULL;
brelse(bh);
goto retry;
}
error = -1;
goto cleanup;
}
}
offs = le16_to_cpu(entry->e_value_offs);
size = le32_to_cpu(entry->e_value_size);
entry_size = EXT4_XATTR_LEN(entry->e_name_len);
i.name_index = entry->e_name_index,
buffer = kmalloc(EXT4_XATTR_SIZE(size), GFP_NOFS);
b_entry_name = kmalloc(entry->e_name_len + 1, GFP_NOFS);
if (!buffer || !b_entry_name) {
error = -ENOMEM;
goto cleanup;
}
/* Save the entry name and the entry value */
memcpy(buffer, (void *)IFIRST(header) + offs,
EXT4_XATTR_SIZE(size));
memcpy(b_entry_name, entry->e_name, entry->e_name_len);
b_entry_name[entry->e_name_len] = '\0';
i.name = b_entry_name;
error = ext4_get_inode_loc(inode, &is->iloc);
if (error)
goto cleanup;
error = ext4_xattr_ibody_find(inode, &i, is);
if (error)
goto cleanup;
/* Remove the chosen entry from the inode */
error = ext4_xattr_ibody_set(handle, inode, &i, is);
if (error)
goto cleanup;
entry = IFIRST(header);
if (entry_size + EXT4_XATTR_SIZE(size) >= new_extra_isize)
shift_bytes = new_extra_isize;
else
shift_bytes = entry_size + size;
/* Adjust the offsets and shift the remaining entries ahead */
ext4_xattr_shift_entries(entry, EXT4_I(inode)->i_extra_isize -
shift_bytes, (void *)raw_inode +
EXT4_GOOD_OLD_INODE_SIZE + extra_isize + shift_bytes,
(void *)header, total_ino - entry_size,
inode->i_sb->s_blocksize);
extra_isize += shift_bytes;
new_extra_isize -= shift_bytes;
EXT4_I(inode)->i_extra_isize = extra_isize;
i.name = b_entry_name;
i.value = buffer;
i.value_len = size;
error = ext4_xattr_block_find(inode, &i, bs);
if (error)
goto cleanup;
/* Add entry which was removed from the inode into the block */
error = ext4_xattr_block_set(handle, inode, &i, bs);
if (error)
goto cleanup;
kfree(b_entry_name);
kfree(buffer);
b_entry_name = NULL;
buffer = NULL;
brelse(is->iloc.bh);
kfree(is);
kfree(bs);
}
brelse(bh);
up_write(&EXT4_I(inode)->xattr_sem);
return 0;
cleanup:
kfree(b_entry_name);
kfree(buffer);
if (is)
brelse(is->iloc.bh);
kfree(is);
kfree(bs);
brelse(bh);
up_write(&EXT4_I(inode)->xattr_sem);
return error;
}
/*
* ext4_xattr_delete_inode()
*
* Free extended attribute resources associated with this inode. This
* is called immediately before an inode is freed. We have exclusive
* access to the inode.
*/
void
ext4_xattr_delete_inode(handle_t *handle, struct inode *inode)
{
struct buffer_head *bh = NULL;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
if (!bh) {
EXT4_ERROR_INODE(inode, "block %llu read error",
EXT4_I(inode)->i_file_acl);
goto cleanup;
}
if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
BHDR(bh)->h_blocks != cpu_to_le32(1)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
goto cleanup;
}
ext4_xattr_release_block(handle, inode, bh);
EXT4_I(inode)->i_file_acl = 0;
cleanup:
brelse(bh);
}
/*
* ext4_xattr_put_super()
*
* This is called when a file system is unmounted.
*/
void
ext4_xattr_put_super(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
}
/*
* ext4_xattr_cache_insert()
*
* Create a new entry in the extended attribute cache, and insert
* it unless such an entry is already in the cache.
*
* Returns 0, or a negative error number on failure.
*/
static void
ext4_xattr_cache_insert(struct mb_cache *ext4_mb_cache, struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(BHDR(bh)->h_hash);
struct mb_cache_entry *ce;
int error;
ce = mb_cache_entry_alloc(ext4_mb_cache, GFP_NOFS);
if (!ce) {
ea_bdebug(bh, "out of memory");
return;
}
error = mb_cache_entry_insert(ce, bh->b_bdev, bh->b_blocknr, hash);
if (error) {
mb_cache_entry_free(ce);
if (error == -EBUSY) {
ea_bdebug(bh, "already in cache");
error = 0;
}
} else {
ea_bdebug(bh, "inserting [%x]", (int)hash);
mb_cache_entry_release(ce);
}
}
/*
* ext4_xattr_cmp()
*
* Compare two extended attribute blocks for equality.
*
* Returns 0 if the blocks are equal, 1 if they differ, and
* a negative error number on errors.
*/
static int
ext4_xattr_cmp(struct ext4_xattr_header *header1,
struct ext4_xattr_header *header2)
{
struct ext4_xattr_entry *entry1, *entry2;
entry1 = ENTRY(header1+1);
entry2 = ENTRY(header2+1);
while (!IS_LAST_ENTRY(entry1)) {
if (IS_LAST_ENTRY(entry2))
return 1;
if (entry1->e_hash != entry2->e_hash ||
entry1->e_name_index != entry2->e_name_index ||
entry1->e_name_len != entry2->e_name_len ||
entry1->e_value_size != entry2->e_value_size ||
memcmp(entry1->e_name, entry2->e_name, entry1->e_name_len))
return 1;
if (entry1->e_value_block != 0 || entry2->e_value_block != 0)
return -EFSCORRUPTED;
if (memcmp((char *)header1 + le16_to_cpu(entry1->e_value_offs),
(char *)header2 + le16_to_cpu(entry2->e_value_offs),
le32_to_cpu(entry1->e_value_size)))
return 1;
entry1 = EXT4_XATTR_NEXT(entry1);
entry2 = EXT4_XATTR_NEXT(entry2);
}
if (!IS_LAST_ENTRY(entry2))
return 1;
return 0;
}
/*
* ext4_xattr_cache_find()
*
* Find an identical extended attribute block.
*
* Returns a pointer to the block found, or NULL if such a block was
* not found or an error occurred.
*/
static struct buffer_head *
ext4_xattr_cache_find(struct inode *inode, struct ext4_xattr_header *header,
struct mb_cache_entry **pce)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb_cache_entry_find_first(ext4_mb_cache, inode->i_sb->s_bdev,
hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
EXT4_ERROR_INODE(inode, "block %lu read error",
(unsigned long) ce->e_block);
} else if (le32_to_cpu(BHDR(bh)->h_refcount) >=
EXT4_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %lu refcount %d>=%d",
(unsigned long) ce->e_block,
le32_to_cpu(BHDR(bh)->h_refcount),
EXT4_XATTR_REFCOUNT_MAX);
} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
*pce = ce;
return bh;
}
brelse(bh);
ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
}
#define NAME_HASH_SHIFT 5
#define VALUE_HASH_SHIFT 16
/*
* ext4_xattr_hash_entry()
*
* Compute the hash of an extended attribute.
*/
static inline void ext4_xattr_hash_entry(struct ext4_xattr_header *header,
struct ext4_xattr_entry *entry)
{
__u32 hash = 0;
char *name = entry->e_name;
int n;
for (n = 0; n < entry->e_name_len; n++) {
hash = (hash << NAME_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
*name++;
}
if (entry->e_value_block == 0 && entry->e_value_size != 0) {
__le32 *value = (__le32 *)((char *)header +
le16_to_cpu(entry->e_value_offs));
for (n = (le32_to_cpu(entry->e_value_size) +
EXT4_XATTR_ROUND) >> EXT4_XATTR_PAD_BITS; n; n--) {
hash = (hash << VALUE_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
le32_to_cpu(*value++);
}
}
entry->e_hash = cpu_to_le32(hash);
}
#undef NAME_HASH_SHIFT
#undef VALUE_HASH_SHIFT
#define BLOCK_HASH_SHIFT 16
/*
* ext4_xattr_rehash()
*
* Re-compute the extended attribute hash value after an entry has changed.
*/
static void ext4_xattr_rehash(struct ext4_xattr_header *header,
struct ext4_xattr_entry *entry)
{
struct ext4_xattr_entry *here;
__u32 hash = 0;
ext4_xattr_hash_entry(header, entry);
here = ENTRY(header+1);
while (!IS_LAST_ENTRY(here)) {
if (!here->e_hash) {
/* Block is not shared if an entry's hash value == 0 */
hash = 0;
break;
}
hash = (hash << BLOCK_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - BLOCK_HASH_SHIFT)) ^
le32_to_cpu(here->e_hash);
here = EXT4_XATTR_NEXT(here);
}
header->h_hash = cpu_to_le32(hash);
}
#undef BLOCK_HASH_SHIFT
#define HASH_BUCKET_BITS 10
struct mb_cache *
ext4_xattr_create_cache(char *name)
{
return mb_cache_create(name, HASH_BUCKET_BITS);
}
void ext4_xattr_destroy_cache(struct mb_cache *cache)
{
if (cache)
mb_cache_destroy(cache);
}
| ./CrossVul/dataset_final_sorted/CWE-19/c/bad_1842_2 |
crossvul-cpp_data_bad_2422_1 | /*
* Based on arch/arm/mm/fault.c
*
* Copyright (C) 1995 Linus Torvalds
* Copyright (C) 1995-2004 Russell King
* Copyright (C) 2012 ARM Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/module.h>
#include <linux/signal.h>
#include <linux/mm.h>
#include <linux/hardirq.h>
#include <linux/init.h>
#include <linux/kprobes.h>
#include <linux/uaccess.h>
#include <linux/page-flags.h>
#include <linux/sched.h>
#include <linux/highmem.h>
#include <linux/perf_event.h>
#include <asm/exception.h>
#include <asm/debug-monitors.h>
#include <asm/esr.h>
#include <asm/system_misc.h>
#include <asm/pgtable.h>
#include <asm/tlbflush.h>
static const char *fault_name(unsigned int esr);
/*
* Dump out the page tables associated with 'addr' in mm 'mm'.
*/
void show_pte(struct mm_struct *mm, unsigned long addr)
{
pgd_t *pgd;
if (!mm)
mm = &init_mm;
pr_alert("pgd = %p\n", mm->pgd);
pgd = pgd_offset(mm, addr);
pr_alert("[%08lx] *pgd=%016llx", addr, pgd_val(*pgd));
do {
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
if (pgd_none(*pgd) || pgd_bad(*pgd))
break;
pud = pud_offset(pgd, addr);
if (pud_none(*pud) || pud_bad(*pud))
break;
pmd = pmd_offset(pud, addr);
printk(", *pmd=%016llx", pmd_val(*pmd));
if (pmd_none(*pmd) || pmd_bad(*pmd))
break;
pte = pte_offset_map(pmd, addr);
printk(", *pte=%016llx", pte_val(*pte));
pte_unmap(pte);
} while(0);
printk("\n");
}
/*
* The kernel tried to access some page that wasn't present.
*/
static void __do_kernel_fault(struct mm_struct *mm, unsigned long addr,
unsigned int esr, struct pt_regs *regs)
{
/*
* Are we prepared to handle this kernel fault?
*/
if (fixup_exception(regs))
return;
/*
* No handler, we'll have to terminate things with extreme prejudice.
*/
bust_spinlocks(1);
pr_alert("Unable to handle kernel %s at virtual address %08lx\n",
(addr < PAGE_SIZE) ? "NULL pointer dereference" :
"paging request", addr);
show_pte(mm, addr);
die("Oops", regs, esr);
bust_spinlocks(0);
do_exit(SIGKILL);
}
/*
* Something tried to access memory that isn't in our memory map. User mode
* accesses just cause a SIGSEGV
*/
static void __do_user_fault(struct task_struct *tsk, unsigned long addr,
unsigned int esr, unsigned int sig, int code,
struct pt_regs *regs)
{
struct siginfo si;
if (show_unhandled_signals && unhandled_signal(tsk, sig) &&
printk_ratelimit()) {
pr_info("%s[%d]: unhandled %s (%d) at 0x%08lx, esr 0x%03x\n",
tsk->comm, task_pid_nr(tsk), fault_name(esr), sig,
addr, esr);
show_pte(tsk->mm, addr);
show_regs(regs);
}
tsk->thread.fault_address = addr;
tsk->thread.fault_code = esr;
si.si_signo = sig;
si.si_errno = 0;
si.si_code = code;
si.si_addr = (void __user *)addr;
force_sig_info(sig, &si, tsk);
}
static void do_bad_area(unsigned long addr, unsigned int esr, struct pt_regs *regs)
{
struct task_struct *tsk = current;
struct mm_struct *mm = tsk->active_mm;
/*
* If we are in kernel mode at this point, we have no context to
* handle this fault with.
*/
if (user_mode(regs))
__do_user_fault(tsk, addr, esr, SIGSEGV, SEGV_MAPERR, regs);
else
__do_kernel_fault(mm, addr, esr, regs);
}
#define VM_FAULT_BADMAP 0x010000
#define VM_FAULT_BADACCESS 0x020000
#define ESR_LNX_EXEC (1 << 24)
static int __do_page_fault(struct mm_struct *mm, unsigned long addr,
unsigned int mm_flags, unsigned long vm_flags,
struct task_struct *tsk)
{
struct vm_area_struct *vma;
int fault;
vma = find_vma(mm, addr);
fault = VM_FAULT_BADMAP;
if (unlikely(!vma))
goto out;
if (unlikely(vma->vm_start > addr))
goto check_stack;
/*
* Ok, we have a good vm_area for this memory access, so we can handle
* it.
*/
good_area:
/*
* Check that the permissions on the VMA allow for the fault which
* occurred.
*/
if (!(vma->vm_flags & vm_flags)) {
fault = VM_FAULT_BADACCESS;
goto out;
}
return handle_mm_fault(mm, vma, addr & PAGE_MASK, mm_flags);
check_stack:
if (vma->vm_flags & VM_GROWSDOWN && !expand_stack(vma, addr))
goto good_area;
out:
return fault;
}
static int __kprobes do_page_fault(unsigned long addr, unsigned int esr,
struct pt_regs *regs)
{
struct task_struct *tsk;
struct mm_struct *mm;
int fault, sig, code;
unsigned long vm_flags = VM_READ | VM_WRITE;
unsigned int mm_flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
tsk = current;
mm = tsk->mm;
/* Enable interrupts if they were enabled in the parent context. */
if (interrupts_enabled(regs))
local_irq_enable();
/*
* If we're in an interrupt or have no user context, we must not take
* the fault.
*/
if (in_atomic() || !mm)
goto no_context;
if (user_mode(regs))
mm_flags |= FAULT_FLAG_USER;
if (esr & ESR_LNX_EXEC) {
vm_flags = VM_EXEC;
} else if ((esr & ESR_EL1_WRITE) && !(esr & ESR_EL1_CM)) {
vm_flags = VM_WRITE;
mm_flags |= FAULT_FLAG_WRITE;
}
/*
* As per x86, we may deadlock here. However, since the kernel only
* validly references user space from well defined areas of the code,
* we can bug out early if this is from code which shouldn't.
*/
if (!down_read_trylock(&mm->mmap_sem)) {
if (!user_mode(regs) && !search_exception_tables(regs->pc))
goto no_context;
retry:
down_read(&mm->mmap_sem);
} else {
/*
* The above down_read_trylock() might have succeeded in which
* case, we'll have missed the might_sleep() from down_read().
*/
might_sleep();
#ifdef CONFIG_DEBUG_VM
if (!user_mode(regs) && !search_exception_tables(regs->pc))
goto no_context;
#endif
}
fault = __do_page_fault(mm, addr, mm_flags, vm_flags, tsk);
/*
* If we need to retry but a fatal signal is pending, handle the
* signal first. We do not need to release the mmap_sem because it
* would already be released in __lock_page_or_retry in mm/filemap.c.
*/
if ((fault & VM_FAULT_RETRY) && fatal_signal_pending(current))
return 0;
/*
* Major/minor page fault accounting is only done on the initial
* attempt. If we go through a retry, it is extremely likely that the
* page will be found in page cache at that point.
*/
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, addr);
if (mm_flags & FAULT_FLAG_ALLOW_RETRY) {
if (fault & VM_FAULT_MAJOR) {
tsk->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs,
addr);
} else {
tsk->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs,
addr);
}
if (fault & VM_FAULT_RETRY) {
/*
* Clear FAULT_FLAG_ALLOW_RETRY to avoid any risk of
* starvation.
*/
mm_flags &= ~FAULT_FLAG_ALLOW_RETRY;
goto retry;
}
}
up_read(&mm->mmap_sem);
/*
* Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR
*/
if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP |
VM_FAULT_BADACCESS))))
return 0;
/*
* If we are in kernel mode at this point, we have no context to
* handle this fault with.
*/
if (!user_mode(regs))
goto no_context;
if (fault & VM_FAULT_OOM) {
/*
* We ran out of memory, call the OOM killer, and return to
* userspace (which will retry the fault, or kill us if we got
* oom-killed).
*/
pagefault_out_of_memory();
return 0;
}
if (fault & VM_FAULT_SIGBUS) {
/*
* We had some memory, but were unable to successfully fix up
* this page fault.
*/
sig = SIGBUS;
code = BUS_ADRERR;
} else {
/*
* Something tried to access memory that isn't in our memory
* map.
*/
sig = SIGSEGV;
code = fault == VM_FAULT_BADACCESS ?
SEGV_ACCERR : SEGV_MAPERR;
}
__do_user_fault(tsk, addr, esr, sig, code, regs);
return 0;
no_context:
__do_kernel_fault(mm, addr, esr, regs);
return 0;
}
/*
* First Level Translation Fault Handler
*
* We enter here because the first level page table doesn't contain a valid
* entry for the address.
*
* If the address is in kernel space (>= TASK_SIZE), then we are probably
* faulting in the vmalloc() area.
*
* If the init_task's first level page tables contains the relevant entry, we
* copy the it to this task. If not, we send the process a signal, fixup the
* exception, or oops the kernel.
*
* NOTE! We MUST NOT take any locks for this case. We may be in an interrupt
* or a critical region, and should only copy the information from the master
* page table, nothing more.
*/
static int __kprobes do_translation_fault(unsigned long addr,
unsigned int esr,
struct pt_regs *regs)
{
if (addr < TASK_SIZE)
return do_page_fault(addr, esr, regs);
do_bad_area(addr, esr, regs);
return 0;
}
/*
* This abort handler always returns "fault".
*/
static int do_bad(unsigned long addr, unsigned int esr, struct pt_regs *regs)
{
return 1;
}
static struct fault_info {
int (*fn)(unsigned long addr, unsigned int esr, struct pt_regs *regs);
int sig;
int code;
const char *name;
} fault_info[] = {
{ do_bad, SIGBUS, 0, "ttbr address size fault" },
{ do_bad, SIGBUS, 0, "level 1 address size fault" },
{ do_bad, SIGBUS, 0, "level 2 address size fault" },
{ do_bad, SIGBUS, 0, "level 3 address size fault" },
{ do_translation_fault, SIGSEGV, SEGV_MAPERR, "input address range fault" },
{ do_translation_fault, SIGSEGV, SEGV_MAPERR, "level 1 translation fault" },
{ do_translation_fault, SIGSEGV, SEGV_MAPERR, "level 2 translation fault" },
{ do_page_fault, SIGSEGV, SEGV_MAPERR, "level 3 translation fault" },
{ do_bad, SIGBUS, 0, "reserved access flag fault" },
{ do_page_fault, SIGSEGV, SEGV_ACCERR, "level 1 access flag fault" },
{ do_page_fault, SIGSEGV, SEGV_ACCERR, "level 2 access flag fault" },
{ do_page_fault, SIGSEGV, SEGV_ACCERR, "level 3 access flag fault" },
{ do_bad, SIGBUS, 0, "reserved permission fault" },
{ do_page_fault, SIGSEGV, SEGV_ACCERR, "level 1 permission fault" },
{ do_page_fault, SIGSEGV, SEGV_ACCERR, "level 2 permission fault" },
{ do_page_fault, SIGSEGV, SEGV_ACCERR, "level 3 permission fault" },
{ do_bad, SIGBUS, 0, "synchronous external abort" },
{ do_bad, SIGBUS, 0, "asynchronous external abort" },
{ do_bad, SIGBUS, 0, "unknown 18" },
{ do_bad, SIGBUS, 0, "unknown 19" },
{ do_bad, SIGBUS, 0, "synchronous abort (translation table walk)" },
{ do_bad, SIGBUS, 0, "synchronous abort (translation table walk)" },
{ do_bad, SIGBUS, 0, "synchronous abort (translation table walk)" },
{ do_bad, SIGBUS, 0, "synchronous abort (translation table walk)" },
{ do_bad, SIGBUS, 0, "synchronous parity error" },
{ do_bad, SIGBUS, 0, "asynchronous parity error" },
{ do_bad, SIGBUS, 0, "unknown 26" },
{ do_bad, SIGBUS, 0, "unknown 27" },
{ do_bad, SIGBUS, 0, "synchronous parity error (translation table walk" },
{ do_bad, SIGBUS, 0, "synchronous parity error (translation table walk" },
{ do_bad, SIGBUS, 0, "synchronous parity error (translation table walk" },
{ do_bad, SIGBUS, 0, "synchronous parity error (translation table walk" },
{ do_bad, SIGBUS, 0, "unknown 32" },
{ do_bad, SIGBUS, BUS_ADRALN, "alignment fault" },
{ do_bad, SIGBUS, 0, "debug event" },
{ do_bad, SIGBUS, 0, "unknown 35" },
{ do_bad, SIGBUS, 0, "unknown 36" },
{ do_bad, SIGBUS, 0, "unknown 37" },
{ do_bad, SIGBUS, 0, "unknown 38" },
{ do_bad, SIGBUS, 0, "unknown 39" },
{ do_bad, SIGBUS, 0, "unknown 40" },
{ do_bad, SIGBUS, 0, "unknown 41" },
{ do_bad, SIGBUS, 0, "unknown 42" },
{ do_bad, SIGBUS, 0, "unknown 43" },
{ do_bad, SIGBUS, 0, "unknown 44" },
{ do_bad, SIGBUS, 0, "unknown 45" },
{ do_bad, SIGBUS, 0, "unknown 46" },
{ do_bad, SIGBUS, 0, "unknown 47" },
{ do_bad, SIGBUS, 0, "unknown 48" },
{ do_bad, SIGBUS, 0, "unknown 49" },
{ do_bad, SIGBUS, 0, "unknown 50" },
{ do_bad, SIGBUS, 0, "unknown 51" },
{ do_bad, SIGBUS, 0, "implementation fault (lockdown abort)" },
{ do_bad, SIGBUS, 0, "unknown 53" },
{ do_bad, SIGBUS, 0, "unknown 54" },
{ do_bad, SIGBUS, 0, "unknown 55" },
{ do_bad, SIGBUS, 0, "unknown 56" },
{ do_bad, SIGBUS, 0, "unknown 57" },
{ do_bad, SIGBUS, 0, "implementation fault (coprocessor abort)" },
{ do_bad, SIGBUS, 0, "unknown 59" },
{ do_bad, SIGBUS, 0, "unknown 60" },
{ do_bad, SIGBUS, 0, "unknown 61" },
{ do_bad, SIGBUS, 0, "unknown 62" },
{ do_bad, SIGBUS, 0, "unknown 63" },
};
static const char *fault_name(unsigned int esr)
{
const struct fault_info *inf = fault_info + (esr & 63);
return inf->name;
}
/*
* Dispatch a data abort to the relevant handler.
*/
asmlinkage void __exception do_mem_abort(unsigned long addr, unsigned int esr,
struct pt_regs *regs)
{
const struct fault_info *inf = fault_info + (esr & 63);
struct siginfo info;
if (!inf->fn(addr, esr, regs))
return;
pr_alert("Unhandled fault: %s (0x%08x) at 0x%016lx\n",
inf->name, esr, addr);
info.si_signo = inf->sig;
info.si_errno = 0;
info.si_code = inf->code;
info.si_addr = (void __user *)addr;
arm64_notify_die("", regs, &info, esr);
}
/*
* Handle stack alignment exceptions.
*/
asmlinkage void __exception do_sp_pc_abort(unsigned long addr,
unsigned int esr,
struct pt_regs *regs)
{
struct siginfo info;
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRALN;
info.si_addr = (void __user *)addr;
arm64_notify_die("", regs, &info, esr);
}
static struct fault_info debug_fault_info[] = {
{ do_bad, SIGTRAP, TRAP_HWBKPT, "hardware breakpoint" },
{ do_bad, SIGTRAP, TRAP_HWBKPT, "hardware single-step" },
{ do_bad, SIGTRAP, TRAP_HWBKPT, "hardware watchpoint" },
{ do_bad, SIGBUS, 0, "unknown 3" },
{ do_bad, SIGTRAP, TRAP_BRKPT, "aarch32 BKPT" },
{ do_bad, SIGTRAP, 0, "aarch32 vector catch" },
{ do_bad, SIGTRAP, TRAP_BRKPT, "aarch64 BRK" },
{ do_bad, SIGBUS, 0, "unknown 7" },
};
void __init hook_debug_fault_code(int nr,
int (*fn)(unsigned long, unsigned int, struct pt_regs *),
int sig, int code, const char *name)
{
BUG_ON(nr < 0 || nr >= ARRAY_SIZE(debug_fault_info));
debug_fault_info[nr].fn = fn;
debug_fault_info[nr].sig = sig;
debug_fault_info[nr].code = code;
debug_fault_info[nr].name = name;
}
asmlinkage int __exception do_debug_exception(unsigned long addr,
unsigned int esr,
struct pt_regs *regs)
{
const struct fault_info *inf = debug_fault_info + DBG_ESR_EVT(esr);
struct siginfo info;
if (!inf->fn(addr, esr, regs))
return 1;
pr_alert("Unhandled debug exception: %s (0x%08x) at 0x%016lx\n",
inf->name, esr, addr);
info.si_signo = inf->sig;
info.si_errno = 0;
info.si_code = inf->code;
info.si_addr = (void __user *)addr;
arm64_notify_die("", regs, &info, 0);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-19/c/bad_2422_1 |
crossvul-cpp_data_good_1844_1 | #include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/list_bl.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/mbcache2.h>
/*
* Mbcache is a simple key-value store. Keys need not be unique, however
* key-value pairs are expected to be unique (we use this fact in
* mb2_cache_entry_delete_block()).
*
* Ext2 and ext4 use this cache for deduplication of extended attribute blocks.
* They use hash of a block contents as a key and block number as a value.
* That's why keys need not be unique (different xattr blocks may end up having
* the same hash). However block number always uniquely identifies a cache
* entry.
*
* We provide functions for creation and removal of entries, search by key,
* and a special "delete entry with given key-value pair" operation. Fixed
* size hash table is used for fast key lookups.
*/
struct mb2_cache {
/* Hash table of entries */
struct hlist_bl_head *c_hash;
/* log2 of hash table size */
int c_bucket_bits;
/* Protects c_lru_list, c_entry_count */
spinlock_t c_lru_list_lock;
struct list_head c_lru_list;
/* Number of entries in cache */
unsigned long c_entry_count;
struct shrinker c_shrink;
};
static struct kmem_cache *mb2_entry_cache;
/*
* mb2_cache_entry_create - create entry in cache
* @cache - cache where the entry should be created
* @mask - gfp mask with which the entry should be allocated
* @key - key of the entry
* @block - block that contains data
*
* Creates entry in @cache with key @key and records that data is stored in
* block @block. The function returns -EBUSY if entry with the same key
* and for the same block already exists in cache. Otherwise 0 is returned.
*/
int mb2_cache_entry_create(struct mb2_cache *cache, gfp_t mask, u32 key,
sector_t block)
{
struct mb2_cache_entry *entry, *dup;
struct hlist_bl_node *dup_node;
struct hlist_bl_head *head;
entry = kmem_cache_alloc(mb2_entry_cache, mask);
if (!entry)
return -ENOMEM;
INIT_LIST_HEAD(&entry->e_lru_list);
/* One ref for hash, one ref returned */
atomic_set(&entry->e_refcnt, 1);
entry->e_key = key;
entry->e_block = block;
head = &cache->c_hash[hash_32(key, cache->c_bucket_bits)];
entry->e_hash_list_head = head;
hlist_bl_lock(head);
hlist_bl_for_each_entry(dup, dup_node, head, e_hash_list) {
if (dup->e_key == key && dup->e_block == block) {
hlist_bl_unlock(head);
kmem_cache_free(mb2_entry_cache, entry);
return -EBUSY;
}
}
hlist_bl_add_head(&entry->e_hash_list, head);
hlist_bl_unlock(head);
spin_lock(&cache->c_lru_list_lock);
list_add_tail(&entry->e_lru_list, &cache->c_lru_list);
/* Grab ref for LRU list */
atomic_inc(&entry->e_refcnt);
cache->c_entry_count++;
spin_unlock(&cache->c_lru_list_lock);
return 0;
}
EXPORT_SYMBOL(mb2_cache_entry_create);
void __mb2_cache_entry_free(struct mb2_cache_entry *entry)
{
kmem_cache_free(mb2_entry_cache, entry);
}
EXPORT_SYMBOL(__mb2_cache_entry_free);
static struct mb2_cache_entry *__entry_find(struct mb2_cache *cache,
struct mb2_cache_entry *entry,
u32 key)
{
struct mb2_cache_entry *old_entry = entry;
struct hlist_bl_node *node;
struct hlist_bl_head *head;
if (entry)
head = entry->e_hash_list_head;
else
head = &cache->c_hash[hash_32(key, cache->c_bucket_bits)];
hlist_bl_lock(head);
if (entry && !hlist_bl_unhashed(&entry->e_hash_list))
node = entry->e_hash_list.next;
else
node = hlist_bl_first(head);
while (node) {
entry = hlist_bl_entry(node, struct mb2_cache_entry,
e_hash_list);
if (entry->e_key == key) {
atomic_inc(&entry->e_refcnt);
goto out;
}
node = node->next;
}
entry = NULL;
out:
hlist_bl_unlock(head);
if (old_entry)
mb2_cache_entry_put(cache, old_entry);
return entry;
}
/*
* mb2_cache_entry_find_first - find the first entry in cache with given key
* @cache: cache where we should search
* @key: key to look for
*
* Search in @cache for entry with key @key. Grabs reference to the first
* entry found and returns the entry.
*/
struct mb2_cache_entry *mb2_cache_entry_find_first(struct mb2_cache *cache,
u32 key)
{
return __entry_find(cache, NULL, key);
}
EXPORT_SYMBOL(mb2_cache_entry_find_first);
/*
* mb2_cache_entry_find_next - find next entry in cache with the same
* @cache: cache where we should search
* @entry: entry to start search from
*
* Finds next entry in the hash chain which has the same key as @entry.
* If @entry is unhashed (which can happen when deletion of entry races
* with the search), finds the first entry in the hash chain. The function
* drops reference to @entry and returns with a reference to the found entry.
*/
struct mb2_cache_entry *mb2_cache_entry_find_next(struct mb2_cache *cache,
struct mb2_cache_entry *entry)
{
return __entry_find(cache, entry, entry->e_key);
}
EXPORT_SYMBOL(mb2_cache_entry_find_next);
/* mb2_cache_entry_delete_block - remove information about block from cache
* @cache - cache we work with
* @key - key of the entry to remove
* @block - block containing data for @key
*
* Remove entry from cache @cache with key @key with data stored in @block.
*/
void mb2_cache_entry_delete_block(struct mb2_cache *cache, u32 key,
sector_t block)
{
struct hlist_bl_node *node;
struct hlist_bl_head *head;
struct mb2_cache_entry *entry;
head = &cache->c_hash[hash_32(key, cache->c_bucket_bits)];
hlist_bl_lock(head);
hlist_bl_for_each_entry(entry, node, head, e_hash_list) {
if (entry->e_key == key && entry->e_block == block) {
/* We keep hash list reference to keep entry alive */
hlist_bl_del_init(&entry->e_hash_list);
hlist_bl_unlock(head);
spin_lock(&cache->c_lru_list_lock);
if (!list_empty(&entry->e_lru_list)) {
list_del_init(&entry->e_lru_list);
cache->c_entry_count--;
atomic_dec(&entry->e_refcnt);
}
spin_unlock(&cache->c_lru_list_lock);
mb2_cache_entry_put(cache, entry);
return;
}
}
hlist_bl_unlock(head);
}
EXPORT_SYMBOL(mb2_cache_entry_delete_block);
/* mb2_cache_entry_touch - cache entry got used
* @cache - cache the entry belongs to
* @entry - entry that got used
*
* Move entry in lru list to reflect the fact that it was used.
*/
void mb2_cache_entry_touch(struct mb2_cache *cache,
struct mb2_cache_entry *entry)
{
spin_lock(&cache->c_lru_list_lock);
if (!list_empty(&entry->e_lru_list))
list_move_tail(&cache->c_lru_list, &entry->e_lru_list);
spin_unlock(&cache->c_lru_list_lock);
}
EXPORT_SYMBOL(mb2_cache_entry_touch);
static unsigned long mb2_cache_count(struct shrinker *shrink,
struct shrink_control *sc)
{
struct mb2_cache *cache = container_of(shrink, struct mb2_cache,
c_shrink);
return cache->c_entry_count;
}
/* Shrink number of entries in cache */
static unsigned long mb2_cache_scan(struct shrinker *shrink,
struct shrink_control *sc)
{
int nr_to_scan = sc->nr_to_scan;
struct mb2_cache *cache = container_of(shrink, struct mb2_cache,
c_shrink);
struct mb2_cache_entry *entry;
struct hlist_bl_head *head;
unsigned int shrunk = 0;
spin_lock(&cache->c_lru_list_lock);
while (nr_to_scan-- && !list_empty(&cache->c_lru_list)) {
entry = list_first_entry(&cache->c_lru_list,
struct mb2_cache_entry, e_lru_list);
list_del_init(&entry->e_lru_list);
cache->c_entry_count--;
/*
* We keep LRU list reference so that entry doesn't go away
* from under us.
*/
spin_unlock(&cache->c_lru_list_lock);
head = entry->e_hash_list_head;
hlist_bl_lock(head);
if (!hlist_bl_unhashed(&entry->e_hash_list)) {
hlist_bl_del_init(&entry->e_hash_list);
atomic_dec(&entry->e_refcnt);
}
hlist_bl_unlock(head);
if (mb2_cache_entry_put(cache, entry))
shrunk++;
cond_resched();
spin_lock(&cache->c_lru_list_lock);
}
spin_unlock(&cache->c_lru_list_lock);
return shrunk;
}
/*
* mb2_cache_create - create cache
* @bucket_bits: log2 of the hash table size
*
* Create cache for keys with 2^bucket_bits hash entries.
*/
struct mb2_cache *mb2_cache_create(int bucket_bits)
{
struct mb2_cache *cache;
int bucket_count = 1 << bucket_bits;
int i;
if (!try_module_get(THIS_MODULE))
return NULL;
cache = kzalloc(sizeof(struct mb2_cache), GFP_KERNEL);
if (!cache)
goto err_out;
cache->c_bucket_bits = bucket_bits;
INIT_LIST_HEAD(&cache->c_lru_list);
spin_lock_init(&cache->c_lru_list_lock);
cache->c_hash = kmalloc(bucket_count * sizeof(struct hlist_bl_head),
GFP_KERNEL);
if (!cache->c_hash) {
kfree(cache);
goto err_out;
}
for (i = 0; i < bucket_count; i++)
INIT_HLIST_BL_HEAD(&cache->c_hash[i]);
cache->c_shrink.count_objects = mb2_cache_count;
cache->c_shrink.scan_objects = mb2_cache_scan;
cache->c_shrink.seeks = DEFAULT_SEEKS;
register_shrinker(&cache->c_shrink);
return cache;
err_out:
module_put(THIS_MODULE);
return NULL;
}
EXPORT_SYMBOL(mb2_cache_create);
/*
* mb2_cache_destroy - destroy cache
* @cache: the cache to destroy
*
* Free all entries in cache and cache itself. Caller must make sure nobody
* (except shrinker) can reach @cache when calling this.
*/
void mb2_cache_destroy(struct mb2_cache *cache)
{
struct mb2_cache_entry *entry, *next;
unregister_shrinker(&cache->c_shrink);
/*
* We don't bother with any locking. Cache must not be used at this
* point.
*/
list_for_each_entry_safe(entry, next, &cache->c_lru_list, e_lru_list) {
if (!hlist_bl_unhashed(&entry->e_hash_list)) {
hlist_bl_del_init(&entry->e_hash_list);
atomic_dec(&entry->e_refcnt);
} else
WARN_ON(1);
list_del(&entry->e_lru_list);
WARN_ON(atomic_read(&entry->e_refcnt) != 1);
mb2_cache_entry_put(cache, entry);
}
kfree(cache->c_hash);
kfree(cache);
module_put(THIS_MODULE);
}
EXPORT_SYMBOL(mb2_cache_destroy);
static int __init mb2cache_init(void)
{
mb2_entry_cache = kmem_cache_create("mbcache",
sizeof(struct mb2_cache_entry), 0,
SLAB_RECLAIM_ACCOUNT|SLAB_MEM_SPREAD, NULL);
BUG_ON(!mb2_entry_cache);
return 0;
}
static void __exit mb2cache_exit(void)
{
kmem_cache_destroy(mb2_entry_cache);
}
module_init(mb2cache_init)
module_exit(mb2cache_exit)
MODULE_AUTHOR("Jan Kara <jack@suse.cz>");
MODULE_DESCRIPTION("Meta block cache (for extended attributes)");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-19/c/good_1844_1 |
crossvul-cpp_data_good_1842_1 | /*
* linux/fs/ext4/super.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/backing-dev.h>
#include <linux/parser.h>
#include <linux/buffer_head.h>
#include <linux/exportfs.h>
#include <linux/vfs.h>
#include <linux/random.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/quotaops.h>
#include <linux/seq_file.h>
#include <linux/ctype.h>
#include <linux/log2.h>
#include <linux/crc16.h>
#include <linux/cleancache.h>
#include <asm/uaccess.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include "ext4.h"
#include "ext4_extents.h" /* Needed for trace points definition */
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
#include "mballoc.h"
#define CREATE_TRACE_POINTS
#include <trace/events/ext4.h>
static struct ext4_lazy_init *ext4_li_info;
static struct mutex ext4_li_mtx;
static int ext4_mballoc_ready;
static struct ratelimit_state ext4_mount_msg_ratelimit;
static int ext4_load_journal(struct super_block *, struct ext4_super_block *,
unsigned long journal_devnum);
static int ext4_show_options(struct seq_file *seq, struct dentry *root);
static int ext4_commit_super(struct super_block *sb, int sync);
static void ext4_mark_recovery_complete(struct super_block *sb,
struct ext4_super_block *es);
static void ext4_clear_journal_err(struct super_block *sb,
struct ext4_super_block *es);
static int ext4_sync_fs(struct super_block *sb, int wait);
static int ext4_remount(struct super_block *sb, int *flags, char *data);
static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf);
static int ext4_unfreeze(struct super_block *sb);
static int ext4_freeze(struct super_block *sb);
static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data);
static inline int ext2_feature_set_ok(struct super_block *sb);
static inline int ext3_feature_set_ok(struct super_block *sb);
static int ext4_feature_set_ok(struct super_block *sb, int readonly);
static void ext4_destroy_lazyinit_thread(void);
static void ext4_unregister_li_request(struct super_block *sb);
static void ext4_clear_request_list(void);
/*
* Lock ordering
*
* Note the difference between i_mmap_sem (EXT4_I(inode)->i_mmap_sem) and
* i_mmap_rwsem (inode->i_mmap_rwsem)!
*
* page fault path:
* mmap_sem -> sb_start_pagefault -> i_mmap_sem (r) -> transaction start ->
* page lock -> i_data_sem (rw)
*
* buffered write path:
* sb_start_write -> i_mutex -> mmap_sem
* sb_start_write -> i_mutex -> transaction start -> page lock ->
* i_data_sem (rw)
*
* truncate:
* sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (w) -> i_mmap_sem (w) ->
* i_mmap_rwsem (w) -> page lock
* sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (w) -> i_mmap_sem (w) ->
* transaction start -> i_data_sem (rw)
*
* direct IO:
* sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (r) -> mmap_sem
* sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (r) ->
* transaction start -> i_data_sem (rw)
*
* writepages:
* transaction start -> page lock(s) -> i_data_sem (rw)
*/
#if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
static struct file_system_type ext2_fs_type = {
.owner = THIS_MODULE,
.name = "ext2",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext2");
MODULE_ALIAS("ext2");
#define IS_EXT2_SB(sb) ((sb)->s_bdev->bd_holder == &ext2_fs_type)
#else
#define IS_EXT2_SB(sb) (0)
#endif
static struct file_system_type ext3_fs_type = {
.owner = THIS_MODULE,
.name = "ext3",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext3");
MODULE_ALIAS("ext3");
#define IS_EXT3_SB(sb) ((sb)->s_bdev->bd_holder == &ext3_fs_type)
static int ext4_verify_csum_type(struct super_block *sb,
struct ext4_super_block *es)
{
if (!ext4_has_feature_metadata_csum(sb))
return 1;
return es->s_checksum_type == EXT4_CRC32C_CHKSUM;
}
static __le32 ext4_superblock_csum(struct super_block *sb,
struct ext4_super_block *es)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int offset = offsetof(struct ext4_super_block, s_checksum);
__u32 csum;
csum = ext4_chksum(sbi, ~0, (char *)es, offset);
return cpu_to_le32(csum);
}
static int ext4_superblock_csum_verify(struct super_block *sb,
struct ext4_super_block *es)
{
if (!ext4_has_metadata_csum(sb))
return 1;
return es->s_checksum == ext4_superblock_csum(sb, es);
}
void ext4_superblock_csum_set(struct super_block *sb)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
if (!ext4_has_metadata_csum(sb))
return;
es->s_checksum = ext4_superblock_csum(sb, es);
}
void *ext4_kvmalloc(size_t size, gfp_t flags)
{
void *ret;
ret = kmalloc(size, flags | __GFP_NOWARN);
if (!ret)
ret = __vmalloc(size, flags, PAGE_KERNEL);
return ret;
}
void *ext4_kvzalloc(size_t size, gfp_t flags)
{
void *ret;
ret = kzalloc(size, flags | __GFP_NOWARN);
if (!ret)
ret = __vmalloc(size, flags | __GFP_ZERO, PAGE_KERNEL);
return ret;
}
ext4_fsblk_t ext4_block_bitmap(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_block_bitmap_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0);
}
ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_inode_bitmap_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0);
}
ext4_fsblk_t ext4_inode_table(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_inode_table_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0);
}
__u32 ext4_free_group_clusters(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_free_blocks_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0);
}
__u32 ext4_free_inodes_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_free_inodes_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_free_inodes_count_hi) << 16 : 0);
}
__u32 ext4_used_dirs_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_used_dirs_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0);
}
__u32 ext4_itable_unused_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_itable_unused_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0);
}
void ext4_block_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_block_bitmap_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32);
}
void ext4_inode_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_inode_bitmap_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32);
}
void ext4_inode_table_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_inode_table_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_inode_table_hi = cpu_to_le32(blk >> 32);
}
void ext4_free_group_clusters_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_free_blocks_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16);
}
void ext4_free_inodes_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_free_inodes_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_free_inodes_count_hi = cpu_to_le16(count >> 16);
}
void ext4_used_dirs_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_used_dirs_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16);
}
void ext4_itable_unused_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_itable_unused_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_itable_unused_hi = cpu_to_le16(count >> 16);
}
static void __save_error_info(struct super_block *sb, const char *func,
unsigned int line)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
if (bdev_read_only(sb->s_bdev))
return;
es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
es->s_last_error_time = cpu_to_le32(get_seconds());
strncpy(es->s_last_error_func, func, sizeof(es->s_last_error_func));
es->s_last_error_line = cpu_to_le32(line);
if (!es->s_first_error_time) {
es->s_first_error_time = es->s_last_error_time;
strncpy(es->s_first_error_func, func,
sizeof(es->s_first_error_func));
es->s_first_error_line = cpu_to_le32(line);
es->s_first_error_ino = es->s_last_error_ino;
es->s_first_error_block = es->s_last_error_block;
}
/*
* Start the daily error reporting function if it hasn't been
* started already
*/
if (!es->s_error_count)
mod_timer(&EXT4_SB(sb)->s_err_report, jiffies + 24*60*60*HZ);
le32_add_cpu(&es->s_error_count, 1);
}
static void save_error_info(struct super_block *sb, const char *func,
unsigned int line)
{
__save_error_info(sb, func, line);
ext4_commit_super(sb, 1);
}
/*
* The del_gendisk() function uninitializes the disk-specific data
* structures, including the bdi structure, without telling anyone
* else. Once this happens, any attempt to call mark_buffer_dirty()
* (for example, by ext4_commit_super), will cause a kernel OOPS.
* This is a kludge to prevent these oops until we can put in a proper
* hook in del_gendisk() to inform the VFS and file system layers.
*/
static int block_device_ejected(struct super_block *sb)
{
struct inode *bd_inode = sb->s_bdev->bd_inode;
struct backing_dev_info *bdi = inode_to_bdi(bd_inode);
return bdi->dev == NULL;
}
static void ext4_journal_commit_callback(journal_t *journal, transaction_t *txn)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
int error = is_journal_aborted(journal);
struct ext4_journal_cb_entry *jce;
BUG_ON(txn->t_state == T_FINISHED);
spin_lock(&sbi->s_md_lock);
while (!list_empty(&txn->t_private_list)) {
jce = list_entry(txn->t_private_list.next,
struct ext4_journal_cb_entry, jce_list);
list_del_init(&jce->jce_list);
spin_unlock(&sbi->s_md_lock);
jce->jce_func(sb, jce, error);
spin_lock(&sbi->s_md_lock);
}
spin_unlock(&sbi->s_md_lock);
}
/* Deal with the reporting of failure conditions on a filesystem such as
* inconsistencies detected or read IO failures.
*
* On ext2, we can store the error state of the filesystem in the
* superblock. That is not possible on ext4, because we may have other
* write ordering constraints on the superblock which prevent us from
* writing it out straight away; and given that the journal is about to
* be aborted, we can't rely on the current, or future, transactions to
* write out the superblock safely.
*
* We'll just use the jbd2_journal_abort() error code to record an error in
* the journal instead. On recovery, the journal will complain about
* that error until we've noted it down and cleared it.
*/
static void ext4_handle_error(struct super_block *sb)
{
if (sb->s_flags & MS_RDONLY)
return;
if (!test_opt(sb, ERRORS_CONT)) {
journal_t *journal = EXT4_SB(sb)->s_journal;
EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
if (journal)
jbd2_journal_abort(journal, -EIO);
}
if (test_opt(sb, ERRORS_RO)) {
ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
/*
* Make sure updated value of ->s_mount_flags will be visible
* before ->s_flags update
*/
smp_wmb();
sb->s_flags |= MS_RDONLY;
}
if (test_opt(sb, ERRORS_PANIC)) {
if (EXT4_SB(sb)->s_journal &&
!(EXT4_SB(sb)->s_journal->j_flags & JBD2_REC_ERR))
return;
panic("EXT4-fs (device %s): panic forced after error\n",
sb->s_id);
}
}
#define ext4_error_ratelimit(sb) \
___ratelimit(&(EXT4_SB(sb)->s_err_ratelimit_state), \
"EXT4-fs error")
void __ext4_error(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (ext4_error_ratelimit(sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: comm %s: %pV\n",
sb->s_id, function, line, current->comm, &vaf);
va_end(args);
}
save_error_info(sb, function, line);
ext4_handle_error(sb);
}
void __ext4_error_inode(struct inode *inode, const char *function,
unsigned int line, ext4_fsblk_t block,
const char *fmt, ...)
{
va_list args;
struct va_format vaf;
struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
es->s_last_error_ino = cpu_to_le32(inode->i_ino);
es->s_last_error_block = cpu_to_le64(block);
if (ext4_error_ratelimit(inode->i_sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (block)
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
"inode #%lu: block %llu: comm %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
block, current->comm, &vaf);
else
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
"inode #%lu: comm %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
current->comm, &vaf);
va_end(args);
}
save_error_info(inode->i_sb, function, line);
ext4_handle_error(inode->i_sb);
}
void __ext4_error_file(struct file *file, const char *function,
unsigned int line, ext4_fsblk_t block,
const char *fmt, ...)
{
va_list args;
struct va_format vaf;
struct ext4_super_block *es;
struct inode *inode = file_inode(file);
char pathname[80], *path;
es = EXT4_SB(inode->i_sb)->s_es;
es->s_last_error_ino = cpu_to_le32(inode->i_ino);
if (ext4_error_ratelimit(inode->i_sb)) {
path = file_path(file, pathname, sizeof(pathname));
if (IS_ERR(path))
path = "(unknown)";
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (block)
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: inode #%lu: "
"block %llu: comm %s: path %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
block, current->comm, path, &vaf);
else
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: inode #%lu: "
"comm %s: path %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
current->comm, path, &vaf);
va_end(args);
}
save_error_info(inode->i_sb, function, line);
ext4_handle_error(inode->i_sb);
}
const char *ext4_decode_error(struct super_block *sb, int errno,
char nbuf[16])
{
char *errstr = NULL;
switch (errno) {
case -EFSCORRUPTED:
errstr = "Corrupt filesystem";
break;
case -EFSBADCRC:
errstr = "Filesystem failed CRC";
break;
case -EIO:
errstr = "IO failure";
break;
case -ENOMEM:
errstr = "Out of memory";
break;
case -EROFS:
if (!sb || (EXT4_SB(sb)->s_journal &&
EXT4_SB(sb)->s_journal->j_flags & JBD2_ABORT))
errstr = "Journal has aborted";
else
errstr = "Readonly filesystem";
break;
default:
/* If the caller passed in an extra buffer for unknown
* errors, textualise them now. Else we just return
* NULL. */
if (nbuf) {
/* Check for truncated error codes... */
if (snprintf(nbuf, 16, "error %d", -errno) >= 0)
errstr = nbuf;
}
break;
}
return errstr;
}
/* __ext4_std_error decodes expected errors from journaling functions
* automatically and invokes the appropriate error response. */
void __ext4_std_error(struct super_block *sb, const char *function,
unsigned int line, int errno)
{
char nbuf[16];
const char *errstr;
/* Special case: if the error is EROFS, and we're not already
* inside a transaction, then there's really no point in logging
* an error. */
if (errno == -EROFS && journal_current_handle() == NULL &&
(sb->s_flags & MS_RDONLY))
return;
if (ext4_error_ratelimit(sb)) {
errstr = ext4_decode_error(sb, errno, nbuf);
printk(KERN_CRIT "EXT4-fs error (device %s) in %s:%d: %s\n",
sb->s_id, function, line, errstr);
}
save_error_info(sb, function, line);
ext4_handle_error(sb);
}
/*
* ext4_abort is a much stronger failure handler than ext4_error. The
* abort function may be used to deal with unrecoverable failures such
* as journal IO errors or ENOMEM at a critical moment in log management.
*
* We unconditionally force the filesystem into an ABORT|READONLY state,
* unless the error response on the fs has been set to panic in which
* case we take the easy way out and panic immediately.
*/
void __ext4_abort(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
va_list args;
save_error_info(sb, function, line);
va_start(args, fmt);
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: ", sb->s_id,
function, line);
vprintk(fmt, args);
printk("\n");
va_end(args);
if ((sb->s_flags & MS_RDONLY) == 0) {
ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
/*
* Make sure updated value of ->s_mount_flags will be visible
* before ->s_flags update
*/
smp_wmb();
sb->s_flags |= MS_RDONLY;
if (EXT4_SB(sb)->s_journal)
jbd2_journal_abort(EXT4_SB(sb)->s_journal, -EIO);
save_error_info(sb, function, line);
}
if (test_opt(sb, ERRORS_PANIC)) {
if (EXT4_SB(sb)->s_journal &&
!(EXT4_SB(sb)->s_journal->j_flags & JBD2_REC_ERR))
return;
panic("EXT4-fs panic from previous error\n");
}
}
void __ext4_msg(struct super_block *sb,
const char *prefix, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (!___ratelimit(&(EXT4_SB(sb)->s_msg_ratelimit_state), "EXT4-fs"))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk("%sEXT4-fs (%s): %pV\n", prefix, sb->s_id, &vaf);
va_end(args);
}
#define ext4_warning_ratelimit(sb) \
___ratelimit(&(EXT4_SB(sb)->s_warning_ratelimit_state), \
"EXT4-fs warning")
void __ext4_warning(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (!ext4_warning_ratelimit(sb))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: %pV\n",
sb->s_id, function, line, &vaf);
va_end(args);
}
void __ext4_warning_inode(const struct inode *inode, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (!ext4_warning_ratelimit(inode->i_sb))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: "
"inode #%lu: comm %s: %pV\n", inode->i_sb->s_id,
function, line, inode->i_ino, current->comm, &vaf);
va_end(args);
}
void __ext4_grp_locked_error(const char *function, unsigned int line,
struct super_block *sb, ext4_group_t grp,
unsigned long ino, ext4_fsblk_t block,
const char *fmt, ...)
__releases(bitlock)
__acquires(bitlock)
{
struct va_format vaf;
va_list args;
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
es->s_last_error_ino = cpu_to_le32(ino);
es->s_last_error_block = cpu_to_le64(block);
__save_error_info(sb, function, line);
if (ext4_error_ratelimit(sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: group %u, ",
sb->s_id, function, line, grp);
if (ino)
printk(KERN_CONT "inode %lu: ", ino);
if (block)
printk(KERN_CONT "block %llu:",
(unsigned long long) block);
printk(KERN_CONT "%pV\n", &vaf);
va_end(args);
}
if (test_opt(sb, ERRORS_CONT)) {
ext4_commit_super(sb, 0);
return;
}
ext4_unlock_group(sb, grp);
ext4_handle_error(sb);
/*
* We only get here in the ERRORS_RO case; relocking the group
* may be dangerous, but nothing bad will happen since the
* filesystem will have already been marked read/only and the
* journal has been aborted. We return 1 as a hint to callers
* who might what to use the return value from
* ext4_grp_locked_error() to distinguish between the
* ERRORS_CONT and ERRORS_RO case, and perhaps return more
* aggressively from the ext4 function in question, with a
* more appropriate error code.
*/
ext4_lock_group(sb, grp);
return;
}
void ext4_update_dynamic_rev(struct super_block *sb)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
if (le32_to_cpu(es->s_rev_level) > EXT4_GOOD_OLD_REV)
return;
ext4_warning(sb,
"updating to rev %d because of new feature flag, "
"running e2fsck is recommended",
EXT4_DYNAMIC_REV);
es->s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO);
es->s_inode_size = cpu_to_le16(EXT4_GOOD_OLD_INODE_SIZE);
es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV);
/* leave es->s_feature_*compat flags alone */
/* es->s_uuid will be set by e2fsck if empty */
/*
* The rest of the superblock fields should be zero, and if not it
* means they are likely already in use, so leave them alone. We
* can leave it up to e2fsck to clean up any inconsistencies there.
*/
}
/*
* Open the external journal device
*/
static struct block_device *ext4_blkdev_get(dev_t dev, struct super_block *sb)
{
struct block_device *bdev;
char b[BDEVNAME_SIZE];
bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb);
if (IS_ERR(bdev))
goto fail;
return bdev;
fail:
ext4_msg(sb, KERN_ERR, "failed to open journal device %s: %ld",
__bdevname(dev, b), PTR_ERR(bdev));
return NULL;
}
/*
* Release the journal device
*/
static void ext4_blkdev_put(struct block_device *bdev)
{
blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
}
static void ext4_blkdev_remove(struct ext4_sb_info *sbi)
{
struct block_device *bdev;
bdev = sbi->journal_bdev;
if (bdev) {
ext4_blkdev_put(bdev);
sbi->journal_bdev = NULL;
}
}
static inline struct inode *orphan_list_entry(struct list_head *l)
{
return &list_entry(l, struct ext4_inode_info, i_orphan)->vfs_inode;
}
static void dump_orphan_list(struct super_block *sb, struct ext4_sb_info *sbi)
{
struct list_head *l;
ext4_msg(sb, KERN_ERR, "sb orphan head is %d",
le32_to_cpu(sbi->s_es->s_last_orphan));
printk(KERN_ERR "sb_info orphan list:\n");
list_for_each(l, &sbi->s_orphan) {
struct inode *inode = orphan_list_entry(l);
printk(KERN_ERR " "
"inode %s:%lu at %p: mode %o, nlink %d, next %d\n",
inode->i_sb->s_id, inode->i_ino, inode,
inode->i_mode, inode->i_nlink,
NEXT_ORPHAN(inode));
}
}
static void ext4_put_super(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int i, err;
ext4_unregister_li_request(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
flush_workqueue(sbi->rsv_conversion_wq);
destroy_workqueue(sbi->rsv_conversion_wq);
if (sbi->s_journal) {
err = jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
if (err < 0)
ext4_abort(sb, "Couldn't clean up the journal");
}
ext4_unregister_sysfs(sb);
ext4_es_unregister_shrinker(sbi);
del_timer_sync(&sbi->s_err_report);
ext4_release_system_zone(sb);
ext4_mb_release(sb);
ext4_ext_release(sb);
if (!(sb->s_flags & MS_RDONLY)) {
ext4_clear_feature_journal_needs_recovery(sb);
es->s_state = cpu_to_le16(sbi->s_mount_state);
}
if (!(sb->s_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
for (i = 0; i < sbi->s_gdb_count; i++)
brelse(sbi->s_group_desc[i]);
kvfree(sbi->s_group_desc);
kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
brelse(sbi->s_sbh);
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
/* Debugging code just in case the in-memory inode orphan list
* isn't empty. The on-disk one can be non-empty if we've
* detected an error and taken the fs readonly, but the
* in-memory list had better be clean by this point. */
if (!list_empty(&sbi->s_orphan))
dump_orphan_list(sb, sbi);
J_ASSERT(list_empty(&sbi->s_orphan));
sync_blockdev(sb->s_bdev);
invalidate_bdev(sb->s_bdev);
if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) {
/*
* Invalidate the journal device's buffers. We don't want them
* floating about in memory - the physical journal device may
* hotswapped, and it breaks the `ro-after' testing code.
*/
sync_blockdev(sbi->journal_bdev);
invalidate_bdev(sbi->journal_bdev);
ext4_blkdev_remove(sbi);
}
if (sbi->s_mb_cache) {
ext4_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
sb->s_fs_info = NULL;
/*
* Now that we are completely done shutting down the
* superblock, we need to actually destroy the kobject.
*/
kobject_put(&sbi->s_kobj);
wait_for_completion(&sbi->s_kobj_unregister);
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
static struct kmem_cache *ext4_inode_cachep;
/*
* Called inside transaction, so use GFP_NOFS
*/
static struct inode *ext4_alloc_inode(struct super_block *sb)
{
struct ext4_inode_info *ei;
ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS);
if (!ei)
return NULL;
ei->vfs_inode.i_version = 1;
spin_lock_init(&ei->i_raw_lock);
INIT_LIST_HEAD(&ei->i_prealloc_list);
spin_lock_init(&ei->i_prealloc_lock);
ext4_es_init_tree(&ei->i_es_tree);
rwlock_init(&ei->i_es_lock);
INIT_LIST_HEAD(&ei->i_es_list);
ei->i_es_all_nr = 0;
ei->i_es_shk_nr = 0;
ei->i_es_shrink_lblk = 0;
ei->i_reserved_data_blocks = 0;
ei->i_reserved_meta_blocks = 0;
ei->i_allocated_meta_blocks = 0;
ei->i_da_metadata_calc_len = 0;
ei->i_da_metadata_calc_last_lblock = 0;
spin_lock_init(&(ei->i_block_reservation_lock));
#ifdef CONFIG_QUOTA
ei->i_reserved_quota = 0;
memset(&ei->i_dquot, 0, sizeof(ei->i_dquot));
#endif
ei->jinode = NULL;
INIT_LIST_HEAD(&ei->i_rsv_conversion_list);
spin_lock_init(&ei->i_completed_io_lock);
ei->i_sync_tid = 0;
ei->i_datasync_tid = 0;
atomic_set(&ei->i_ioend_count, 0);
atomic_set(&ei->i_unwritten, 0);
INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work);
#ifdef CONFIG_EXT4_FS_ENCRYPTION
ei->i_crypt_info = NULL;
#endif
return &ei->vfs_inode;
}
static int ext4_drop_inode(struct inode *inode)
{
int drop = generic_drop_inode(inode);
trace_ext4_drop_inode(inode, drop);
return drop;
}
static void ext4_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(ext4_inode_cachep, EXT4_I(inode));
}
static void ext4_destroy_inode(struct inode *inode)
{
if (!list_empty(&(EXT4_I(inode)->i_orphan))) {
ext4_msg(inode->i_sb, KERN_ERR,
"Inode %lu (%p): orphan list check failed!",
inode->i_ino, EXT4_I(inode));
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 4,
EXT4_I(inode), sizeof(struct ext4_inode_info),
true);
dump_stack();
}
call_rcu(&inode->i_rcu, ext4_i_callback);
}
static void init_once(void *foo)
{
struct ext4_inode_info *ei = (struct ext4_inode_info *) foo;
INIT_LIST_HEAD(&ei->i_orphan);
init_rwsem(&ei->xattr_sem);
init_rwsem(&ei->i_data_sem);
init_rwsem(&ei->i_mmap_sem);
inode_init_once(&ei->vfs_inode);
}
static int __init init_inodecache(void)
{
ext4_inode_cachep = kmem_cache_create("ext4_inode_cache",
sizeof(struct ext4_inode_info),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD|SLAB_ACCOUNT),
init_once);
if (ext4_inode_cachep == NULL)
return -ENOMEM;
return 0;
}
static void destroy_inodecache(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
kmem_cache_destroy(ext4_inode_cachep);
}
void ext4_clear_inode(struct inode *inode)
{
invalidate_inode_buffers(inode);
clear_inode(inode);
dquot_drop(inode);
ext4_discard_preallocations(inode);
ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS);
if (EXT4_I(inode)->jinode) {
jbd2_journal_release_jbd_inode(EXT4_JOURNAL(inode),
EXT4_I(inode)->jinode);
jbd2_free_inode(EXT4_I(inode)->jinode);
EXT4_I(inode)->jinode = NULL;
}
#ifdef CONFIG_EXT4_FS_ENCRYPTION
if (EXT4_I(inode)->i_crypt_info)
ext4_free_encryption_info(inode, EXT4_I(inode)->i_crypt_info);
#endif
}
static struct inode *ext4_nfs_get_inode(struct super_block *sb,
u64 ino, u32 generation)
{
struct inode *inode;
if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
return ERR_PTR(-ESTALE);
if (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
return ERR_PTR(-ESTALE);
/* iget isn't really right if the inode is currently unallocated!!
*
* ext4_read_inode will return a bad_inode if the inode had been
* deleted, so we should be safe.
*
* Currently we don't know the generation for parent directory, so
* a generation of 0 means "accept any"
*/
inode = ext4_iget_normal(sb, ino);
if (IS_ERR(inode))
return ERR_CAST(inode);
if (generation && inode->i_generation != generation) {
iput(inode);
return ERR_PTR(-ESTALE);
}
return inode;
}
static struct dentry *ext4_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
ext4_nfs_get_inode);
}
static struct dentry *ext4_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_parent(sb, fid, fh_len, fh_type,
ext4_nfs_get_inode);
}
/*
* Try to release metadata pages (indirect blocks, directories) which are
* mapped via the block device. Since these pages could have journal heads
* which would prevent try_to_free_buffers() from freeing them, we must use
* jbd2 layer's try_to_free_buffers() function to release them.
*/
static int bdev_try_to_free_page(struct super_block *sb, struct page *page,
gfp_t wait)
{
journal_t *journal = EXT4_SB(sb)->s_journal;
WARN_ON(PageChecked(page));
if (!page_has_buffers(page))
return 0;
if (journal)
return jbd2_journal_try_to_free_buffers(journal, page,
wait & ~__GFP_DIRECT_RECLAIM);
return try_to_free_buffers(page);
}
#ifdef CONFIG_QUOTA
static char *quotatypes[] = INITQFNAMES;
#define QTYPE2NAME(t) (quotatypes[t])
static int ext4_write_dquot(struct dquot *dquot);
static int ext4_acquire_dquot(struct dquot *dquot);
static int ext4_release_dquot(struct dquot *dquot);
static int ext4_mark_dquot_dirty(struct dquot *dquot);
static int ext4_write_info(struct super_block *sb, int type);
static int ext4_quota_on(struct super_block *sb, int type, int format_id,
struct path *path);
static int ext4_quota_off(struct super_block *sb, int type);
static int ext4_quota_on_mount(struct super_block *sb, int type);
static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off);
static ssize_t ext4_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off);
static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
unsigned int flags);
static int ext4_enable_quotas(struct super_block *sb);
static struct dquot **ext4_get_dquots(struct inode *inode)
{
return EXT4_I(inode)->i_dquot;
}
static const struct dquot_operations ext4_quota_operations = {
.get_reserved_space = ext4_get_reserved_space,
.write_dquot = ext4_write_dquot,
.acquire_dquot = ext4_acquire_dquot,
.release_dquot = ext4_release_dquot,
.mark_dirty = ext4_mark_dquot_dirty,
.write_info = ext4_write_info,
.alloc_dquot = dquot_alloc,
.destroy_dquot = dquot_destroy,
.get_projid = ext4_get_projid,
};
static const struct quotactl_ops ext4_qctl_operations = {
.quota_on = ext4_quota_on,
.quota_off = ext4_quota_off,
.quota_sync = dquot_quota_sync,
.get_state = dquot_get_state,
.set_info = dquot_set_dqinfo,
.get_dqblk = dquot_get_dqblk,
.set_dqblk = dquot_set_dqblk
};
#endif
static const struct super_operations ext4_sops = {
.alloc_inode = ext4_alloc_inode,
.destroy_inode = ext4_destroy_inode,
.write_inode = ext4_write_inode,
.dirty_inode = ext4_dirty_inode,
.drop_inode = ext4_drop_inode,
.evict_inode = ext4_evict_inode,
.put_super = ext4_put_super,
.sync_fs = ext4_sync_fs,
.freeze_fs = ext4_freeze,
.unfreeze_fs = ext4_unfreeze,
.statfs = ext4_statfs,
.remount_fs = ext4_remount,
.show_options = ext4_show_options,
#ifdef CONFIG_QUOTA
.quota_read = ext4_quota_read,
.quota_write = ext4_quota_write,
.get_dquots = ext4_get_dquots,
#endif
.bdev_try_to_free_page = bdev_try_to_free_page,
};
static const struct export_operations ext4_export_ops = {
.fh_to_dentry = ext4_fh_to_dentry,
.fh_to_parent = ext4_fh_to_parent,
.get_parent = ext4_get_parent,
};
enum {
Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid,
Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic, Opt_err_ro,
Opt_nouid32, Opt_debug, Opt_removed,
Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl,
Opt_auto_da_alloc, Opt_noauto_da_alloc, Opt_noload,
Opt_commit, Opt_min_batch_time, Opt_max_batch_time, Opt_journal_dev,
Opt_journal_path, Opt_journal_checksum, Opt_journal_async_commit,
Opt_abort, Opt_data_journal, Opt_data_ordered, Opt_data_writeback,
Opt_data_err_abort, Opt_data_err_ignore, Opt_test_dummy_encryption,
Opt_usrjquota, Opt_grpjquota, Opt_offusrjquota, Opt_offgrpjquota,
Opt_jqfmt_vfsold, Opt_jqfmt_vfsv0, Opt_jqfmt_vfsv1, Opt_quota,
Opt_noquota, Opt_barrier, Opt_nobarrier, Opt_err,
Opt_usrquota, Opt_grpquota, Opt_i_version, Opt_dax,
Opt_stripe, Opt_delalloc, Opt_nodelalloc, Opt_mblk_io_submit,
Opt_lazytime, Opt_nolazytime,
Opt_nomblk_io_submit, Opt_block_validity, Opt_noblock_validity,
Opt_inode_readahead_blks, Opt_journal_ioprio,
Opt_dioread_nolock, Opt_dioread_lock,
Opt_discard, Opt_nodiscard, Opt_init_itable, Opt_noinit_itable,
Opt_max_dir_size_kb, Opt_nojournal_checksum,
};
static const match_table_t tokens = {
{Opt_bsd_df, "bsddf"},
{Opt_minix_df, "minixdf"},
{Opt_grpid, "grpid"},
{Opt_grpid, "bsdgroups"},
{Opt_nogrpid, "nogrpid"},
{Opt_nogrpid, "sysvgroups"},
{Opt_resgid, "resgid=%u"},
{Opt_resuid, "resuid=%u"},
{Opt_sb, "sb=%u"},
{Opt_err_cont, "errors=continue"},
{Opt_err_panic, "errors=panic"},
{Opt_err_ro, "errors=remount-ro"},
{Opt_nouid32, "nouid32"},
{Opt_debug, "debug"},
{Opt_removed, "oldalloc"},
{Opt_removed, "orlov"},
{Opt_user_xattr, "user_xattr"},
{Opt_nouser_xattr, "nouser_xattr"},
{Opt_acl, "acl"},
{Opt_noacl, "noacl"},
{Opt_noload, "norecovery"},
{Opt_noload, "noload"},
{Opt_removed, "nobh"},
{Opt_removed, "bh"},
{Opt_commit, "commit=%u"},
{Opt_min_batch_time, "min_batch_time=%u"},
{Opt_max_batch_time, "max_batch_time=%u"},
{Opt_journal_dev, "journal_dev=%u"},
{Opt_journal_path, "journal_path=%s"},
{Opt_journal_checksum, "journal_checksum"},
{Opt_nojournal_checksum, "nojournal_checksum"},
{Opt_journal_async_commit, "journal_async_commit"},
{Opt_abort, "abort"},
{Opt_data_journal, "data=journal"},
{Opt_data_ordered, "data=ordered"},
{Opt_data_writeback, "data=writeback"},
{Opt_data_err_abort, "data_err=abort"},
{Opt_data_err_ignore, "data_err=ignore"},
{Opt_offusrjquota, "usrjquota="},
{Opt_usrjquota, "usrjquota=%s"},
{Opt_offgrpjquota, "grpjquota="},
{Opt_grpjquota, "grpjquota=%s"},
{Opt_jqfmt_vfsold, "jqfmt=vfsold"},
{Opt_jqfmt_vfsv0, "jqfmt=vfsv0"},
{Opt_jqfmt_vfsv1, "jqfmt=vfsv1"},
{Opt_grpquota, "grpquota"},
{Opt_noquota, "noquota"},
{Opt_quota, "quota"},
{Opt_usrquota, "usrquota"},
{Opt_barrier, "barrier=%u"},
{Opt_barrier, "barrier"},
{Opt_nobarrier, "nobarrier"},
{Opt_i_version, "i_version"},
{Opt_dax, "dax"},
{Opt_stripe, "stripe=%u"},
{Opt_delalloc, "delalloc"},
{Opt_lazytime, "lazytime"},
{Opt_nolazytime, "nolazytime"},
{Opt_nodelalloc, "nodelalloc"},
{Opt_removed, "mblk_io_submit"},
{Opt_removed, "nomblk_io_submit"},
{Opt_block_validity, "block_validity"},
{Opt_noblock_validity, "noblock_validity"},
{Opt_inode_readahead_blks, "inode_readahead_blks=%u"},
{Opt_journal_ioprio, "journal_ioprio=%u"},
{Opt_auto_da_alloc, "auto_da_alloc=%u"},
{Opt_auto_da_alloc, "auto_da_alloc"},
{Opt_noauto_da_alloc, "noauto_da_alloc"},
{Opt_dioread_nolock, "dioread_nolock"},
{Opt_dioread_lock, "dioread_lock"},
{Opt_discard, "discard"},
{Opt_nodiscard, "nodiscard"},
{Opt_init_itable, "init_itable=%u"},
{Opt_init_itable, "init_itable"},
{Opt_noinit_itable, "noinit_itable"},
{Opt_max_dir_size_kb, "max_dir_size_kb=%u"},
{Opt_test_dummy_encryption, "test_dummy_encryption"},
{Opt_removed, "check=none"}, /* mount option from ext2/3 */
{Opt_removed, "nocheck"}, /* mount option from ext2/3 */
{Opt_removed, "reservation"}, /* mount option from ext2/3 */
{Opt_removed, "noreservation"}, /* mount option from ext2/3 */
{Opt_removed, "journal=%u"}, /* mount option from ext2/3 */
{Opt_err, NULL},
};
static ext4_fsblk_t get_sb_block(void **data)
{
ext4_fsblk_t sb_block;
char *options = (char *) *data;
if (!options || strncmp(options, "sb=", 3) != 0)
return 1; /* Default location */
options += 3;
/* TODO: use simple_strtoll with >32bit ext4 */
sb_block = simple_strtoul(options, &options, 0);
if (*options && *options != ',') {
printk(KERN_ERR "EXT4-fs: Invalid sb specification: %s\n",
(char *) *data);
return 1;
}
if (*options == ',')
options++;
*data = (void *) options;
return sb_block;
}
#define DEFAULT_JOURNAL_IOPRIO (IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 3))
static char deprecated_msg[] = "Mount option \"%s\" will be removed by %s\n"
"Contact linux-ext4@vger.kernel.org if you think we should keep it.\n";
#ifdef CONFIG_QUOTA
static int set_qf_name(struct super_block *sb, int qtype, substring_t *args)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
char *qname;
int ret = -1;
if (sb_any_quota_loaded(sb) &&
!sbi->s_qf_names[qtype]) {
ext4_msg(sb, KERN_ERR,
"Cannot change journaled "
"quota options when quota turned on");
return -1;
}
if (ext4_has_feature_quota(sb)) {
ext4_msg(sb, KERN_ERR, "Cannot set journaled quota options "
"when QUOTA feature is enabled");
return -1;
}
qname = match_strdup(args);
if (!qname) {
ext4_msg(sb, KERN_ERR,
"Not enough memory for storing quotafile name");
return -1;
}
if (sbi->s_qf_names[qtype]) {
if (strcmp(sbi->s_qf_names[qtype], qname) == 0)
ret = 1;
else
ext4_msg(sb, KERN_ERR,
"%s quota file already specified",
QTYPE2NAME(qtype));
goto errout;
}
if (strchr(qname, '/')) {
ext4_msg(sb, KERN_ERR,
"quotafile must be on filesystem root");
goto errout;
}
sbi->s_qf_names[qtype] = qname;
set_opt(sb, QUOTA);
return 1;
errout:
kfree(qname);
return ret;
}
static int clear_qf_name(struct super_block *sb, int qtype)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (sb_any_quota_loaded(sb) &&
sbi->s_qf_names[qtype]) {
ext4_msg(sb, KERN_ERR, "Cannot change journaled quota options"
" when quota turned on");
return -1;
}
kfree(sbi->s_qf_names[qtype]);
sbi->s_qf_names[qtype] = NULL;
return 1;
}
#endif
#define MOPT_SET 0x0001
#define MOPT_CLEAR 0x0002
#define MOPT_NOSUPPORT 0x0004
#define MOPT_EXPLICIT 0x0008
#define MOPT_CLEAR_ERR 0x0010
#define MOPT_GTE0 0x0020
#ifdef CONFIG_QUOTA
#define MOPT_Q 0
#define MOPT_QFMT 0x0040
#else
#define MOPT_Q MOPT_NOSUPPORT
#define MOPT_QFMT MOPT_NOSUPPORT
#endif
#define MOPT_DATAJ 0x0080
#define MOPT_NO_EXT2 0x0100
#define MOPT_NO_EXT3 0x0200
#define MOPT_EXT4_ONLY (MOPT_NO_EXT2 | MOPT_NO_EXT3)
#define MOPT_STRING 0x0400
static const struct mount_opts {
int token;
int mount_opt;
int flags;
} ext4_mount_opts[] = {
{Opt_minix_df, EXT4_MOUNT_MINIX_DF, MOPT_SET},
{Opt_bsd_df, EXT4_MOUNT_MINIX_DF, MOPT_CLEAR},
{Opt_grpid, EXT4_MOUNT_GRPID, MOPT_SET},
{Opt_nogrpid, EXT4_MOUNT_GRPID, MOPT_CLEAR},
{Opt_block_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_SET},
{Opt_noblock_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_CLEAR},
{Opt_dioread_nolock, EXT4_MOUNT_DIOREAD_NOLOCK,
MOPT_EXT4_ONLY | MOPT_SET},
{Opt_dioread_lock, EXT4_MOUNT_DIOREAD_NOLOCK,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_discard, EXT4_MOUNT_DISCARD, MOPT_SET},
{Opt_nodiscard, EXT4_MOUNT_DISCARD, MOPT_CLEAR},
{Opt_delalloc, EXT4_MOUNT_DELALLOC,
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_nodelalloc, EXT4_MOUNT_DELALLOC,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_nojournal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_journal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_journal_async_commit, (EXT4_MOUNT_JOURNAL_ASYNC_COMMIT |
EXT4_MOUNT_JOURNAL_CHECKSUM),
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_noload, EXT4_MOUNT_NOLOAD, MOPT_NO_EXT2 | MOPT_SET},
{Opt_err_panic, EXT4_MOUNT_ERRORS_PANIC, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_err_ro, EXT4_MOUNT_ERRORS_RO, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_err_cont, EXT4_MOUNT_ERRORS_CONT, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_data_err_abort, EXT4_MOUNT_DATA_ERR_ABORT,
MOPT_NO_EXT2 | MOPT_SET},
{Opt_data_err_ignore, EXT4_MOUNT_DATA_ERR_ABORT,
MOPT_NO_EXT2 | MOPT_CLEAR},
{Opt_barrier, EXT4_MOUNT_BARRIER, MOPT_SET},
{Opt_nobarrier, EXT4_MOUNT_BARRIER, MOPT_CLEAR},
{Opt_noauto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_SET},
{Opt_auto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_CLEAR},
{Opt_noinit_itable, EXT4_MOUNT_INIT_INODE_TABLE, MOPT_CLEAR},
{Opt_commit, 0, MOPT_GTE0},
{Opt_max_batch_time, 0, MOPT_GTE0},
{Opt_min_batch_time, 0, MOPT_GTE0},
{Opt_inode_readahead_blks, 0, MOPT_GTE0},
{Opt_init_itable, 0, MOPT_GTE0},
{Opt_dax, EXT4_MOUNT_DAX, MOPT_SET},
{Opt_stripe, 0, MOPT_GTE0},
{Opt_resuid, 0, MOPT_GTE0},
{Opt_resgid, 0, MOPT_GTE0},
{Opt_journal_dev, 0, MOPT_NO_EXT2 | MOPT_GTE0},
{Opt_journal_path, 0, MOPT_NO_EXT2 | MOPT_STRING},
{Opt_journal_ioprio, 0, MOPT_NO_EXT2 | MOPT_GTE0},
{Opt_data_journal, EXT4_MOUNT_JOURNAL_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_data_ordered, EXT4_MOUNT_ORDERED_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_data_writeback, EXT4_MOUNT_WRITEBACK_DATA,
MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_user_xattr, EXT4_MOUNT_XATTR_USER, MOPT_SET},
{Opt_nouser_xattr, EXT4_MOUNT_XATTR_USER, MOPT_CLEAR},
#ifdef CONFIG_EXT4_FS_POSIX_ACL
{Opt_acl, EXT4_MOUNT_POSIX_ACL, MOPT_SET},
{Opt_noacl, EXT4_MOUNT_POSIX_ACL, MOPT_CLEAR},
#else
{Opt_acl, 0, MOPT_NOSUPPORT},
{Opt_noacl, 0, MOPT_NOSUPPORT},
#endif
{Opt_nouid32, EXT4_MOUNT_NO_UID32, MOPT_SET},
{Opt_debug, EXT4_MOUNT_DEBUG, MOPT_SET},
{Opt_quota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA, MOPT_SET | MOPT_Q},
{Opt_usrquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA,
MOPT_SET | MOPT_Q},
{Opt_grpquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_GRPQUOTA,
MOPT_SET | MOPT_Q},
{Opt_noquota, (EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA |
EXT4_MOUNT_GRPQUOTA), MOPT_CLEAR | MOPT_Q},
{Opt_usrjquota, 0, MOPT_Q},
{Opt_grpjquota, 0, MOPT_Q},
{Opt_offusrjquota, 0, MOPT_Q},
{Opt_offgrpjquota, 0, MOPT_Q},
{Opt_jqfmt_vfsold, QFMT_VFS_OLD, MOPT_QFMT},
{Opt_jqfmt_vfsv0, QFMT_VFS_V0, MOPT_QFMT},
{Opt_jqfmt_vfsv1, QFMT_VFS_V1, MOPT_QFMT},
{Opt_max_dir_size_kb, 0, MOPT_GTE0},
{Opt_test_dummy_encryption, 0, MOPT_GTE0},
{Opt_err, 0, 0}
};
static int handle_mount_opt(struct super_block *sb, char *opt, int token,
substring_t *args, unsigned long *journal_devnum,
unsigned int *journal_ioprio, int is_remount)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
const struct mount_opts *m;
kuid_t uid;
kgid_t gid;
int arg = 0;
#ifdef CONFIG_QUOTA
if (token == Opt_usrjquota)
return set_qf_name(sb, USRQUOTA, &args[0]);
else if (token == Opt_grpjquota)
return set_qf_name(sb, GRPQUOTA, &args[0]);
else if (token == Opt_offusrjquota)
return clear_qf_name(sb, USRQUOTA);
else if (token == Opt_offgrpjquota)
return clear_qf_name(sb, GRPQUOTA);
#endif
switch (token) {
case Opt_noacl:
case Opt_nouser_xattr:
ext4_msg(sb, KERN_WARNING, deprecated_msg, opt, "3.5");
break;
case Opt_sb:
return 1; /* handled by get_sb_block() */
case Opt_removed:
ext4_msg(sb, KERN_WARNING, "Ignoring removed %s option", opt);
return 1;
case Opt_abort:
sbi->s_mount_flags |= EXT4_MF_FS_ABORTED;
return 1;
case Opt_i_version:
sb->s_flags |= MS_I_VERSION;
return 1;
case Opt_lazytime:
sb->s_flags |= MS_LAZYTIME;
return 1;
case Opt_nolazytime:
sb->s_flags &= ~MS_LAZYTIME;
return 1;
}
for (m = ext4_mount_opts; m->token != Opt_err; m++)
if (token == m->token)
break;
if (m->token == Opt_err) {
ext4_msg(sb, KERN_ERR, "Unrecognized mount option \"%s\" "
"or missing value", opt);
return -1;
}
if ((m->flags & MOPT_NO_EXT2) && IS_EXT2_SB(sb)) {
ext4_msg(sb, KERN_ERR,
"Mount option \"%s\" incompatible with ext2", opt);
return -1;
}
if ((m->flags & MOPT_NO_EXT3) && IS_EXT3_SB(sb)) {
ext4_msg(sb, KERN_ERR,
"Mount option \"%s\" incompatible with ext3", opt);
return -1;
}
if (args->from && !(m->flags & MOPT_STRING) && match_int(args, &arg))
return -1;
if (args->from && (m->flags & MOPT_GTE0) && (arg < 0))
return -1;
if (m->flags & MOPT_EXPLICIT) {
if (m->mount_opt & EXT4_MOUNT_DELALLOC) {
set_opt2(sb, EXPLICIT_DELALLOC);
} else if (m->mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) {
set_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM);
} else
return -1;
}
if (m->flags & MOPT_CLEAR_ERR)
clear_opt(sb, ERRORS_MASK);
if (token == Opt_noquota && sb_any_quota_loaded(sb)) {
ext4_msg(sb, KERN_ERR, "Cannot change quota "
"options when quota turned on");
return -1;
}
if (m->flags & MOPT_NOSUPPORT) {
ext4_msg(sb, KERN_ERR, "%s option not supported", opt);
} else if (token == Opt_commit) {
if (arg == 0)
arg = JBD2_DEFAULT_MAX_COMMIT_AGE;
sbi->s_commit_interval = HZ * arg;
} else if (token == Opt_max_batch_time) {
sbi->s_max_batch_time = arg;
} else if (token == Opt_min_batch_time) {
sbi->s_min_batch_time = arg;
} else if (token == Opt_inode_readahead_blks) {
if (arg && (arg > (1 << 30) || !is_power_of_2(arg))) {
ext4_msg(sb, KERN_ERR,
"EXT4-fs: inode_readahead_blks must be "
"0 or a power of 2 smaller than 2^31");
return -1;
}
sbi->s_inode_readahead_blks = arg;
} else if (token == Opt_init_itable) {
set_opt(sb, INIT_INODE_TABLE);
if (!args->from)
arg = EXT4_DEF_LI_WAIT_MULT;
sbi->s_li_wait_mult = arg;
} else if (token == Opt_max_dir_size_kb) {
sbi->s_max_dir_size_kb = arg;
} else if (token == Opt_stripe) {
sbi->s_stripe = arg;
} else if (token == Opt_resuid) {
uid = make_kuid(current_user_ns(), arg);
if (!uid_valid(uid)) {
ext4_msg(sb, KERN_ERR, "Invalid uid value %d", arg);
return -1;
}
sbi->s_resuid = uid;
} else if (token == Opt_resgid) {
gid = make_kgid(current_user_ns(), arg);
if (!gid_valid(gid)) {
ext4_msg(sb, KERN_ERR, "Invalid gid value %d", arg);
return -1;
}
sbi->s_resgid = gid;
} else if (token == Opt_journal_dev) {
if (is_remount) {
ext4_msg(sb, KERN_ERR,
"Cannot specify journal on remount");
return -1;
}
*journal_devnum = arg;
} else if (token == Opt_journal_path) {
char *journal_path;
struct inode *journal_inode;
struct path path;
int error;
if (is_remount) {
ext4_msg(sb, KERN_ERR,
"Cannot specify journal on remount");
return -1;
}
journal_path = match_strdup(&args[0]);
if (!journal_path) {
ext4_msg(sb, KERN_ERR, "error: could not dup "
"journal device string");
return -1;
}
error = kern_path(journal_path, LOOKUP_FOLLOW, &path);
if (error) {
ext4_msg(sb, KERN_ERR, "error: could not find "
"journal device path: error %d", error);
kfree(journal_path);
return -1;
}
journal_inode = d_inode(path.dentry);
if (!S_ISBLK(journal_inode->i_mode)) {
ext4_msg(sb, KERN_ERR, "error: journal path %s "
"is not a block device", journal_path);
path_put(&path);
kfree(journal_path);
return -1;
}
*journal_devnum = new_encode_dev(journal_inode->i_rdev);
path_put(&path);
kfree(journal_path);
} else if (token == Opt_journal_ioprio) {
if (arg > 7) {
ext4_msg(sb, KERN_ERR, "Invalid journal IO priority"
" (must be 0-7)");
return -1;
}
*journal_ioprio =
IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, arg);
} else if (token == Opt_test_dummy_encryption) {
#ifdef CONFIG_EXT4_FS_ENCRYPTION
sbi->s_mount_flags |= EXT4_MF_TEST_DUMMY_ENCRYPTION;
ext4_msg(sb, KERN_WARNING,
"Test dummy encryption mode enabled");
#else
ext4_msg(sb, KERN_WARNING,
"Test dummy encryption mount option ignored");
#endif
} else if (m->flags & MOPT_DATAJ) {
if (is_remount) {
if (!sbi->s_journal)
ext4_msg(sb, KERN_WARNING, "Remounting file system with no journal so ignoring journalled data option");
else if (test_opt(sb, DATA_FLAGS) != m->mount_opt) {
ext4_msg(sb, KERN_ERR,
"Cannot change data mode on remount");
return -1;
}
} else {
clear_opt(sb, DATA_FLAGS);
sbi->s_mount_opt |= m->mount_opt;
}
#ifdef CONFIG_QUOTA
} else if (m->flags & MOPT_QFMT) {
if (sb_any_quota_loaded(sb) &&
sbi->s_jquota_fmt != m->mount_opt) {
ext4_msg(sb, KERN_ERR, "Cannot change journaled "
"quota options when quota turned on");
return -1;
}
if (ext4_has_feature_quota(sb)) {
ext4_msg(sb, KERN_ERR,
"Cannot set journaled quota options "
"when QUOTA feature is enabled");
return -1;
}
sbi->s_jquota_fmt = m->mount_opt;
#endif
} else if (token == Opt_dax) {
#ifdef CONFIG_FS_DAX
ext4_msg(sb, KERN_WARNING,
"DAX enabled. Warning: EXPERIMENTAL, use at your own risk");
sbi->s_mount_opt |= m->mount_opt;
#else
ext4_msg(sb, KERN_INFO, "dax option not supported");
return -1;
#endif
} else {
if (!args->from)
arg = 1;
if (m->flags & MOPT_CLEAR)
arg = !arg;
else if (unlikely(!(m->flags & MOPT_SET))) {
ext4_msg(sb, KERN_WARNING,
"buggy handling of option %s", opt);
WARN_ON(1);
return -1;
}
if (arg != 0)
sbi->s_mount_opt |= m->mount_opt;
else
sbi->s_mount_opt &= ~m->mount_opt;
}
return 1;
}
static int parse_options(char *options, struct super_block *sb,
unsigned long *journal_devnum,
unsigned int *journal_ioprio,
int is_remount)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
char *p;
substring_t args[MAX_OPT_ARGS];
int token;
if (!options)
return 1;
while ((p = strsep(&options, ",")) != NULL) {
if (!*p)
continue;
/*
* Initialize args struct so we know whether arg was
* found; some options take optional arguments.
*/
args[0].to = args[0].from = NULL;
token = match_token(p, tokens, args);
if (handle_mount_opt(sb, p, token, args, journal_devnum,
journal_ioprio, is_remount) < 0)
return 0;
}
#ifdef CONFIG_QUOTA
if (ext4_has_feature_quota(sb) &&
(test_opt(sb, USRQUOTA) || test_opt(sb, GRPQUOTA))) {
ext4_msg(sb, KERN_ERR, "Cannot set quota options when QUOTA "
"feature is enabled");
return 0;
}
if (sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
if (test_opt(sb, USRQUOTA) && sbi->s_qf_names[USRQUOTA])
clear_opt(sb, USRQUOTA);
if (test_opt(sb, GRPQUOTA) && sbi->s_qf_names[GRPQUOTA])
clear_opt(sb, GRPQUOTA);
if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) {
ext4_msg(sb, KERN_ERR, "old and new quota "
"format mixing");
return 0;
}
if (!sbi->s_jquota_fmt) {
ext4_msg(sb, KERN_ERR, "journaled quota format "
"not specified");
return 0;
}
}
#endif
if (test_opt(sb, DIOREAD_NOLOCK)) {
int blocksize =
BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);
if (blocksize < PAGE_CACHE_SIZE) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"dioread_nolock if block size != PAGE_SIZE");
return 0;
}
}
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA &&
test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ext4_msg(sb, KERN_ERR, "can't mount with journal_async_commit "
"in data=ordered mode");
return 0;
}
return 1;
}
static inline void ext4_show_quota_options(struct seq_file *seq,
struct super_block *sb)
{
#if defined(CONFIG_QUOTA)
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (sbi->s_jquota_fmt) {
char *fmtname = "";
switch (sbi->s_jquota_fmt) {
case QFMT_VFS_OLD:
fmtname = "vfsold";
break;
case QFMT_VFS_V0:
fmtname = "vfsv0";
break;
case QFMT_VFS_V1:
fmtname = "vfsv1";
break;
}
seq_printf(seq, ",jqfmt=%s", fmtname);
}
if (sbi->s_qf_names[USRQUOTA])
seq_show_option(seq, "usrjquota", sbi->s_qf_names[USRQUOTA]);
if (sbi->s_qf_names[GRPQUOTA])
seq_show_option(seq, "grpjquota", sbi->s_qf_names[GRPQUOTA]);
#endif
}
static const char *token2str(int token)
{
const struct match_token *t;
for (t = tokens; t->token != Opt_err; t++)
if (t->token == token && !strchr(t->pattern, '='))
break;
return t->pattern;
}
/*
* Show an option if
* - it's set to a non-default value OR
* - if the per-sb default is different from the global default
*/
static int _ext4_show_options(struct seq_file *seq, struct super_block *sb,
int nodefs)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int def_errors, def_mount_opt = nodefs ? 0 : sbi->s_def_mount_opt;
const struct mount_opts *m;
char sep = nodefs ? '\n' : ',';
#define SEQ_OPTS_PUTS(str) seq_printf(seq, "%c" str, sep)
#define SEQ_OPTS_PRINT(str, arg) seq_printf(seq, "%c" str, sep, arg)
if (sbi->s_sb_block != 1)
SEQ_OPTS_PRINT("sb=%llu", sbi->s_sb_block);
for (m = ext4_mount_opts; m->token != Opt_err; m++) {
int want_set = m->flags & MOPT_SET;
if (((m->flags & (MOPT_SET|MOPT_CLEAR)) == 0) ||
(m->flags & MOPT_CLEAR_ERR))
continue;
if (!(m->mount_opt & (sbi->s_mount_opt ^ def_mount_opt)))
continue; /* skip if same as the default */
if ((want_set &&
(sbi->s_mount_opt & m->mount_opt) != m->mount_opt) ||
(!want_set && (sbi->s_mount_opt & m->mount_opt)))
continue; /* select Opt_noFoo vs Opt_Foo */
SEQ_OPTS_PRINT("%s", token2str(m->token));
}
if (nodefs || !uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT4_DEF_RESUID)) ||
le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID)
SEQ_OPTS_PRINT("resuid=%u",
from_kuid_munged(&init_user_ns, sbi->s_resuid));
if (nodefs || !gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT4_DEF_RESGID)) ||
le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID)
SEQ_OPTS_PRINT("resgid=%u",
from_kgid_munged(&init_user_ns, sbi->s_resgid));
def_errors = nodefs ? -1 : le16_to_cpu(es->s_errors);
if (test_opt(sb, ERRORS_RO) && def_errors != EXT4_ERRORS_RO)
SEQ_OPTS_PUTS("errors=remount-ro");
if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE)
SEQ_OPTS_PUTS("errors=continue");
if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC)
SEQ_OPTS_PUTS("errors=panic");
if (nodefs || sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ)
SEQ_OPTS_PRINT("commit=%lu", sbi->s_commit_interval / HZ);
if (nodefs || sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME)
SEQ_OPTS_PRINT("min_batch_time=%u", sbi->s_min_batch_time);
if (nodefs || sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME)
SEQ_OPTS_PRINT("max_batch_time=%u", sbi->s_max_batch_time);
if (sb->s_flags & MS_I_VERSION)
SEQ_OPTS_PUTS("i_version");
if (nodefs || sbi->s_stripe)
SEQ_OPTS_PRINT("stripe=%lu", sbi->s_stripe);
if (EXT4_MOUNT_DATA_FLAGS & (sbi->s_mount_opt ^ def_mount_opt)) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
SEQ_OPTS_PUTS("data=journal");
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
SEQ_OPTS_PUTS("data=ordered");
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)
SEQ_OPTS_PUTS("data=writeback");
}
if (nodefs ||
sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS)
SEQ_OPTS_PRINT("inode_readahead_blks=%u",
sbi->s_inode_readahead_blks);
if (nodefs || (test_opt(sb, INIT_INODE_TABLE) &&
(sbi->s_li_wait_mult != EXT4_DEF_LI_WAIT_MULT)))
SEQ_OPTS_PRINT("init_itable=%u", sbi->s_li_wait_mult);
if (nodefs || sbi->s_max_dir_size_kb)
SEQ_OPTS_PRINT("max_dir_size_kb=%u", sbi->s_max_dir_size_kb);
ext4_show_quota_options(seq, sb);
return 0;
}
static int ext4_show_options(struct seq_file *seq, struct dentry *root)
{
return _ext4_show_options(seq, root->d_sb, 0);
}
int ext4_seq_options_show(struct seq_file *seq, void *offset)
{
struct super_block *sb = seq->private;
int rc;
seq_puts(seq, (sb->s_flags & MS_RDONLY) ? "ro" : "rw");
rc = _ext4_show_options(seq, sb, 1);
seq_puts(seq, "\n");
return rc;
}
static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es,
int read_only)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int res = 0;
if (le32_to_cpu(es->s_rev_level) > EXT4_MAX_SUPP_REV) {
ext4_msg(sb, KERN_ERR, "revision level too high, "
"forcing read-only mode");
res = MS_RDONLY;
}
if (read_only)
goto done;
if (!(sbi->s_mount_state & EXT4_VALID_FS))
ext4_msg(sb, KERN_WARNING, "warning: mounting unchecked fs, "
"running e2fsck is recommended");
else if (sbi->s_mount_state & EXT4_ERROR_FS)
ext4_msg(sb, KERN_WARNING,
"warning: mounting fs with errors, "
"running e2fsck is recommended");
else if ((__s16) le16_to_cpu(es->s_max_mnt_count) > 0 &&
le16_to_cpu(es->s_mnt_count) >=
(unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count))
ext4_msg(sb, KERN_WARNING,
"warning: maximal mount count reached, "
"running e2fsck is recommended");
else if (le32_to_cpu(es->s_checkinterval) &&
(le32_to_cpu(es->s_lastcheck) +
le32_to_cpu(es->s_checkinterval) <= get_seconds()))
ext4_msg(sb, KERN_WARNING,
"warning: checktime reached, "
"running e2fsck is recommended");
if (!sbi->s_journal)
es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
if (!(__s16) le16_to_cpu(es->s_max_mnt_count))
es->s_max_mnt_count = cpu_to_le16(EXT4_DFL_MAX_MNT_COUNT);
le16_add_cpu(&es->s_mnt_count, 1);
es->s_mtime = cpu_to_le32(get_seconds());
ext4_update_dynamic_rev(sb);
if (sbi->s_journal)
ext4_set_feature_journal_needs_recovery(sb);
ext4_commit_super(sb, 1);
done:
if (test_opt(sb, DEBUG))
printk(KERN_INFO "[EXT4 FS bs=%lu, gc=%u, "
"bpg=%lu, ipg=%lu, mo=%04x, mo2=%04x]\n",
sb->s_blocksize,
sbi->s_groups_count,
EXT4_BLOCKS_PER_GROUP(sb),
EXT4_INODES_PER_GROUP(sb),
sbi->s_mount_opt, sbi->s_mount_opt2);
cleancache_init_fs(sb);
return res;
}
int ext4_alloc_flex_bg_array(struct super_block *sb, ext4_group_t ngroup)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct flex_groups *new_groups;
int size;
if (!sbi->s_log_groups_per_flex)
return 0;
size = ext4_flex_group(sbi, ngroup - 1) + 1;
if (size <= sbi->s_flex_groups_allocated)
return 0;
size = roundup_pow_of_two(size * sizeof(struct flex_groups));
new_groups = ext4_kvzalloc(size, GFP_KERNEL);
if (!new_groups) {
ext4_msg(sb, KERN_ERR, "not enough memory for %d flex groups",
size / (int) sizeof(struct flex_groups));
return -ENOMEM;
}
if (sbi->s_flex_groups) {
memcpy(new_groups, sbi->s_flex_groups,
(sbi->s_flex_groups_allocated *
sizeof(struct flex_groups)));
kvfree(sbi->s_flex_groups);
}
sbi->s_flex_groups = new_groups;
sbi->s_flex_groups_allocated = size / sizeof(struct flex_groups);
return 0;
}
static int ext4_fill_flex_info(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp = NULL;
ext4_group_t flex_group;
int i, err;
sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
if (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) {
sbi->s_log_groups_per_flex = 0;
return 1;
}
err = ext4_alloc_flex_bg_array(sb, sbi->s_groups_count);
if (err)
goto failed;
for (i = 0; i < sbi->s_groups_count; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
flex_group = ext4_flex_group(sbi, i);
atomic_add(ext4_free_inodes_count(sb, gdp),
&sbi->s_flex_groups[flex_group].free_inodes);
atomic64_add(ext4_free_group_clusters(sb, gdp),
&sbi->s_flex_groups[flex_group].free_clusters);
atomic_add(ext4_used_dirs_count(sb, gdp),
&sbi->s_flex_groups[flex_group].used_dirs);
}
return 1;
failed:
return 0;
}
static __le16 ext4_group_desc_csum(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
int offset;
__u16 crc = 0;
__le32 le_group = cpu_to_le32(block_group);
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (ext4_has_metadata_csum(sbi->s_sb)) {
/* Use new metadata_csum algorithm */
__le16 save_csum;
__u32 csum32;
save_csum = gdp->bg_checksum;
gdp->bg_checksum = 0;
csum32 = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&le_group,
sizeof(le_group));
csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp,
sbi->s_desc_size);
gdp->bg_checksum = save_csum;
crc = csum32 & 0xFFFF;
goto out;
}
/* old crc16 code */
if (!ext4_has_feature_gdt_csum(sb))
return 0;
offset = offsetof(struct ext4_group_desc, bg_checksum);
crc = crc16(~0, sbi->s_es->s_uuid, sizeof(sbi->s_es->s_uuid));
crc = crc16(crc, (__u8 *)&le_group, sizeof(le_group));
crc = crc16(crc, (__u8 *)gdp, offset);
offset += sizeof(gdp->bg_checksum); /* skip checksum */
/* for checksum of struct ext4_group_desc do the rest...*/
if (ext4_has_feature_64bit(sb) &&
offset < le16_to_cpu(sbi->s_es->s_desc_size))
crc = crc16(crc, (__u8 *)gdp + offset,
le16_to_cpu(sbi->s_es->s_desc_size) -
offset);
out:
return cpu_to_le16(crc);
}
int ext4_group_desc_csum_verify(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
if (ext4_has_group_desc_csum(sb) &&
(gdp->bg_checksum != ext4_group_desc_csum(sb, block_group, gdp)))
return 0;
return 1;
}
void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
if (!ext4_has_group_desc_csum(sb))
return;
gdp->bg_checksum = ext4_group_desc_csum(sb, block_group, gdp);
}
/* Called at mount-time, super-block is locked */
static int ext4_check_descriptors(struct super_block *sb,
ext4_group_t *first_not_zeroed)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block);
ext4_fsblk_t last_block;
ext4_fsblk_t block_bitmap;
ext4_fsblk_t inode_bitmap;
ext4_fsblk_t inode_table;
int flexbg_flag = 0;
ext4_group_t i, grp = sbi->s_groups_count;
if (ext4_has_feature_flex_bg(sb))
flexbg_flag = 1;
ext4_debug("Checking group descriptors");
for (i = 0; i < sbi->s_groups_count; i++) {
struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
if (i == sbi->s_groups_count - 1 || flexbg_flag)
last_block = ext4_blocks_count(sbi->s_es) - 1;
else
last_block = first_block +
(EXT4_BLOCKS_PER_GROUP(sb) - 1);
if ((grp == sbi->s_groups_count) &&
!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
grp = i;
block_bitmap = ext4_block_bitmap(sb, gdp);
if (block_bitmap < first_block || block_bitmap > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Block bitmap for group %u not in group "
"(block %llu)!", i, block_bitmap);
return 0;
}
inode_bitmap = ext4_inode_bitmap(sb, gdp);
if (inode_bitmap < first_block || inode_bitmap > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode bitmap for group %u not in group "
"(block %llu)!", i, inode_bitmap);
return 0;
}
inode_table = ext4_inode_table(sb, gdp);
if (inode_table < first_block ||
inode_table + sbi->s_itb_per_group - 1 > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode table for group %u not in group "
"(block %llu)!", i, inode_table);
return 0;
}
ext4_lock_group(sb, i);
if (!ext4_group_desc_csum_verify(sb, i, gdp)) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Checksum for group %u failed (%u!=%u)",
i, le16_to_cpu(ext4_group_desc_csum(sb, i,
gdp)), le16_to_cpu(gdp->bg_checksum));
if (!(sb->s_flags & MS_RDONLY)) {
ext4_unlock_group(sb, i);
return 0;
}
}
ext4_unlock_group(sb, i);
if (!flexbg_flag)
first_block += EXT4_BLOCKS_PER_GROUP(sb);
}
if (NULL != first_not_zeroed)
*first_not_zeroed = grp;
return 1;
}
/* ext4_orphan_cleanup() walks a singly-linked list of inodes (starting at
* the superblock) which were deleted from all directories, but held open by
* a process at the time of a crash. We walk the list and try to delete these
* inodes at recovery time (only with a read-write filesystem).
*
* In order to keep the orphan inode chain consistent during traversal (in
* case of crash during recovery), we link each inode into the superblock
* orphan list_head and handle it the same way as an inode deletion during
* normal operation (which journals the operations for us).
*
* We only do an iget() and an iput() on each inode, which is very safe if we
* accidentally point at an in-use or already deleted inode. The worst that
* can happen in this case is that we get a "bit already cleared" message from
* ext4_free_inode(). The only reason we would point at a wrong inode is if
* e2fsck was run on this filesystem, and it must have already done the orphan
* inode cleanup for us, so we can safely abort without any further action.
*/
static void ext4_orphan_cleanup(struct super_block *sb,
struct ext4_super_block *es)
{
unsigned int s_flags = sb->s_flags;
int nr_orphans = 0, nr_truncates = 0;
#ifdef CONFIG_QUOTA
int i;
#endif
if (!es->s_last_orphan) {
jbd_debug(4, "no orphan inodes to clean up\n");
return;
}
if (bdev_read_only(sb->s_bdev)) {
ext4_msg(sb, KERN_ERR, "write access "
"unavailable, skipping orphan cleanup");
return;
}
/* Check if feature set would not allow a r/w mount */
if (!ext4_feature_set_ok(sb, 0)) {
ext4_msg(sb, KERN_INFO, "Skipping orphan cleanup due to "
"unknown ROCOMPAT features");
return;
}
if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
/* don't clear list on RO mount w/ errors */
if (es->s_last_orphan && !(s_flags & MS_RDONLY)) {
ext4_msg(sb, KERN_INFO, "Errors on filesystem, "
"clearing orphan list.\n");
es->s_last_orphan = 0;
}
jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
return;
}
if (s_flags & MS_RDONLY) {
ext4_msg(sb, KERN_INFO, "orphan cleanup on readonly fs");
sb->s_flags &= ~MS_RDONLY;
}
#ifdef CONFIG_QUOTA
/* Needed for iput() to work correctly and not trash data */
sb->s_flags |= MS_ACTIVE;
/* Turn on quotas so that they are updated correctly */
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
if (EXT4_SB(sb)->s_qf_names[i]) {
int ret = ext4_quota_on_mount(sb, i);
if (ret < 0)
ext4_msg(sb, KERN_ERR,
"Cannot turn on journaled "
"quota: error %d", ret);
}
}
#endif
while (es->s_last_orphan) {
struct inode *inode;
inode = ext4_orphan_get(sb, le32_to_cpu(es->s_last_orphan));
if (IS_ERR(inode)) {
es->s_last_orphan = 0;
break;
}
list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
dquot_initialize(inode);
if (inode->i_nlink) {
if (test_opt(sb, DEBUG))
ext4_msg(sb, KERN_DEBUG,
"%s: truncating inode %lu to %lld bytes",
__func__, inode->i_ino, inode->i_size);
jbd_debug(2, "truncating inode %lu to %lld bytes\n",
inode->i_ino, inode->i_size);
inode_lock(inode);
truncate_inode_pages(inode->i_mapping, inode->i_size);
ext4_truncate(inode);
inode_unlock(inode);
nr_truncates++;
} else {
if (test_opt(sb, DEBUG))
ext4_msg(sb, KERN_DEBUG,
"%s: deleting unreferenced inode %lu",
__func__, inode->i_ino);
jbd_debug(2, "deleting unreferenced inode %lu\n",
inode->i_ino);
nr_orphans++;
}
iput(inode); /* The delete magic happens here! */
}
#define PLURAL(x) (x), ((x) == 1) ? "" : "s"
if (nr_orphans)
ext4_msg(sb, KERN_INFO, "%d orphan inode%s deleted",
PLURAL(nr_orphans));
if (nr_truncates)
ext4_msg(sb, KERN_INFO, "%d truncate%s cleaned up",
PLURAL(nr_truncates));
#ifdef CONFIG_QUOTA
/* Turn quotas off */
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
if (sb_dqopt(sb)->files[i])
dquot_quota_off(sb, i);
}
#endif
sb->s_flags = s_flags; /* Restore MS_RDONLY status */
}
/*
* Maximal extent format file size.
* Resulting logical blkno at s_maxbytes must fit in our on-disk
* extent format containers, within a sector_t, and within i_blocks
* in the vfs. ext4 inode has 48 bits of i_block in fsblock units,
* so that won't be a limiting factor.
*
* However there is other limiting factor. We do store extents in the form
* of starting block and length, hence the resulting length of the extent
* covering maximum file size must fit into on-disk format containers as
* well. Given that length is always by 1 unit bigger than max unit (because
* we count 0 as well) we have to lower the s_maxbytes by one fs block.
*
* Note, this does *not* consider any metadata overhead for vfs i_blocks.
*/
static loff_t ext4_max_size(int blkbits, int has_huge_files)
{
loff_t res;
loff_t upper_limit = MAX_LFS_FILESIZE;
/* small i_blocks in vfs inode? */
if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
/*
* CONFIG_LBDAF is not enabled implies the inode
* i_block represent total blocks in 512 bytes
* 32 == size of vfs inode i_blocks * 8
*/
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (blkbits - 9);
upper_limit <<= blkbits;
}
/*
* 32-bit extent-start container, ee_block. We lower the maxbytes
* by one fs block, so ee_len can cover the extent of maximum file
* size
*/
res = (1LL << 32) - 1;
res <<= blkbits;
/* Sanity check against vm- & vfs- imposed limits */
if (res > upper_limit)
res = upper_limit;
return res;
}
/*
* Maximal bitmap file size. There is a direct, and {,double-,triple-}indirect
* block limit, and also a limit of (2^48 - 1) 512-byte sectors in i_blocks.
* We need to be 1 filesystem block less than the 2^48 sector limit.
*/
static loff_t ext4_max_bitmap_size(int bits, int has_huge_files)
{
loff_t res = EXT4_NDIR_BLOCKS;
int meta_blocks;
loff_t upper_limit;
/* This is calculated to be the largest file size for a dense, block
* mapped file such that the file's total number of 512-byte sectors,
* including data and all indirect blocks, does not exceed (2^48 - 1).
*
* __u32 i_blocks_lo and _u16 i_blocks_high represent the total
* number of 512-byte sectors of the file.
*/
if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
/*
* !has_huge_files or CONFIG_LBDAF not enabled implies that
* the inode i_block field represents total file blocks in
* 2^32 512-byte sectors == size of vfs inode i_blocks * 8
*/
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (bits - 9);
} else {
/*
* We use 48 bit ext4_inode i_blocks
* With EXT4_HUGE_FILE_FL set the i_blocks
* represent total number of blocks in
* file system block size
*/
upper_limit = (1LL << 48) - 1;
}
/* indirect blocks */
meta_blocks = 1;
/* double indirect blocks */
meta_blocks += 1 + (1LL << (bits-2));
/* tripple indirect blocks */
meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2)));
upper_limit -= meta_blocks;
upper_limit <<= bits;
res += 1LL << (bits-2);
res += 1LL << (2*(bits-2));
res += 1LL << (3*(bits-2));
res <<= bits;
if (res > upper_limit)
res = upper_limit;
if (res > MAX_LFS_FILESIZE)
res = MAX_LFS_FILESIZE;
return res;
}
static ext4_fsblk_t descriptor_loc(struct super_block *sb,
ext4_fsblk_t logical_sb_block, int nr)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_group_t bg, first_meta_bg;
int has_super = 0;
first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
if (!ext4_has_feature_meta_bg(sb) || nr < first_meta_bg)
return logical_sb_block + nr + 1;
bg = sbi->s_desc_per_block * nr;
if (ext4_bg_has_super(sb, bg))
has_super = 1;
/*
* If we have a meta_bg fs with 1k blocks, group 0's GDT is at
* block 2, not 1. If s_first_data_block == 0 (bigalloc is enabled
* on modern mke2fs or blksize > 1k on older mke2fs) then we must
* compensate.
*/
if (sb->s_blocksize == 1024 && nr == 0 &&
le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block) == 0)
has_super++;
return (has_super + ext4_group_first_block_no(sb, bg));
}
/**
* ext4_get_stripe_size: Get the stripe size.
* @sbi: In memory super block info
*
* If we have specified it via mount option, then
* use the mount option value. If the value specified at mount time is
* greater than the blocks per group use the super block value.
* If the super block value is greater than blocks per group return 0.
* Allocator needs it be less than blocks per group.
*
*/
static unsigned long ext4_get_stripe_size(struct ext4_sb_info *sbi)
{
unsigned long stride = le16_to_cpu(sbi->s_es->s_raid_stride);
unsigned long stripe_width =
le32_to_cpu(sbi->s_es->s_raid_stripe_width);
int ret;
if (sbi->s_stripe && sbi->s_stripe <= sbi->s_blocks_per_group)
ret = sbi->s_stripe;
else if (stripe_width <= sbi->s_blocks_per_group)
ret = stripe_width;
else if (stride <= sbi->s_blocks_per_group)
ret = stride;
else
ret = 0;
/*
* If the stripe width is 1, this makes no sense and
* we set it to 0 to turn off stripe handling code.
*/
if (ret <= 1)
ret = 0;
return ret;
}
/*
* Check whether this filesystem can be mounted based on
* the features present and the RDONLY/RDWR mount requested.
* Returns 1 if this filesystem can be mounted as requested,
* 0 if it cannot be.
*/
static int ext4_feature_set_ok(struct super_block *sb, int readonly)
{
if (ext4_has_unknown_ext4_incompat_features(sb)) {
ext4_msg(sb, KERN_ERR,
"Couldn't mount because of "
"unsupported optional features (%x)",
(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) &
~EXT4_FEATURE_INCOMPAT_SUPP));
return 0;
}
if (readonly)
return 1;
if (ext4_has_feature_readonly(sb)) {
ext4_msg(sb, KERN_INFO, "filesystem is read-only");
sb->s_flags |= MS_RDONLY;
return 1;
}
/* Check that feature set is OK for a read-write mount */
if (ext4_has_unknown_ext4_ro_compat_features(sb)) {
ext4_msg(sb, KERN_ERR, "couldn't mount RDWR because of "
"unsupported optional features (%x)",
(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) &
~EXT4_FEATURE_RO_COMPAT_SUPP));
return 0;
}
/*
* Large file size enabled file system can only be mounted
* read-write on 32-bit systems if kernel is built with CONFIG_LBDAF
*/
if (ext4_has_feature_huge_file(sb)) {
if (sizeof(blkcnt_t) < sizeof(u64)) {
ext4_msg(sb, KERN_ERR, "Filesystem with huge files "
"cannot be mounted RDWR without "
"CONFIG_LBDAF");
return 0;
}
}
if (ext4_has_feature_bigalloc(sb) && !ext4_has_feature_extents(sb)) {
ext4_msg(sb, KERN_ERR,
"Can't support bigalloc feature without "
"extents feature\n");
return 0;
}
#ifndef CONFIG_QUOTA
if (ext4_has_feature_quota(sb) && !readonly) {
ext4_msg(sb, KERN_ERR,
"Filesystem with quota feature cannot be mounted RDWR "
"without CONFIG_QUOTA");
return 0;
}
if (ext4_has_feature_project(sb) && !readonly) {
ext4_msg(sb, KERN_ERR,
"Filesystem with project quota feature cannot be mounted RDWR "
"without CONFIG_QUOTA");
return 0;
}
#endif /* CONFIG_QUOTA */
return 1;
}
/*
* This function is called once a day if we have errors logged
* on the file system
*/
static void print_daily_error_info(unsigned long arg)
{
struct super_block *sb = (struct super_block *) arg;
struct ext4_sb_info *sbi;
struct ext4_super_block *es;
sbi = EXT4_SB(sb);
es = sbi->s_es;
if (es->s_error_count)
/* fsck newer than v1.41.13 is needed to clean this condition. */
ext4_msg(sb, KERN_NOTICE, "error count since last fsck: %u",
le32_to_cpu(es->s_error_count));
if (es->s_first_error_time) {
printk(KERN_NOTICE "EXT4-fs (%s): initial error at time %u: %.*s:%d",
sb->s_id, le32_to_cpu(es->s_first_error_time),
(int) sizeof(es->s_first_error_func),
es->s_first_error_func,
le32_to_cpu(es->s_first_error_line));
if (es->s_first_error_ino)
printk(": inode %u",
le32_to_cpu(es->s_first_error_ino));
if (es->s_first_error_block)
printk(": block %llu", (unsigned long long)
le64_to_cpu(es->s_first_error_block));
printk("\n");
}
if (es->s_last_error_time) {
printk(KERN_NOTICE "EXT4-fs (%s): last error at time %u: %.*s:%d",
sb->s_id, le32_to_cpu(es->s_last_error_time),
(int) sizeof(es->s_last_error_func),
es->s_last_error_func,
le32_to_cpu(es->s_last_error_line));
if (es->s_last_error_ino)
printk(": inode %u",
le32_to_cpu(es->s_last_error_ino));
if (es->s_last_error_block)
printk(": block %llu", (unsigned long long)
le64_to_cpu(es->s_last_error_block));
printk("\n");
}
mod_timer(&sbi->s_err_report, jiffies + 24*60*60*HZ); /* Once a day */
}
/* Find next suitable group and run ext4_init_inode_table */
static int ext4_run_li_request(struct ext4_li_request *elr)
{
struct ext4_group_desc *gdp = NULL;
ext4_group_t group, ngroups;
struct super_block *sb;
unsigned long timeout = 0;
int ret = 0;
sb = elr->lr_super;
ngroups = EXT4_SB(sb)->s_groups_count;
sb_start_write(sb);
for (group = elr->lr_next_group; group < ngroups; group++) {
gdp = ext4_get_group_desc(sb, group, NULL);
if (!gdp) {
ret = 1;
break;
}
if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
break;
}
if (group >= ngroups)
ret = 1;
if (!ret) {
timeout = jiffies;
ret = ext4_init_inode_table(sb, group,
elr->lr_timeout ? 0 : 1);
if (elr->lr_timeout == 0) {
timeout = (jiffies - timeout) *
elr->lr_sbi->s_li_wait_mult;
elr->lr_timeout = timeout;
}
elr->lr_next_sched = jiffies + elr->lr_timeout;
elr->lr_next_group = group + 1;
}
sb_end_write(sb);
return ret;
}
/*
* Remove lr_request from the list_request and free the
* request structure. Should be called with li_list_mtx held
*/
static void ext4_remove_li_request(struct ext4_li_request *elr)
{
struct ext4_sb_info *sbi;
if (!elr)
return;
sbi = elr->lr_sbi;
list_del(&elr->lr_request);
sbi->s_li_request = NULL;
kfree(elr);
}
static void ext4_unregister_li_request(struct super_block *sb)
{
mutex_lock(&ext4_li_mtx);
if (!ext4_li_info) {
mutex_unlock(&ext4_li_mtx);
return;
}
mutex_lock(&ext4_li_info->li_list_mtx);
ext4_remove_li_request(EXT4_SB(sb)->s_li_request);
mutex_unlock(&ext4_li_info->li_list_mtx);
mutex_unlock(&ext4_li_mtx);
}
static struct task_struct *ext4_lazyinit_task;
/*
* This is the function where ext4lazyinit thread lives. It walks
* through the request list searching for next scheduled filesystem.
* When such a fs is found, run the lazy initialization request
* (ext4_rn_li_request) and keep track of the time spend in this
* function. Based on that time we compute next schedule time of
* the request. When walking through the list is complete, compute
* next waking time and put itself into sleep.
*/
static int ext4_lazyinit_thread(void *arg)
{
struct ext4_lazy_init *eli = (struct ext4_lazy_init *)arg;
struct list_head *pos, *n;
struct ext4_li_request *elr;
unsigned long next_wakeup, cur;
BUG_ON(NULL == eli);
cont_thread:
while (true) {
next_wakeup = MAX_JIFFY_OFFSET;
mutex_lock(&eli->li_list_mtx);
if (list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
goto exit_thread;
}
list_for_each_safe(pos, n, &eli->li_request_list) {
elr = list_entry(pos, struct ext4_li_request,
lr_request);
if (time_after_eq(jiffies, elr->lr_next_sched)) {
if (ext4_run_li_request(elr) != 0) {
/* error, remove the lazy_init job */
ext4_remove_li_request(elr);
continue;
}
}
if (time_before(elr->lr_next_sched, next_wakeup))
next_wakeup = elr->lr_next_sched;
}
mutex_unlock(&eli->li_list_mtx);
try_to_freeze();
cur = jiffies;
if ((time_after_eq(cur, next_wakeup)) ||
(MAX_JIFFY_OFFSET == next_wakeup)) {
cond_resched();
continue;
}
schedule_timeout_interruptible(next_wakeup - cur);
if (kthread_should_stop()) {
ext4_clear_request_list();
goto exit_thread;
}
}
exit_thread:
/*
* It looks like the request list is empty, but we need
* to check it under the li_list_mtx lock, to prevent any
* additions into it, and of course we should lock ext4_li_mtx
* to atomically free the list and ext4_li_info, because at
* this point another ext4 filesystem could be registering
* new one.
*/
mutex_lock(&ext4_li_mtx);
mutex_lock(&eli->li_list_mtx);
if (!list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
mutex_unlock(&ext4_li_mtx);
goto cont_thread;
}
mutex_unlock(&eli->li_list_mtx);
kfree(ext4_li_info);
ext4_li_info = NULL;
mutex_unlock(&ext4_li_mtx);
return 0;
}
static void ext4_clear_request_list(void)
{
struct list_head *pos, *n;
struct ext4_li_request *elr;
mutex_lock(&ext4_li_info->li_list_mtx);
list_for_each_safe(pos, n, &ext4_li_info->li_request_list) {
elr = list_entry(pos, struct ext4_li_request,
lr_request);
ext4_remove_li_request(elr);
}
mutex_unlock(&ext4_li_info->li_list_mtx);
}
static int ext4_run_lazyinit_thread(void)
{
ext4_lazyinit_task = kthread_run(ext4_lazyinit_thread,
ext4_li_info, "ext4lazyinit");
if (IS_ERR(ext4_lazyinit_task)) {
int err = PTR_ERR(ext4_lazyinit_task);
ext4_clear_request_list();
kfree(ext4_li_info);
ext4_li_info = NULL;
printk(KERN_CRIT "EXT4-fs: error %d creating inode table "
"initialization thread\n",
err);
return err;
}
ext4_li_info->li_state |= EXT4_LAZYINIT_RUNNING;
return 0;
}
/*
* Check whether it make sense to run itable init. thread or not.
* If there is at least one uninitialized inode table, return
* corresponding group number, else the loop goes through all
* groups and return total number of groups.
*/
static ext4_group_t ext4_has_uninit_itable(struct super_block *sb)
{
ext4_group_t group, ngroups = EXT4_SB(sb)->s_groups_count;
struct ext4_group_desc *gdp = NULL;
for (group = 0; group < ngroups; group++) {
gdp = ext4_get_group_desc(sb, group, NULL);
if (!gdp)
continue;
if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
break;
}
return group;
}
static int ext4_li_info_new(void)
{
struct ext4_lazy_init *eli = NULL;
eli = kzalloc(sizeof(*eli), GFP_KERNEL);
if (!eli)
return -ENOMEM;
INIT_LIST_HEAD(&eli->li_request_list);
mutex_init(&eli->li_list_mtx);
eli->li_state |= EXT4_LAZYINIT_QUIT;
ext4_li_info = eli;
return 0;
}
static struct ext4_li_request *ext4_li_request_new(struct super_block *sb,
ext4_group_t start)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_li_request *elr;
elr = kzalloc(sizeof(*elr), GFP_KERNEL);
if (!elr)
return NULL;
elr->lr_super = sb;
elr->lr_sbi = sbi;
elr->lr_next_group = start;
/*
* Randomize first schedule time of the request to
* spread the inode table initialization requests
* better.
*/
elr->lr_next_sched = jiffies + (prandom_u32() %
(EXT4_DEF_LI_MAX_START_DELAY * HZ));
return elr;
}
int ext4_register_li_request(struct super_block *sb,
ext4_group_t first_not_zeroed)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_li_request *elr = NULL;
ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
int ret = 0;
mutex_lock(&ext4_li_mtx);
if (sbi->s_li_request != NULL) {
/*
* Reset timeout so it can be computed again, because
* s_li_wait_mult might have changed.
*/
sbi->s_li_request->lr_timeout = 0;
goto out;
}
if (first_not_zeroed == ngroups ||
(sb->s_flags & MS_RDONLY) ||
!test_opt(sb, INIT_INODE_TABLE))
goto out;
elr = ext4_li_request_new(sb, first_not_zeroed);
if (!elr) {
ret = -ENOMEM;
goto out;
}
if (NULL == ext4_li_info) {
ret = ext4_li_info_new();
if (ret)
goto out;
}
mutex_lock(&ext4_li_info->li_list_mtx);
list_add(&elr->lr_request, &ext4_li_info->li_request_list);
mutex_unlock(&ext4_li_info->li_list_mtx);
sbi->s_li_request = elr;
/*
* set elr to NULL here since it has been inserted to
* the request_list and the removal and free of it is
* handled by ext4_clear_request_list from now on.
*/
elr = NULL;
if (!(ext4_li_info->li_state & EXT4_LAZYINIT_RUNNING)) {
ret = ext4_run_lazyinit_thread();
if (ret)
goto out;
}
out:
mutex_unlock(&ext4_li_mtx);
if (ret)
kfree(elr);
return ret;
}
/*
* We do not need to lock anything since this is called on
* module unload.
*/
static void ext4_destroy_lazyinit_thread(void)
{
/*
* If thread exited earlier
* there's nothing to be done.
*/
if (!ext4_li_info || !ext4_lazyinit_task)
return;
kthread_stop(ext4_lazyinit_task);
}
static int set_journal_csum_feature_set(struct super_block *sb)
{
int ret = 1;
int compat, incompat;
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (ext4_has_metadata_csum(sb)) {
/* journal checksum v3 */
compat = 0;
incompat = JBD2_FEATURE_INCOMPAT_CSUM_V3;
} else {
/* journal checksum v1 */
compat = JBD2_FEATURE_COMPAT_CHECKSUM;
incompat = 0;
}
jbd2_journal_clear_features(sbi->s_journal,
JBD2_FEATURE_COMPAT_CHECKSUM, 0,
JBD2_FEATURE_INCOMPAT_CSUM_V3 |
JBD2_FEATURE_INCOMPAT_CSUM_V2);
if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ret = jbd2_journal_set_features(sbi->s_journal,
compat, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT |
incompat);
} else if (test_opt(sb, JOURNAL_CHECKSUM)) {
ret = jbd2_journal_set_features(sbi->s_journal,
compat, 0,
incompat);
jbd2_journal_clear_features(sbi->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
} else {
jbd2_journal_clear_features(sbi->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
}
return ret;
}
/*
* Note: calculating the overhead so we can be compatible with
* historical BSD practice is quite difficult in the face of
* clusters/bigalloc. This is because multiple metadata blocks from
* different block group can end up in the same allocation cluster.
* Calculating the exact overhead in the face of clustered allocation
* requires either O(all block bitmaps) in memory or O(number of block
* groups**2) in time. We will still calculate the superblock for
* older file systems --- and if we come across with a bigalloc file
* system with zero in s_overhead_clusters the estimate will be close to
* correct especially for very large cluster sizes --- but for newer
* file systems, it's better to calculate this figure once at mkfs
* time, and store it in the superblock. If the superblock value is
* present (even for non-bigalloc file systems), we will use it.
*/
static int count_overhead(struct super_block *sb, ext4_group_t grp,
char *buf)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp;
ext4_fsblk_t first_block, last_block, b;
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
int s, j, count = 0;
if (!ext4_has_feature_bigalloc(sb))
return (ext4_bg_has_super(sb, grp) + ext4_bg_num_gdb(sb, grp) +
sbi->s_itb_per_group + 2);
first_block = le32_to_cpu(sbi->s_es->s_first_data_block) +
(grp * EXT4_BLOCKS_PER_GROUP(sb));
last_block = first_block + EXT4_BLOCKS_PER_GROUP(sb) - 1;
for (i = 0; i < ngroups; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
b = ext4_block_bitmap(sb, gdp);
if (b >= first_block && b <= last_block) {
ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
count++;
}
b = ext4_inode_bitmap(sb, gdp);
if (b >= first_block && b <= last_block) {
ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
count++;
}
b = ext4_inode_table(sb, gdp);
if (b >= first_block && b + sbi->s_itb_per_group <= last_block)
for (j = 0; j < sbi->s_itb_per_group; j++, b++) {
int c = EXT4_B2C(sbi, b - first_block);
ext4_set_bit(c, buf);
count++;
}
if (i != grp)
continue;
s = 0;
if (ext4_bg_has_super(sb, grp)) {
ext4_set_bit(s++, buf);
count++;
}
for (j = ext4_bg_num_gdb(sb, grp); j > 0; j--) {
ext4_set_bit(EXT4_B2C(sbi, s++), buf);
count++;
}
}
if (!count)
return 0;
return EXT4_CLUSTERS_PER_GROUP(sb) -
ext4_count_free(buf, EXT4_CLUSTERS_PER_GROUP(sb) / 8);
}
/*
* Compute the overhead and stash it in sbi->s_overhead
*/
int ext4_calculate_overhead(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
ext4_fsblk_t overhead = 0;
char *buf = (char *) get_zeroed_page(GFP_NOFS);
if (!buf)
return -ENOMEM;
/*
* Compute the overhead (FS structures). This is constant
* for a given filesystem unless the number of block groups
* changes so we cache the previous value until it does.
*/
/*
* All of the blocks before first_data_block are overhead
*/
overhead = EXT4_B2C(sbi, le32_to_cpu(es->s_first_data_block));
/*
* Add the overhead found in each block group
*/
for (i = 0; i < ngroups; i++) {
int blks;
blks = count_overhead(sb, i, buf);
overhead += blks;
if (blks)
memset(buf, 0, PAGE_SIZE);
cond_resched();
}
/* Add the internal journal blocks as well */
if (sbi->s_journal && !sbi->journal_bdev)
overhead += EXT4_NUM_B2C(sbi, sbi->s_journal->j_maxlen);
sbi->s_overhead = overhead;
smp_wmb();
free_page((unsigned long) buf);
return 0;
}
static void ext4_set_resv_clusters(struct super_block *sb)
{
ext4_fsblk_t resv_clusters;
struct ext4_sb_info *sbi = EXT4_SB(sb);
/*
* There's no need to reserve anything when we aren't using extents.
* The space estimates are exact, there are no unwritten extents,
* hole punching doesn't need new metadata... This is needed especially
* to keep ext2/3 backward compatibility.
*/
if (!ext4_has_feature_extents(sb))
return;
/*
* By default we reserve 2% or 4096 clusters, whichever is smaller.
* This should cover the situations where we can not afford to run
* out of space like for example punch hole, or converting
* unwritten extents in delalloc path. In most cases such
* allocation would require 1, or 2 blocks, higher numbers are
* very rare.
*/
resv_clusters = (ext4_blocks_count(sbi->s_es) >>
sbi->s_cluster_bits);
do_div(resv_clusters, 50);
resv_clusters = min_t(ext4_fsblk_t, resv_clusters, 4096);
atomic64_set(&sbi->s_resv_clusters, resv_clusters);
}
static int ext4_fill_super(struct super_block *sb, void *data, int silent)
{
char *orig_data = kstrdup(data, GFP_KERNEL);
struct buffer_head *bh;
struct ext4_super_block *es = NULL;
struct ext4_sb_info *sbi;
ext4_fsblk_t block;
ext4_fsblk_t sb_block = get_sb_block(&data);
ext4_fsblk_t logical_sb_block;
unsigned long offset = 0;
unsigned long journal_devnum = 0;
unsigned long def_mount_opts;
struct inode *root;
const char *descr;
int ret = -ENOMEM;
int blocksize, clustersize;
unsigned int db_count;
unsigned int i;
int needs_recovery, has_huge_files, has_bigalloc;
__u64 blocks_count;
int err = 0;
unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
ext4_group_t first_not_zeroed;
sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
if (!sbi)
goto out_free_orig;
sbi->s_blockgroup_lock =
kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
if (!sbi->s_blockgroup_lock) {
kfree(sbi);
goto out_free_orig;
}
sb->s_fs_info = sbi;
sbi->s_sb = sb;
sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;
sbi->s_sb_block = sb_block;
if (sb->s_bdev->bd_part)
sbi->s_sectors_written_start =
part_stat_read(sb->s_bdev->bd_part, sectors[1]);
/* Cleanup superblock name */
strreplace(sb->s_id, '/', '!');
/* -EINVAL is default */
ret = -EINVAL;
blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);
if (!blocksize) {
ext4_msg(sb, KERN_ERR, "unable to set blocksize");
goto out_fail;
}
/*
* The ext4 superblock will not be buffer aligned for other than 1kB
* block sizes. We need to calculate the offset from buffer start.
*/
if (blocksize != EXT4_MIN_BLOCK_SIZE) {
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
} else {
logical_sb_block = sb_block;
}
if (!(bh = sb_bread_unmovable(sb, logical_sb_block))) {
ext4_msg(sb, KERN_ERR, "unable to read superblock");
goto out_fail;
}
/*
* Note: s_es must be initialized as soon as possible because
* some ext4 macro-instructions depend on its value
*/
es = (struct ext4_super_block *) (bh->b_data + offset);
sbi->s_es = es;
sb->s_magic = le16_to_cpu(es->s_magic);
if (sb->s_magic != EXT4_SUPER_MAGIC)
goto cantfind_ext4;
sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written);
/* Warn if metadata_csum and gdt_csum are both set. */
if (ext4_has_feature_metadata_csum(sb) &&
ext4_has_feature_gdt_csum(sb))
ext4_warning(sb, "metadata_csum and uninit_bg are "
"redundant flags; please run fsck.");
/* Check for a known checksum algorithm */
if (!ext4_verify_csum_type(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"unknown checksum algorithm.");
silent = 1;
goto cantfind_ext4;
}
/* Load the checksum driver */
if (ext4_has_feature_metadata_csum(sb)) {
sbi->s_chksum_driver = crypto_alloc_shash("crc32c", 0, 0);
if (IS_ERR(sbi->s_chksum_driver)) {
ext4_msg(sb, KERN_ERR, "Cannot load crc32c driver.");
ret = PTR_ERR(sbi->s_chksum_driver);
sbi->s_chksum_driver = NULL;
goto failed_mount;
}
}
/* Check superblock checksum */
if (!ext4_superblock_csum_verify(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"invalid superblock checksum. Run e2fsck?");
silent = 1;
ret = -EFSBADCRC;
goto cantfind_ext4;
}
/* Precompute checksum seed for all metadata */
if (ext4_has_feature_csum_seed(sb))
sbi->s_csum_seed = le32_to_cpu(es->s_checksum_seed);
else if (ext4_has_metadata_csum(sb))
sbi->s_csum_seed = ext4_chksum(sbi, ~0, es->s_uuid,
sizeof(es->s_uuid));
/* Set defaults before we parse the mount options */
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
set_opt(sb, INIT_INODE_TABLE);
if (def_mount_opts & EXT4_DEFM_DEBUG)
set_opt(sb, DEBUG);
if (def_mount_opts & EXT4_DEFM_BSDGROUPS)
set_opt(sb, GRPID);
if (def_mount_opts & EXT4_DEFM_UID16)
set_opt(sb, NO_UID32);
/* xattr user namespace & acls are now defaulted on */
set_opt(sb, XATTR_USER);
#ifdef CONFIG_EXT4_FS_POSIX_ACL
set_opt(sb, POSIX_ACL);
#endif
/* don't forget to enable journal_csum when metadata_csum is enabled. */
if (ext4_has_metadata_csum(sb))
set_opt(sb, JOURNAL_CHECKSUM);
if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)
set_opt(sb, JOURNAL_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)
set_opt(sb, ORDERED_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)
set_opt(sb, WRITEBACK_DATA);
if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC)
set_opt(sb, ERRORS_PANIC);
else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE)
set_opt(sb, ERRORS_CONT);
else
set_opt(sb, ERRORS_RO);
/* block_validity enabled by default; disable with noblock_validity */
set_opt(sb, BLOCK_VALIDITY);
if (def_mount_opts & EXT4_DEFM_DISCARD)
set_opt(sb, DISCARD);
sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));
sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));
sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;
sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;
sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;
if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0)
set_opt(sb, BARRIER);
/*
* enable delayed allocation by default
* Use -o nodelalloc to turn it off
*/
if (!IS_EXT3_SB(sb) && !IS_EXT2_SB(sb) &&
((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0))
set_opt(sb, DELALLOC);
/*
* set default s_li_wait_mult for lazyinit, for the case there is
* no mount option specified.
*/
sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT;
if (!parse_options((char *) sbi->s_es->s_mount_opts, sb,
&journal_devnum, &journal_ioprio, 0)) {
ext4_msg(sb, KERN_WARNING,
"failed to parse options in superblock: %s",
sbi->s_es->s_mount_opts);
}
sbi->s_def_mount_opt = sbi->s_mount_opt;
if (!parse_options((char *) data, sb, &journal_devnum,
&journal_ioprio, 0))
goto failed_mount;
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
printk_once(KERN_WARNING "EXT4-fs: Warning: mounting "
"with data=journal disables delayed "
"allocation and O_DIRECT support!\n");
if (test_opt2(sb, EXPLICIT_DELALLOC)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
goto failed_mount;
}
if (test_opt(sb, DIOREAD_NOLOCK)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dioread_nolock");
goto failed_mount;
}
if (test_opt(sb, DAX)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dax");
goto failed_mount;
}
if (test_opt(sb, DELALLOC))
clear_opt(sb, DELALLOC);
} else {
sb->s_iflags |= SB_I_CGROUPWB;
}
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&
(ext4_has_compat_features(sb) ||
ext4_has_ro_compat_features(sb) ||
ext4_has_incompat_features(sb)))
ext4_msg(sb, KERN_WARNING,
"feature flags set on rev 0 fs, "
"running e2fsck is recommended");
if (es->s_creator_os == cpu_to_le32(EXT4_OS_HURD)) {
set_opt2(sb, HURD_COMPAT);
if (ext4_has_feature_64bit(sb)) {
ext4_msg(sb, KERN_ERR,
"The Hurd can't support 64-bit file systems");
goto failed_mount;
}
}
if (IS_EXT2_SB(sb)) {
if (ext2_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext2 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext2 due "
"to feature incompatibilities");
goto failed_mount;
}
}
if (IS_EXT3_SB(sb)) {
if (ext3_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext3 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext3 due "
"to feature incompatibilities");
goto failed_mount;
}
}
/*
* Check feature flags regardless of the revision level, since we
* previously didn't change the revision level when setting the flags,
* so there is a chance incompat flags are set on a rev 0 filesystem.
*/
if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY)))
goto failed_mount;
blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);
if (blocksize < EXT4_MIN_BLOCK_SIZE ||
blocksize > EXT4_MAX_BLOCK_SIZE) {
ext4_msg(sb, KERN_ERR,
"Unsupported filesystem blocksize %d", blocksize);
goto failed_mount;
}
if (sbi->s_mount_opt & EXT4_MOUNT_DAX) {
if (blocksize != PAGE_SIZE) {
ext4_msg(sb, KERN_ERR,
"error: unsupported blocksize for dax");
goto failed_mount;
}
if (!sb->s_bdev->bd_disk->fops->direct_access) {
ext4_msg(sb, KERN_ERR,
"error: device does not support dax");
goto failed_mount;
}
}
if (ext4_has_feature_encrypt(sb) && es->s_encryption_level) {
ext4_msg(sb, KERN_ERR, "Unsupported encryption level %d",
es->s_encryption_level);
goto failed_mount;
}
if (sb->s_blocksize != blocksize) {
/* Validate the filesystem blocksize */
if (!sb_set_blocksize(sb, blocksize)) {
ext4_msg(sb, KERN_ERR, "bad block size %d",
blocksize);
goto failed_mount;
}
brelse(bh);
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
bh = sb_bread_unmovable(sb, logical_sb_block);
if (!bh) {
ext4_msg(sb, KERN_ERR,
"Can't read superblock on 2nd try");
goto failed_mount;
}
es = (struct ext4_super_block *)(bh->b_data + offset);
sbi->s_es = es;
if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {
ext4_msg(sb, KERN_ERR,
"Magic mismatch, very weird!");
goto failed_mount;
}
}
has_huge_files = ext4_has_feature_huge_file(sb);
sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,
has_huge_files);
sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {
sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;
sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
} else {
sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||
(!is_power_of_2(sbi->s_inode_size)) ||
(sbi->s_inode_size > blocksize)) {
ext4_msg(sb, KERN_ERR,
"unsupported inode size: %d",
sbi->s_inode_size);
goto failed_mount;
}
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE)
sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2);
}
sbi->s_desc_size = le16_to_cpu(es->s_desc_size);
if (ext4_has_feature_64bit(sb)) {
if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||
sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||
!is_power_of_2(sbi->s_desc_size)) {
ext4_msg(sb, KERN_ERR,
"unsupported descriptor size %lu",
sbi->s_desc_size);
goto failed_mount;
}
} else
sbi->s_desc_size = EXT4_MIN_DESC_SIZE;
sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
if (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0)
goto cantfind_ext4;
sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb);
if (sbi->s_inodes_per_block == 0)
goto cantfind_ext4;
sbi->s_itb_per_group = sbi->s_inodes_per_group /
sbi->s_inodes_per_block;
sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb);
sbi->s_sbh = bh;
sbi->s_mount_state = le16_to_cpu(es->s_state);
sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));
sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));
for (i = 0; i < 4; i++)
sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);
sbi->s_def_hash_version = es->s_def_hash_version;
if (ext4_has_feature_dir_index(sb)) {
i = le32_to_cpu(es->s_flags);
if (i & EXT2_FLAGS_UNSIGNED_HASH)
sbi->s_hash_unsigned = 3;
else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {
#ifdef __CHAR_UNSIGNED__
if (!(sb->s_flags & MS_RDONLY))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);
sbi->s_hash_unsigned = 3;
#else
if (!(sb->s_flags & MS_RDONLY))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_SIGNED_HASH);
#endif
}
}
/* Handle clustersize */
clustersize = BLOCK_SIZE << le32_to_cpu(es->s_log_cluster_size);
has_bigalloc = ext4_has_feature_bigalloc(sb);
if (has_bigalloc) {
if (clustersize < blocksize) {
ext4_msg(sb, KERN_ERR,
"cluster size (%d) smaller than "
"block size (%d)", clustersize, blocksize);
goto failed_mount;
}
sbi->s_cluster_bits = le32_to_cpu(es->s_log_cluster_size) -
le32_to_cpu(es->s_log_block_size);
sbi->s_clusters_per_group =
le32_to_cpu(es->s_clusters_per_group);
if (sbi->s_clusters_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#clusters per group too big: %lu",
sbi->s_clusters_per_group);
goto failed_mount;
}
if (sbi->s_blocks_per_group !=
(sbi->s_clusters_per_group * (clustersize / blocksize))) {
ext4_msg(sb, KERN_ERR, "blocks per group (%lu) and "
"clusters per group (%lu) inconsistent",
sbi->s_blocks_per_group,
sbi->s_clusters_per_group);
goto failed_mount;
}
} else {
if (clustersize != blocksize) {
ext4_warning(sb, "fragment/cluster size (%d) != "
"block size (%d)", clustersize,
blocksize);
clustersize = blocksize;
}
if (sbi->s_blocks_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#blocks per group too big: %lu",
sbi->s_blocks_per_group);
goto failed_mount;
}
sbi->s_clusters_per_group = sbi->s_blocks_per_group;
sbi->s_cluster_bits = 0;
}
sbi->s_cluster_ratio = clustersize / blocksize;
if (sbi->s_inodes_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#inodes per group too big: %lu",
sbi->s_inodes_per_group);
goto failed_mount;
}
/* Do we have standard group size of clustersize * 8 blocks ? */
if (sbi->s_blocks_per_group == clustersize << 3)
set_opt2(sb, STD_GROUP_SIZE);
/*
* Test whether we have more sectors than will fit in sector_t,
* and whether the max offset is addressable by the page cache.
*/
err = generic_check_addressable(sb->s_blocksize_bits,
ext4_blocks_count(es));
if (err) {
ext4_msg(sb, KERN_ERR, "filesystem"
" too large to mount safely on this system");
if (sizeof(sector_t) < 8)
ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled");
goto failed_mount;
}
if (EXT4_BLOCKS_PER_GROUP(sb) == 0)
goto cantfind_ext4;
/* check blocks count against device size */
blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
if (blocks_count && ext4_blocks_count(es) > blocks_count) {
ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu "
"exceeds size of device (%llu blocks)",
ext4_blocks_count(es), blocks_count);
goto failed_mount;
}
/*
* It makes no sense for the first data block to be beyond the end
* of the filesystem.
*/
if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) {
ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
"block %u is beyond end of filesystem (%llu)",
le32_to_cpu(es->s_first_data_block),
ext4_blocks_count(es));
goto failed_mount;
}
blocks_count = (ext4_blocks_count(es) -
le32_to_cpu(es->s_first_data_block) +
EXT4_BLOCKS_PER_GROUP(sb) - 1);
do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));
if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) {
ext4_msg(sb, KERN_WARNING, "groups count too large: %u "
"(block count %llu, first data block %u, "
"blocks per group %lu)", sbi->s_groups_count,
ext4_blocks_count(es),
le32_to_cpu(es->s_first_data_block),
EXT4_BLOCKS_PER_GROUP(sb));
goto failed_mount;
}
sbi->s_groups_count = blocks_count;
sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
(EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /
EXT4_DESC_PER_BLOCK(sb);
sbi->s_group_desc = ext4_kvmalloc(db_count *
sizeof(struct buffer_head *),
GFP_KERNEL);
if (sbi->s_group_desc == NULL) {
ext4_msg(sb, KERN_ERR, "not enough memory");
ret = -ENOMEM;
goto failed_mount;
}
bgl_lock_init(sbi->s_blockgroup_lock);
for (i = 0; i < db_count; i++) {
block = descriptor_loc(sb, logical_sb_block, i);
sbi->s_group_desc[i] = sb_bread_unmovable(sb, block);
if (!sbi->s_group_desc[i]) {
ext4_msg(sb, KERN_ERR,
"can't read group descriptor %d", i);
db_count = i;
goto failed_mount2;
}
}
if (!ext4_check_descriptors(sb, &first_not_zeroed)) {
ext4_msg(sb, KERN_ERR, "group descriptors corrupted!");
ret = -EFSCORRUPTED;
goto failed_mount2;
}
sbi->s_gdb_count = db_count;
get_random_bytes(&sbi->s_next_generation, sizeof(u32));
spin_lock_init(&sbi->s_next_gen_lock);
setup_timer(&sbi->s_err_report, print_daily_error_info,
(unsigned long) sb);
/* Register extent status tree shrinker */
if (ext4_es_register_shrinker(sbi))
goto failed_mount3;
sbi->s_stripe = ext4_get_stripe_size(sbi);
sbi->s_extent_max_zeroout_kb = 32;
/*
* set up enough so that it can read an inode
*/
sb->s_op = &ext4_sops;
sb->s_export_op = &ext4_export_ops;
sb->s_xattr = ext4_xattr_handlers;
#ifdef CONFIG_QUOTA
sb->dq_op = &ext4_quota_operations;
if (ext4_has_feature_quota(sb))
sb->s_qcop = &dquot_quotactl_sysfile_ops;
else
sb->s_qcop = &ext4_qctl_operations;
sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;
#endif
memcpy(sb->s_uuid, es->s_uuid, sizeof(es->s_uuid));
INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */
mutex_init(&sbi->s_orphan_lock);
sb->s_root = NULL;
needs_recovery = (es->s_last_orphan != 0 ||
ext4_has_feature_journal_needs_recovery(sb));
if (ext4_has_feature_mmp(sb) && !(sb->s_flags & MS_RDONLY))
if (ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block)))
goto failed_mount3a;
/*
* The first inode we look at is the journal inode. Don't try
* root first: it may be modified in the journal!
*/
if (!test_opt(sb, NOLOAD) && ext4_has_feature_journal(sb)) {
if (ext4_load_journal(sb, es, journal_devnum))
goto failed_mount3a;
} else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) &&
ext4_has_feature_journal_needs_recovery(sb)) {
ext4_msg(sb, KERN_ERR, "required journal recovery "
"suppressed and not mounted read-only");
goto failed_mount_wq;
} else {
/* Nojournal mode, all journal mount options are illegal */
if (test_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_checksum, fs mounted w/o journal");
goto failed_mount_wq;
}
if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_async_commit, fs mounted w/o journal");
goto failed_mount_wq;
}
if (sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"commit=%lu, fs mounted w/o journal",
sbi->s_commit_interval / HZ);
goto failed_mount_wq;
}
if (EXT4_MOUNT_DATA_FLAGS &
(sbi->s_mount_opt ^ sbi->s_def_mount_opt)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"data=, fs mounted w/o journal");
goto failed_mount_wq;
}
sbi->s_def_mount_opt &= EXT4_MOUNT_JOURNAL_CHECKSUM;
clear_opt(sb, JOURNAL_CHECKSUM);
clear_opt(sb, DATA_FLAGS);
sbi->s_journal = NULL;
needs_recovery = 0;
goto no_journal;
}
if (ext4_has_feature_64bit(sb) &&
!jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_64BIT)) {
ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature");
goto failed_mount_wq;
}
if (!set_journal_csum_feature_set(sb)) {
ext4_msg(sb, KERN_ERR, "Failed to set journal checksum "
"feature set");
goto failed_mount_wq;
}
/* We have now updated the journal if required, so we can
* validate the data journaling mode. */
switch (test_opt(sb, DATA_FLAGS)) {
case 0:
/* No mode set, assume a default based on the journal
* capabilities: ORDERED_DATA if the journal can
* cope, else JOURNAL_DATA
*/
if (jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE))
set_opt(sb, ORDERED_DATA);
else
set_opt(sb, JOURNAL_DATA);
break;
case EXT4_MOUNT_ORDERED_DATA:
case EXT4_MOUNT_WRITEBACK_DATA:
if (!jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
ext4_msg(sb, KERN_ERR, "Journal does not support "
"requested data journaling mode");
goto failed_mount_wq;
}
default:
break;
}
set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
sbi->s_journal->j_commit_callback = ext4_journal_commit_callback;
no_journal:
if (ext4_mballoc_ready) {
sbi->s_mb_cache = ext4_xattr_create_cache();
if (!sbi->s_mb_cache) {
ext4_msg(sb, KERN_ERR, "Failed to create an mb_cache");
goto failed_mount_wq;
}
}
if ((DUMMY_ENCRYPTION_ENABLED(sbi) || ext4_has_feature_encrypt(sb)) &&
(blocksize != PAGE_CACHE_SIZE)) {
ext4_msg(sb, KERN_ERR,
"Unsupported blocksize for fs encryption");
goto failed_mount_wq;
}
if (DUMMY_ENCRYPTION_ENABLED(sbi) && !(sb->s_flags & MS_RDONLY) &&
!ext4_has_feature_encrypt(sb)) {
ext4_set_feature_encrypt(sb);
ext4_commit_super(sb, 1);
}
/*
* Get the # of file system overhead blocks from the
* superblock if present.
*/
if (es->s_overhead_clusters)
sbi->s_overhead = le32_to_cpu(es->s_overhead_clusters);
else {
err = ext4_calculate_overhead(sb);
if (err)
goto failed_mount_wq;
}
/*
* The maximum number of concurrent works can be high and
* concurrency isn't really necessary. Limit it to 1.
*/
EXT4_SB(sb)->rsv_conversion_wq =
alloc_workqueue("ext4-rsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
if (!EXT4_SB(sb)->rsv_conversion_wq) {
printk(KERN_ERR "EXT4-fs: failed to create workqueue\n");
ret = -ENOMEM;
goto failed_mount4;
}
/*
* The jbd2_journal_load will have done any necessary log recovery,
* so we can safely mount the rest of the filesystem now.
*/
root = ext4_iget(sb, EXT4_ROOT_INO);
if (IS_ERR(root)) {
ext4_msg(sb, KERN_ERR, "get root inode failed");
ret = PTR_ERR(root);
root = NULL;
goto failed_mount4;
}
if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck");
iput(root);
goto failed_mount4;
}
sb->s_root = d_make_root(root);
if (!sb->s_root) {
ext4_msg(sb, KERN_ERR, "get root dentry failed");
ret = -ENOMEM;
goto failed_mount4;
}
if (ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY))
sb->s_flags |= MS_RDONLY;
/* determine the minimum size of new large inodes, if present */
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
if (ext4_has_feature_extra_isize(sb)) {
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_want_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_want_extra_isize);
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_min_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_min_extra_isize);
}
}
/* Check if enough inode space is available */
if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize >
sbi->s_inode_size) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
ext4_msg(sb, KERN_INFO, "required extra inode space not"
"available");
}
ext4_set_resv_clusters(sb);
err = ext4_setup_system_zone(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize system "
"zone (%d)", err);
goto failed_mount4a;
}
ext4_ext_init(sb);
err = ext4_mb_init(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)",
err);
goto failed_mount5;
}
block = ext4_count_free_clusters(sb);
ext4_free_blocks_count_set(sbi->s_es,
EXT4_C2B(sbi, block));
err = percpu_counter_init(&sbi->s_freeclusters_counter, block,
GFP_KERNEL);
if (!err) {
unsigned long freei = ext4_count_free_inodes(sb);
sbi->s_es->s_free_inodes_count = cpu_to_le32(freei);
err = percpu_counter_init(&sbi->s_freeinodes_counter, freei,
GFP_KERNEL);
}
if (!err)
err = percpu_counter_init(&sbi->s_dirs_counter,
ext4_count_dirs(sb), GFP_KERNEL);
if (!err)
err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0,
GFP_KERNEL);
if (err) {
ext4_msg(sb, KERN_ERR, "insufficient memory");
goto failed_mount6;
}
if (ext4_has_feature_flex_bg(sb))
if (!ext4_fill_flex_info(sb)) {
ext4_msg(sb, KERN_ERR,
"unable to initialize "
"flex_bg meta info!");
goto failed_mount6;
}
err = ext4_register_li_request(sb, first_not_zeroed);
if (err)
goto failed_mount6;
err = ext4_register_sysfs(sb);
if (err)
goto failed_mount7;
#ifdef CONFIG_QUOTA
/* Enable quota usage during mount. */
if (ext4_has_feature_quota(sb) && !(sb->s_flags & MS_RDONLY)) {
err = ext4_enable_quotas(sb);
if (err)
goto failed_mount8;
}
#endif /* CONFIG_QUOTA */
EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;
ext4_orphan_cleanup(sb, es);
EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;
if (needs_recovery) {
ext4_msg(sb, KERN_INFO, "recovery complete");
ext4_mark_recovery_complete(sb, es);
}
if (EXT4_SB(sb)->s_journal) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
descr = " journalled data mode";
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
descr = " ordered data mode";
else
descr = " writeback data mode";
} else
descr = "out journal";
if (test_opt(sb, DISCARD)) {
struct request_queue *q = bdev_get_queue(sb->s_bdev);
if (!blk_queue_discard(q))
ext4_msg(sb, KERN_WARNING,
"mounting with \"discard\" option, but "
"the device does not support discard");
}
if (___ratelimit(&ext4_mount_msg_ratelimit, "EXT4-fs mount"))
ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. "
"Opts: %s%s%s", descr, sbi->s_es->s_mount_opts,
*sbi->s_es->s_mount_opts ? "; " : "", orig_data);
if (es->s_error_count)
mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */
/* Enable message ratelimiting. Default is 10 messages per 5 secs. */
ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10);
kfree(orig_data);
return 0;
cantfind_ext4:
if (!silent)
ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem");
goto failed_mount;
#ifdef CONFIG_QUOTA
failed_mount8:
ext4_unregister_sysfs(sb);
#endif
failed_mount7:
ext4_unregister_li_request(sb);
failed_mount6:
ext4_mb_release(sb);
if (sbi->s_flex_groups)
kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
failed_mount5:
ext4_ext_release(sb);
ext4_release_system_zone(sb);
failed_mount4a:
dput(sb->s_root);
sb->s_root = NULL;
failed_mount4:
ext4_msg(sb, KERN_ERR, "mount failed");
if (EXT4_SB(sb)->rsv_conversion_wq)
destroy_workqueue(EXT4_SB(sb)->rsv_conversion_wq);
failed_mount_wq:
if (sbi->s_mb_cache) {
ext4_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (sbi->s_journal) {
jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
}
failed_mount3a:
ext4_es_unregister_shrinker(sbi);
failed_mount3:
del_timer_sync(&sbi->s_err_report);
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
failed_mount2:
for (i = 0; i < db_count; i++)
brelse(sbi->s_group_desc[i]);
kvfree(sbi->s_group_desc);
failed_mount:
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
ext4_blkdev_remove(sbi);
brelse(bh);
out_fail:
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
out_free_orig:
kfree(orig_data);
return err ? err : ret;
}
/*
* Setup any per-fs journal parameters now. We'll do this both on
* initial mount, once the journal has been initialised but before we've
* done any recovery; and again on any subsequent remount.
*/
static void ext4_init_journal_params(struct super_block *sb, journal_t *journal)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
journal->j_commit_interval = sbi->s_commit_interval;
journal->j_min_batch_time = sbi->s_min_batch_time;
journal->j_max_batch_time = sbi->s_max_batch_time;
write_lock(&journal->j_state_lock);
if (test_opt(sb, BARRIER))
journal->j_flags |= JBD2_BARRIER;
else
journal->j_flags &= ~JBD2_BARRIER;
if (test_opt(sb, DATA_ERR_ABORT))
journal->j_flags |= JBD2_ABORT_ON_SYNCDATA_ERR;
else
journal->j_flags &= ~JBD2_ABORT_ON_SYNCDATA_ERR;
write_unlock(&journal->j_state_lock);
}
static journal_t *ext4_get_journal(struct super_block *sb,
unsigned int journal_inum)
{
struct inode *journal_inode;
journal_t *journal;
BUG_ON(!ext4_has_feature_journal(sb));
/* First, test for the existence of a valid inode on disk. Bad
* things happen if we iget() an unused inode, as the subsequent
* iput() will try to delete it. */
journal_inode = ext4_iget(sb, journal_inum);
if (IS_ERR(journal_inode)) {
ext4_msg(sb, KERN_ERR, "no journal found");
return NULL;
}
if (!journal_inode->i_nlink) {
make_bad_inode(journal_inode);
iput(journal_inode);
ext4_msg(sb, KERN_ERR, "journal inode is deleted");
return NULL;
}
jbd_debug(2, "Journal inode found at %p: %lld bytes\n",
journal_inode, journal_inode->i_size);
if (!S_ISREG(journal_inode->i_mode)) {
ext4_msg(sb, KERN_ERR, "invalid journal inode");
iput(journal_inode);
return NULL;
}
journal = jbd2_journal_init_inode(journal_inode);
if (!journal) {
ext4_msg(sb, KERN_ERR, "Could not load journal inode");
iput(journal_inode);
return NULL;
}
journal->j_private = sb;
ext4_init_journal_params(sb, journal);
return journal;
}
static journal_t *ext4_get_dev_journal(struct super_block *sb,
dev_t j_dev)
{
struct buffer_head *bh;
journal_t *journal;
ext4_fsblk_t start;
ext4_fsblk_t len;
int hblock, blocksize;
ext4_fsblk_t sb_block;
unsigned long offset;
struct ext4_super_block *es;
struct block_device *bdev;
BUG_ON(!ext4_has_feature_journal(sb));
bdev = ext4_blkdev_get(j_dev, sb);
if (bdev == NULL)
return NULL;
blocksize = sb->s_blocksize;
hblock = bdev_logical_block_size(bdev);
if (blocksize < hblock) {
ext4_msg(sb, KERN_ERR,
"blocksize too small for journal device");
goto out_bdev;
}
sb_block = EXT4_MIN_BLOCK_SIZE / blocksize;
offset = EXT4_MIN_BLOCK_SIZE % blocksize;
set_blocksize(bdev, blocksize);
if (!(bh = __bread(bdev, sb_block, blocksize))) {
ext4_msg(sb, KERN_ERR, "couldn't read superblock of "
"external journal");
goto out_bdev;
}
es = (struct ext4_super_block *) (bh->b_data + offset);
if ((le16_to_cpu(es->s_magic) != EXT4_SUPER_MAGIC) ||
!(le32_to_cpu(es->s_feature_incompat) &
EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)) {
ext4_msg(sb, KERN_ERR, "external journal has "
"bad superblock");
brelse(bh);
goto out_bdev;
}
if ((le32_to_cpu(es->s_feature_ro_compat) &
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) &&
es->s_checksum != ext4_superblock_csum(sb, es)) {
ext4_msg(sb, KERN_ERR, "external journal has "
"corrupt superblock");
brelse(bh);
goto out_bdev;
}
if (memcmp(EXT4_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) {
ext4_msg(sb, KERN_ERR, "journal UUID does not match");
brelse(bh);
goto out_bdev;
}
len = ext4_blocks_count(es);
start = sb_block + 1;
brelse(bh); /* we're done with the superblock */
journal = jbd2_journal_init_dev(bdev, sb->s_bdev,
start, len, blocksize);
if (!journal) {
ext4_msg(sb, KERN_ERR, "failed to create device journal");
goto out_bdev;
}
journal->j_private = sb;
ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &journal->j_sb_buffer);
wait_on_buffer(journal->j_sb_buffer);
if (!buffer_uptodate(journal->j_sb_buffer)) {
ext4_msg(sb, KERN_ERR, "I/O error on journal device");
goto out_journal;
}
if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) {
ext4_msg(sb, KERN_ERR, "External journal has more than one "
"user (unsupported) - %d",
be32_to_cpu(journal->j_superblock->s_nr_users));
goto out_journal;
}
EXT4_SB(sb)->journal_bdev = bdev;
ext4_init_journal_params(sb, journal);
return journal;
out_journal:
jbd2_journal_destroy(journal);
out_bdev:
ext4_blkdev_put(bdev);
return NULL;
}
static int ext4_load_journal(struct super_block *sb,
struct ext4_super_block *es,
unsigned long journal_devnum)
{
journal_t *journal;
unsigned int journal_inum = le32_to_cpu(es->s_journal_inum);
dev_t journal_dev;
int err = 0;
int really_read_only;
BUG_ON(!ext4_has_feature_journal(sb));
if (journal_devnum &&
journal_devnum != le32_to_cpu(es->s_journal_dev)) {
ext4_msg(sb, KERN_INFO, "external journal device major/minor "
"numbers have changed");
journal_dev = new_decode_dev(journal_devnum);
} else
journal_dev = new_decode_dev(le32_to_cpu(es->s_journal_dev));
really_read_only = bdev_read_only(sb->s_bdev);
/*
* Are we loading a blank journal or performing recovery after a
* crash? For recovery, we need to check in advance whether we
* can get read-write access to the device.
*/
if (ext4_has_feature_journal_needs_recovery(sb)) {
if (sb->s_flags & MS_RDONLY) {
ext4_msg(sb, KERN_INFO, "INFO: recovery "
"required on readonly filesystem");
if (really_read_only) {
ext4_msg(sb, KERN_ERR, "write access "
"unavailable, cannot proceed");
return -EROFS;
}
ext4_msg(sb, KERN_INFO, "write access will "
"be enabled during recovery");
}
}
if (journal_inum && journal_dev) {
ext4_msg(sb, KERN_ERR, "filesystem has both journal "
"and inode journals!");
return -EINVAL;
}
if (journal_inum) {
if (!(journal = ext4_get_journal(sb, journal_inum)))
return -EINVAL;
} else {
if (!(journal = ext4_get_dev_journal(sb, journal_dev)))
return -EINVAL;
}
if (!(journal->j_flags & JBD2_BARRIER))
ext4_msg(sb, KERN_INFO, "barriers disabled");
if (!ext4_has_feature_journal_needs_recovery(sb))
err = jbd2_journal_wipe(journal, !really_read_only);
if (!err) {
char *save = kmalloc(EXT4_S_ERR_LEN, GFP_KERNEL);
if (save)
memcpy(save, ((char *) es) +
EXT4_S_ERR_START, EXT4_S_ERR_LEN);
err = jbd2_journal_load(journal);
if (save)
memcpy(((char *) es) + EXT4_S_ERR_START,
save, EXT4_S_ERR_LEN);
kfree(save);
}
if (err) {
ext4_msg(sb, KERN_ERR, "error loading journal");
jbd2_journal_destroy(journal);
return err;
}
EXT4_SB(sb)->s_journal = journal;
ext4_clear_journal_err(sb, es);
if (!really_read_only && journal_devnum &&
journal_devnum != le32_to_cpu(es->s_journal_dev)) {
es->s_journal_dev = cpu_to_le32(journal_devnum);
/* Make sure we flush the recovery flag to disk. */
ext4_commit_super(sb, 1);
}
return 0;
}
static int ext4_commit_super(struct super_block *sb, int sync)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
struct buffer_head *sbh = EXT4_SB(sb)->s_sbh;
int error = 0;
if (!sbh || block_device_ejected(sb))
return error;
if (buffer_write_io_error(sbh)) {
/*
* Oh, dear. A previous attempt to write the
* superblock failed. This could happen because the
* USB device was yanked out. Or it could happen to
* be a transient write error and maybe the block will
* be remapped. Nothing we can do but to retry the
* write and hope for the best.
*/
ext4_msg(sb, KERN_ERR, "previous I/O error to "
"superblock detected");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
}
/*
* If the file system is mounted read-only, don't update the
* superblock write time. This avoids updating the superblock
* write time when we are mounting the root file system
* read/only but we need to replay the journal; at that point,
* for people who are east of GMT and who make their clock
* tick in localtime for Windows bug-for-bug compatibility,
* the clock is set in the future, and this will cause e2fsck
* to complain and force a full file system check.
*/
if (!(sb->s_flags & MS_RDONLY))
es->s_wtime = cpu_to_le32(get_seconds());
if (sb->s_bdev->bd_part)
es->s_kbytes_written =
cpu_to_le64(EXT4_SB(sb)->s_kbytes_written +
((part_stat_read(sb->s_bdev->bd_part, sectors[1]) -
EXT4_SB(sb)->s_sectors_written_start) >> 1));
else
es->s_kbytes_written =
cpu_to_le64(EXT4_SB(sb)->s_kbytes_written);
if (percpu_counter_initialized(&EXT4_SB(sb)->s_freeclusters_counter))
ext4_free_blocks_count_set(es,
EXT4_C2B(EXT4_SB(sb), percpu_counter_sum_positive(
&EXT4_SB(sb)->s_freeclusters_counter)));
if (percpu_counter_initialized(&EXT4_SB(sb)->s_freeinodes_counter))
es->s_free_inodes_count =
cpu_to_le32(percpu_counter_sum_positive(
&EXT4_SB(sb)->s_freeinodes_counter));
BUFFER_TRACE(sbh, "marking dirty");
ext4_superblock_csum_set(sb);
mark_buffer_dirty(sbh);
if (sync) {
error = __sync_dirty_buffer(sbh,
test_opt(sb, BARRIER) ? WRITE_FUA : WRITE_SYNC);
if (error)
return error;
error = buffer_write_io_error(sbh);
if (error) {
ext4_msg(sb, KERN_ERR, "I/O error while writing "
"superblock");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
}
}
return error;
}
/*
* Have we just finished recovery? If so, and if we are mounting (or
* remounting) the filesystem readonly, then we will end up with a
* consistent fs on disk. Record that fact.
*/
static void ext4_mark_recovery_complete(struct super_block *sb,
struct ext4_super_block *es)
{
journal_t *journal = EXT4_SB(sb)->s_journal;
if (!ext4_has_feature_journal(sb)) {
BUG_ON(journal != NULL);
return;
}
jbd2_journal_lock_updates(journal);
if (jbd2_journal_flush(journal) < 0)
goto out;
if (ext4_has_feature_journal_needs_recovery(sb) &&
sb->s_flags & MS_RDONLY) {
ext4_clear_feature_journal_needs_recovery(sb);
ext4_commit_super(sb, 1);
}
out:
jbd2_journal_unlock_updates(journal);
}
/*
* If we are mounting (or read-write remounting) a filesystem whose journal
* has recorded an error from a previous lifetime, move that error to the
* main filesystem now.
*/
static void ext4_clear_journal_err(struct super_block *sb,
struct ext4_super_block *es)
{
journal_t *journal;
int j_errno;
const char *errstr;
BUG_ON(!ext4_has_feature_journal(sb));
journal = EXT4_SB(sb)->s_journal;
/*
* Now check for any error status which may have been recorded in the
* journal by a prior ext4_error() or ext4_abort()
*/
j_errno = jbd2_journal_errno(journal);
if (j_errno) {
char nbuf[16];
errstr = ext4_decode_error(sb, j_errno, nbuf);
ext4_warning(sb, "Filesystem error recorded "
"from previous mount: %s", errstr);
ext4_warning(sb, "Marking fs in need of filesystem check.");
EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
ext4_commit_super(sb, 1);
jbd2_journal_clear_err(journal);
jbd2_journal_update_sb_errno(journal);
}
}
/*
* Force the running and committing transactions to commit,
* and wait on the commit.
*/
int ext4_force_commit(struct super_block *sb)
{
journal_t *journal;
if (sb->s_flags & MS_RDONLY)
return 0;
journal = EXT4_SB(sb)->s_journal;
return ext4_journal_force_commit(journal);
}
static int ext4_sync_fs(struct super_block *sb, int wait)
{
int ret = 0;
tid_t target;
bool needs_barrier = false;
struct ext4_sb_info *sbi = EXT4_SB(sb);
trace_ext4_sync_fs(sb, wait);
flush_workqueue(sbi->rsv_conversion_wq);
/*
* Writeback quota in non-journalled quota case - journalled quota has
* no dirty dquots
*/
dquot_writeback_dquots(sb, -1);
/*
* Data writeback is possible w/o journal transaction, so barrier must
* being sent at the end of the function. But we can skip it if
* transaction_commit will do it for us.
*/
if (sbi->s_journal) {
target = jbd2_get_latest_transaction(sbi->s_journal);
if (wait && sbi->s_journal->j_flags & JBD2_BARRIER &&
!jbd2_trans_will_send_data_barrier(sbi->s_journal, target))
needs_barrier = true;
if (jbd2_journal_start_commit(sbi->s_journal, &target)) {
if (wait)
ret = jbd2_log_wait_commit(sbi->s_journal,
target);
}
} else if (wait && test_opt(sb, BARRIER))
needs_barrier = true;
if (needs_barrier) {
int err;
err = blkdev_issue_flush(sb->s_bdev, GFP_KERNEL, NULL);
if (!ret)
ret = err;
}
return ret;
}
/*
* LVM calls this function before a (read-only) snapshot is created. This
* gives us a chance to flush the journal completely and mark the fs clean.
*
* Note that only this function cannot bring a filesystem to be in a clean
* state independently. It relies on upper layer to stop all data & metadata
* modifications.
*/
static int ext4_freeze(struct super_block *sb)
{
int error = 0;
journal_t *journal;
if (sb->s_flags & MS_RDONLY)
return 0;
journal = EXT4_SB(sb)->s_journal;
if (journal) {
/* Now we set up the journal barrier. */
jbd2_journal_lock_updates(journal);
/*
* Don't clear the needs_recovery flag if we failed to
* flush the journal.
*/
error = jbd2_journal_flush(journal);
if (error < 0)
goto out;
/* Journal blocked and flushed, clear needs_recovery flag. */
ext4_clear_feature_journal_needs_recovery(sb);
}
error = ext4_commit_super(sb, 1);
out:
if (journal)
/* we rely on upper layer to stop further updates */
jbd2_journal_unlock_updates(journal);
return error;
}
/*
* Called by LVM after the snapshot is done. We need to reset the RECOVER
* flag here, even though the filesystem is not technically dirty yet.
*/
static int ext4_unfreeze(struct super_block *sb)
{
if (sb->s_flags & MS_RDONLY)
return 0;
if (EXT4_SB(sb)->s_journal) {
/* Reset the needs_recovery flag before the fs is unlocked. */
ext4_set_feature_journal_needs_recovery(sb);
}
ext4_commit_super(sb, 1);
return 0;
}
/*
* Structure to save mount options for ext4_remount's benefit
*/
struct ext4_mount_options {
unsigned long s_mount_opt;
unsigned long s_mount_opt2;
kuid_t s_resuid;
kgid_t s_resgid;
unsigned long s_commit_interval;
u32 s_min_batch_time, s_max_batch_time;
#ifdef CONFIG_QUOTA
int s_jquota_fmt;
char *s_qf_names[EXT4_MAXQUOTAS];
#endif
};
static int ext4_remount(struct super_block *sb, int *flags, char *data)
{
struct ext4_super_block *es;
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned long old_sb_flags;
struct ext4_mount_options old_opts;
int enable_quota = 0;
ext4_group_t g;
unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
int err = 0;
#ifdef CONFIG_QUOTA
int i, j;
#endif
char *orig_data = kstrdup(data, GFP_KERNEL);
/* Store the original options */
old_sb_flags = sb->s_flags;
old_opts.s_mount_opt = sbi->s_mount_opt;
old_opts.s_mount_opt2 = sbi->s_mount_opt2;
old_opts.s_resuid = sbi->s_resuid;
old_opts.s_resgid = sbi->s_resgid;
old_opts.s_commit_interval = sbi->s_commit_interval;
old_opts.s_min_batch_time = sbi->s_min_batch_time;
old_opts.s_max_batch_time = sbi->s_max_batch_time;
#ifdef CONFIG_QUOTA
old_opts.s_jquota_fmt = sbi->s_jquota_fmt;
for (i = 0; i < EXT4_MAXQUOTAS; i++)
if (sbi->s_qf_names[i]) {
old_opts.s_qf_names[i] = kstrdup(sbi->s_qf_names[i],
GFP_KERNEL);
if (!old_opts.s_qf_names[i]) {
for (j = 0; j < i; j++)
kfree(old_opts.s_qf_names[j]);
kfree(orig_data);
return -ENOMEM;
}
} else
old_opts.s_qf_names[i] = NULL;
#endif
if (sbi->s_journal && sbi->s_journal->j_task->io_context)
journal_ioprio = sbi->s_journal->j_task->io_context->ioprio;
if (!parse_options(data, sb, NULL, &journal_ioprio, 1)) {
err = -EINVAL;
goto restore_opts;
}
if ((old_opts.s_mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) ^
test_opt(sb, JOURNAL_CHECKSUM)) {
ext4_msg(sb, KERN_ERR, "changing journal_checksum "
"during remount not supported; ignoring");
sbi->s_mount_opt ^= EXT4_MOUNT_JOURNAL_CHECKSUM;
}
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
if (test_opt2(sb, EXPLICIT_DELALLOC)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
err = -EINVAL;
goto restore_opts;
}
if (test_opt(sb, DIOREAD_NOLOCK)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dioread_nolock");
err = -EINVAL;
goto restore_opts;
}
if (test_opt(sb, DAX)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dax");
err = -EINVAL;
goto restore_opts;
}
}
if ((sbi->s_mount_opt ^ old_opts.s_mount_opt) & EXT4_MOUNT_DAX) {
ext4_msg(sb, KERN_WARNING, "warning: refusing change of "
"dax flag with busy inodes while remounting");
sbi->s_mount_opt ^= EXT4_MOUNT_DAX;
}
if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED)
ext4_abort(sb, "Abort forced by user");
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
es = sbi->s_es;
if (sbi->s_journal) {
ext4_init_journal_params(sb, sbi->s_journal);
set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
}
if (*flags & MS_LAZYTIME)
sb->s_flags |= MS_LAZYTIME;
if ((*flags & MS_RDONLY) != (sb->s_flags & MS_RDONLY)) {
if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED) {
err = -EROFS;
goto restore_opts;
}
if (*flags & MS_RDONLY) {
err = sync_filesystem(sb);
if (err < 0)
goto restore_opts;
err = dquot_suspend(sb, -1);
if (err < 0)
goto restore_opts;
/*
* First of all, the unconditional stuff we have to do
* to disable replay of the journal when we next remount
*/
sb->s_flags |= MS_RDONLY;
/*
* OK, test if we are remounting a valid rw partition
* readonly, and if so set the rdonly flag and then
* mark the partition as valid again.
*/
if (!(es->s_state & cpu_to_le16(EXT4_VALID_FS)) &&
(sbi->s_mount_state & EXT4_VALID_FS))
es->s_state = cpu_to_le16(sbi->s_mount_state);
if (sbi->s_journal)
ext4_mark_recovery_complete(sb, es);
} else {
/* Make sure we can mount this feature set readwrite */
if (ext4_has_feature_readonly(sb) ||
!ext4_feature_set_ok(sb, 0)) {
err = -EROFS;
goto restore_opts;
}
/*
* Make sure the group descriptor checksums
* are sane. If they aren't, refuse to remount r/w.
*/
for (g = 0; g < sbi->s_groups_count; g++) {
struct ext4_group_desc *gdp =
ext4_get_group_desc(sb, g, NULL);
if (!ext4_group_desc_csum_verify(sb, g, gdp)) {
ext4_msg(sb, KERN_ERR,
"ext4_remount: Checksum for group %u failed (%u!=%u)",
g, le16_to_cpu(ext4_group_desc_csum(sb, g, gdp)),
le16_to_cpu(gdp->bg_checksum));
err = -EFSBADCRC;
goto restore_opts;
}
}
/*
* If we have an unprocessed orphan list hanging
* around from a previously readonly bdev mount,
* require a full umount/remount for now.
*/
if (es->s_last_orphan) {
ext4_msg(sb, KERN_WARNING, "Couldn't "
"remount RDWR because of unprocessed "
"orphan inode list. Please "
"umount/remount instead");
err = -EINVAL;
goto restore_opts;
}
/*
* Mounting a RDONLY partition read-write, so reread
* and store the current valid flag. (It may have
* been changed by e2fsck since we originally mounted
* the partition.)
*/
if (sbi->s_journal)
ext4_clear_journal_err(sb, es);
sbi->s_mount_state = le16_to_cpu(es->s_state);
if (!ext4_setup_super(sb, es, 0))
sb->s_flags &= ~MS_RDONLY;
if (ext4_has_feature_mmp(sb))
if (ext4_multi_mount_protect(sb,
le64_to_cpu(es->s_mmp_block))) {
err = -EROFS;
goto restore_opts;
}
enable_quota = 1;
}
}
/*
* Reinitialize lazy itable initialization thread based on
* current settings
*/
if ((sb->s_flags & MS_RDONLY) || !test_opt(sb, INIT_INODE_TABLE))
ext4_unregister_li_request(sb);
else {
ext4_group_t first_not_zeroed;
first_not_zeroed = ext4_has_uninit_itable(sb);
ext4_register_li_request(sb, first_not_zeroed);
}
ext4_setup_system_zone(sb);
if (sbi->s_journal == NULL && !(old_sb_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
#ifdef CONFIG_QUOTA
/* Release old quota file names */
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(old_opts.s_qf_names[i]);
if (enable_quota) {
if (sb_any_quota_suspended(sb))
dquot_resume(sb, -1);
else if (ext4_has_feature_quota(sb)) {
err = ext4_enable_quotas(sb);
if (err)
goto restore_opts;
}
}
#endif
*flags = (*flags & ~MS_LAZYTIME) | (sb->s_flags & MS_LAZYTIME);
ext4_msg(sb, KERN_INFO, "re-mounted. Opts: %s", orig_data);
kfree(orig_data);
return 0;
restore_opts:
sb->s_flags = old_sb_flags;
sbi->s_mount_opt = old_opts.s_mount_opt;
sbi->s_mount_opt2 = old_opts.s_mount_opt2;
sbi->s_resuid = old_opts.s_resuid;
sbi->s_resgid = old_opts.s_resgid;
sbi->s_commit_interval = old_opts.s_commit_interval;
sbi->s_min_batch_time = old_opts.s_min_batch_time;
sbi->s_max_batch_time = old_opts.s_max_batch_time;
#ifdef CONFIG_QUOTA
sbi->s_jquota_fmt = old_opts.s_jquota_fmt;
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
kfree(sbi->s_qf_names[i]);
sbi->s_qf_names[i] = old_opts.s_qf_names[i];
}
#endif
kfree(orig_data);
return err;
}
#ifdef CONFIG_QUOTA
static int ext4_statfs_project(struct super_block *sb,
kprojid_t projid, struct kstatfs *buf)
{
struct kqid qid;
struct dquot *dquot;
u64 limit;
u64 curblock;
qid = make_kqid_projid(projid);
dquot = dqget(sb, qid);
if (IS_ERR(dquot))
return PTR_ERR(dquot);
spin_lock(&dq_data_lock);
limit = (dquot->dq_dqb.dqb_bsoftlimit ?
dquot->dq_dqb.dqb_bsoftlimit :
dquot->dq_dqb.dqb_bhardlimit) >> sb->s_blocksize_bits;
if (limit && buf->f_blocks > limit) {
curblock = dquot->dq_dqb.dqb_curspace >> sb->s_blocksize_bits;
buf->f_blocks = limit;
buf->f_bfree = buf->f_bavail =
(buf->f_blocks > curblock) ?
(buf->f_blocks - curblock) : 0;
}
limit = dquot->dq_dqb.dqb_isoftlimit ?
dquot->dq_dqb.dqb_isoftlimit :
dquot->dq_dqb.dqb_ihardlimit;
if (limit && buf->f_files > limit) {
buf->f_files = limit;
buf->f_ffree =
(buf->f_files > dquot->dq_dqb.dqb_curinodes) ?
(buf->f_files - dquot->dq_dqb.dqb_curinodes) : 0;
}
spin_unlock(&dq_data_lock);
dqput(dquot);
return 0;
}
#endif
static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_fsblk_t overhead = 0, resv_blocks;
u64 fsid;
s64 bfree;
resv_blocks = EXT4_C2B(sbi, atomic64_read(&sbi->s_resv_clusters));
if (!test_opt(sb, MINIX_DF))
overhead = sbi->s_overhead;
buf->f_type = EXT4_SUPER_MAGIC;
buf->f_bsize = sb->s_blocksize;
buf->f_blocks = ext4_blocks_count(es) - EXT4_C2B(sbi, overhead);
bfree = percpu_counter_sum_positive(&sbi->s_freeclusters_counter) -
percpu_counter_sum_positive(&sbi->s_dirtyclusters_counter);
/* prevent underflow in case that few free space is available */
buf->f_bfree = EXT4_C2B(sbi, max_t(s64, bfree, 0));
buf->f_bavail = buf->f_bfree -
(ext4_r_blocks_count(es) + resv_blocks);
if (buf->f_bfree < (ext4_r_blocks_count(es) + resv_blocks))
buf->f_bavail = 0;
buf->f_files = le32_to_cpu(es->s_inodes_count);
buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter);
buf->f_namelen = EXT4_NAME_LEN;
fsid = le64_to_cpup((void *)es->s_uuid) ^
le64_to_cpup((void *)es->s_uuid + sizeof(u64));
buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
#ifdef CONFIG_QUOTA
if (ext4_test_inode_flag(dentry->d_inode, EXT4_INODE_PROJINHERIT) &&
sb_has_quota_limits_enabled(sb, PRJQUOTA))
ext4_statfs_project(sb, EXT4_I(dentry->d_inode)->i_projid, buf);
#endif
return 0;
}
/* Helper function for writing quotas on sync - we need to start transaction
* before quota file is locked for write. Otherwise the are possible deadlocks:
* Process 1 Process 2
* ext4_create() quota_sync()
* jbd2_journal_start() write_dquot()
* dquot_initialize() down(dqio_mutex)
* down(dqio_mutex) jbd2_journal_start()
*
*/
#ifdef CONFIG_QUOTA
static inline struct inode *dquot_to_inode(struct dquot *dquot)
{
return sb_dqopt(dquot->dq_sb)->files[dquot->dq_id.type];
}
static int ext4_write_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
struct inode *inode;
inode = dquot_to_inode(dquot);
handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
EXT4_QUOTA_TRANS_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_commit(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_acquire_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
EXT4_QUOTA_INIT_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_acquire(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_release_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
EXT4_QUOTA_DEL_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle)) {
/* Release dquot anyway to avoid endless cycle in dqput() */
dquot_release(dquot);
return PTR_ERR(handle);
}
ret = dquot_release(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_mark_dquot_dirty(struct dquot *dquot)
{
struct super_block *sb = dquot->dq_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
/* Are we journaling quotas? */
if (ext4_has_feature_quota(sb) ||
sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
dquot_mark_dquot_dirty(dquot);
return ext4_write_dquot(dquot);
} else {
return dquot_mark_dquot_dirty(dquot);
}
}
static int ext4_write_info(struct super_block *sb, int type)
{
int ret, err;
handle_t *handle;
/* Data block + inode block */
handle = ext4_journal_start(d_inode(sb->s_root), EXT4_HT_QUOTA, 2);
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_commit_info(sb, type);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
/*
* Turn on quotas during mount time - we need to find
* the quota file and such...
*/
static int ext4_quota_on_mount(struct super_block *sb, int type)
{
return dquot_quota_on_mount(sb, EXT4_SB(sb)->s_qf_names[type],
EXT4_SB(sb)->s_jquota_fmt, type);
}
/*
* Standard function to be called on quota_on
*/
static int ext4_quota_on(struct super_block *sb, int type, int format_id,
struct path *path)
{
int err;
if (!test_opt(sb, QUOTA))
return -EINVAL;
/* Quotafile not on the same filesystem? */
if (path->dentry->d_sb != sb)
return -EXDEV;
/* Journaling quota? */
if (EXT4_SB(sb)->s_qf_names[type]) {
/* Quotafile not in fs root? */
if (path->dentry->d_parent != sb->s_root)
ext4_msg(sb, KERN_WARNING,
"Quota file not on filesystem root. "
"Journaled quota will not work");
}
/*
* When we journal data on quota file, we have to flush journal to see
* all updates to the file when we bypass pagecache...
*/
if (EXT4_SB(sb)->s_journal &&
ext4_should_journal_data(d_inode(path->dentry))) {
/*
* We don't need to lock updates but journal_flush() could
* otherwise be livelocked...
*/
jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
err = jbd2_journal_flush(EXT4_SB(sb)->s_journal);
jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
if (err)
return err;
}
return dquot_quota_on(sb, type, format_id, path);
}
static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
unsigned int flags)
{
int err;
struct inode *qf_inode;
unsigned long qf_inums[EXT4_MAXQUOTAS] = {
le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
};
BUG_ON(!ext4_has_feature_quota(sb));
if (!qf_inums[type])
return -EPERM;
qf_inode = ext4_iget(sb, qf_inums[type]);
if (IS_ERR(qf_inode)) {
ext4_error(sb, "Bad quota inode # %lu", qf_inums[type]);
return PTR_ERR(qf_inode);
}
/* Don't account quota for quota files to avoid recursion */
qf_inode->i_flags |= S_NOQUOTA;
err = dquot_enable(qf_inode, type, format_id, flags);
iput(qf_inode);
return err;
}
/* Enable usage tracking for all quota types. */
static int ext4_enable_quotas(struct super_block *sb)
{
int type, err = 0;
unsigned long qf_inums[EXT4_MAXQUOTAS] = {
le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
};
sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE;
for (type = 0; type < EXT4_MAXQUOTAS; type++) {
if (qf_inums[type]) {
err = ext4_quota_enable(sb, type, QFMT_VFS_V1,
DQUOT_USAGE_ENABLED);
if (err) {
ext4_warning(sb,
"Failed to enable quota tracking "
"(type=%d, err=%d). Please run "
"e2fsck to fix.", type, err);
return err;
}
}
}
return 0;
}
static int ext4_quota_off(struct super_block *sb, int type)
{
struct inode *inode = sb_dqopt(sb)->files[type];
handle_t *handle;
/* Force all delayed allocation blocks to be allocated.
* Caller already holds s_umount sem */
if (test_opt(sb, DELALLOC))
sync_filesystem(sb);
if (!inode)
goto out;
/* Update modification times of quota files when userspace can
* start looking at them */
handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1);
if (IS_ERR(handle))
goto out;
inode->i_mtime = inode->i_ctime = CURRENT_TIME;
ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
out:
return dquot_quota_off(sb, type);
}
/* Read data from quotafile - avoid pagecache and such because we cannot afford
* acquiring the locks... As quota files are never truncated and quota code
* itself serializes the operations (and no one else should touch the files)
* we don't have to be afraid of races */
static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
int offset = off & (sb->s_blocksize - 1);
int tocopy;
size_t toread;
struct buffer_head *bh;
loff_t i_size = i_size_read(inode);
if (off > i_size)
return 0;
if (off+len > i_size)
len = i_size-off;
toread = len;
while (toread > 0) {
tocopy = sb->s_blocksize - offset < toread ?
sb->s_blocksize - offset : toread;
bh = ext4_bread(NULL, inode, blk, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh) /* A hole? */
memset(data, 0, tocopy);
else
memcpy(data, bh->b_data+offset, tocopy);
brelse(bh);
offset = 0;
toread -= tocopy;
data += tocopy;
blk++;
}
return len;
}
/* Write to quotafile (we know the transaction is already started and has
* enough credits) */
static ssize_t ext4_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
int err, offset = off & (sb->s_blocksize - 1);
int retries = 0;
struct buffer_head *bh;
handle_t *handle = journal_current_handle();
if (EXT4_SB(sb)->s_journal && !handle) {
ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
" cancelled because transaction is not started",
(unsigned long long)off, (unsigned long long)len);
return -EIO;
}
/*
* Since we account only one data block in transaction credits,
* then it is impossible to cross a block boundary.
*/
if (sb->s_blocksize - offset < len) {
ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
" cancelled because not block aligned",
(unsigned long long)off, (unsigned long long)len);
return -EIO;
}
do {
bh = ext4_bread(handle, inode, blk,
EXT4_GET_BLOCKS_CREATE |
EXT4_GET_BLOCKS_METADATA_NOFAIL);
} while (IS_ERR(bh) && (PTR_ERR(bh) == -ENOSPC) &&
ext4_should_retry_alloc(inode->i_sb, &retries));
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh)
goto out;
BUFFER_TRACE(bh, "get write access");
err = ext4_journal_get_write_access(handle, bh);
if (err) {
brelse(bh);
return err;
}
lock_buffer(bh);
memcpy(bh->b_data+offset, data, len);
flush_dcache_page(bh->b_page);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, NULL, bh);
brelse(bh);
out:
if (inode->i_size < off + len) {
i_size_write(inode, off + len);
EXT4_I(inode)->i_disksize = inode->i_size;
ext4_mark_inode_dirty(handle, inode);
}
return len;
}
#endif
static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data)
{
return mount_bdev(fs_type, flags, dev_name, data, ext4_fill_super);
}
#if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
static inline void register_as_ext2(void)
{
int err = register_filesystem(&ext2_fs_type);
if (err)
printk(KERN_WARNING
"EXT4-fs: Unable to register as ext2 (%d)\n", err);
}
static inline void unregister_as_ext2(void)
{
unregister_filesystem(&ext2_fs_type);
}
static inline int ext2_feature_set_ok(struct super_block *sb)
{
if (ext4_has_unknown_ext2_incompat_features(sb))
return 0;
if (sb->s_flags & MS_RDONLY)
return 1;
if (ext4_has_unknown_ext2_ro_compat_features(sb))
return 0;
return 1;
}
#else
static inline void register_as_ext2(void) { }
static inline void unregister_as_ext2(void) { }
static inline int ext2_feature_set_ok(struct super_block *sb) { return 0; }
#endif
static inline void register_as_ext3(void)
{
int err = register_filesystem(&ext3_fs_type);
if (err)
printk(KERN_WARNING
"EXT4-fs: Unable to register as ext3 (%d)\n", err);
}
static inline void unregister_as_ext3(void)
{
unregister_filesystem(&ext3_fs_type);
}
static inline int ext3_feature_set_ok(struct super_block *sb)
{
if (ext4_has_unknown_ext3_incompat_features(sb))
return 0;
if (!ext4_has_feature_journal(sb))
return 0;
if (sb->s_flags & MS_RDONLY)
return 1;
if (ext4_has_unknown_ext3_ro_compat_features(sb))
return 0;
return 1;
}
static struct file_system_type ext4_fs_type = {
.owner = THIS_MODULE,
.name = "ext4",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext4");
/* Shared across all ext4 file systems */
wait_queue_head_t ext4__ioend_wq[EXT4_WQ_HASH_SZ];
struct mutex ext4__aio_mutex[EXT4_WQ_HASH_SZ];
static int __init ext4_init_fs(void)
{
int i, err;
ratelimit_state_init(&ext4_mount_msg_ratelimit, 30 * HZ, 64);
ext4_li_info = NULL;
mutex_init(&ext4_li_mtx);
/* Build-time check for flags consistency */
ext4_check_flag_values();
for (i = 0; i < EXT4_WQ_HASH_SZ; i++) {
mutex_init(&ext4__aio_mutex[i]);
init_waitqueue_head(&ext4__ioend_wq[i]);
}
err = ext4_init_es();
if (err)
return err;
err = ext4_init_pageio();
if (err)
goto out5;
err = ext4_init_system_zone();
if (err)
goto out4;
err = ext4_init_sysfs();
if (err)
goto out3;
err = ext4_init_mballoc();
if (err)
goto out2;
else
ext4_mballoc_ready = 1;
err = init_inodecache();
if (err)
goto out1;
register_as_ext3();
register_as_ext2();
err = register_filesystem(&ext4_fs_type);
if (err)
goto out;
return 0;
out:
unregister_as_ext2();
unregister_as_ext3();
destroy_inodecache();
out1:
ext4_mballoc_ready = 0;
ext4_exit_mballoc();
out2:
ext4_exit_sysfs();
out3:
ext4_exit_system_zone();
out4:
ext4_exit_pageio();
out5:
ext4_exit_es();
return err;
}
static void __exit ext4_exit_fs(void)
{
ext4_exit_crypto();
ext4_destroy_lazyinit_thread();
unregister_as_ext2();
unregister_as_ext3();
unregister_filesystem(&ext4_fs_type);
destroy_inodecache();
ext4_exit_mballoc();
ext4_exit_sysfs();
ext4_exit_system_zone();
ext4_exit_pageio();
ext4_exit_es();
}
MODULE_AUTHOR("Remy Card, Stephen Tweedie, Andrew Morton, Andreas Dilger, Theodore Ts'o and others");
MODULE_DESCRIPTION("Fourth Extended Filesystem");
MODULE_LICENSE("GPL");
module_init(ext4_init_fs)
module_exit(ext4_exit_fs)
| ./CrossVul/dataset_final_sorted/CWE-19/c/good_1842_1 |
crossvul-cpp_data_good_4935_0 | /*
* Copyright (C) 2005-2010 IBM Corporation
*
* Author:
* Mimi Zohar <zohar@us.ibm.com>
* Kylene Hall <kjhall@us.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*
* File: evm_main.c
* implements evm_inode_setxattr, evm_inode_post_setxattr,
* evm_inode_removexattr, and evm_verifyxattr
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/crypto.h>
#include <linux/audit.h>
#include <linux/xattr.h>
#include <linux/integrity.h>
#include <linux/evm.h>
#include <crypto/hash.h>
#include <crypto/algapi.h>
#include "evm.h"
int evm_initialized;
static char *integrity_status_msg[] = {
"pass", "fail", "no_label", "no_xattrs", "unknown"
};
char *evm_hmac = "hmac(sha1)";
char *evm_hash = "sha1";
int evm_hmac_attrs;
char *evm_config_xattrnames[] = {
#ifdef CONFIG_SECURITY_SELINUX
XATTR_NAME_SELINUX,
#endif
#ifdef CONFIG_SECURITY_SMACK
XATTR_NAME_SMACK,
#ifdef CONFIG_EVM_EXTRA_SMACK_XATTRS
XATTR_NAME_SMACKEXEC,
XATTR_NAME_SMACKTRANSMUTE,
XATTR_NAME_SMACKMMAP,
#endif
#endif
#ifdef CONFIG_IMA_APPRAISE
XATTR_NAME_IMA,
#endif
XATTR_NAME_CAPS,
NULL
};
static int evm_fixmode;
static int __init evm_set_fixmode(char *str)
{
if (strncmp(str, "fix", 3) == 0)
evm_fixmode = 1;
return 0;
}
__setup("evm=", evm_set_fixmode);
static void __init evm_init_config(void)
{
#ifdef CONFIG_EVM_ATTR_FSUUID
evm_hmac_attrs |= EVM_ATTR_FSUUID;
#endif
pr_info("HMAC attrs: 0x%x\n", evm_hmac_attrs);
}
static int evm_find_protected_xattrs(struct dentry *dentry)
{
struct inode *inode = d_backing_inode(dentry);
char **xattr;
int error;
int count = 0;
if (!inode->i_op->getxattr)
return -EOPNOTSUPP;
for (xattr = evm_config_xattrnames; *xattr != NULL; xattr++) {
error = inode->i_op->getxattr(dentry, *xattr, NULL, 0);
if (error < 0) {
if (error == -ENODATA)
continue;
return error;
}
count++;
}
return count;
}
/*
* evm_verify_hmac - calculate and compare the HMAC with the EVM xattr
*
* Compute the HMAC on the dentry's protected set of extended attributes
* and compare it against the stored security.evm xattr.
*
* For performance:
* - use the previoulsy retrieved xattr value and length to calculate the
* HMAC.)
* - cache the verification result in the iint, when available.
*
* Returns integrity status
*/
static enum integrity_status evm_verify_hmac(struct dentry *dentry,
const char *xattr_name,
char *xattr_value,
size_t xattr_value_len,
struct integrity_iint_cache *iint)
{
struct evm_ima_xattr_data *xattr_data = NULL;
struct evm_ima_xattr_data calc;
enum integrity_status evm_status = INTEGRITY_PASS;
int rc, xattr_len;
if (iint && iint->evm_status == INTEGRITY_PASS)
return iint->evm_status;
/* if status is not PASS, try to check again - against -ENOMEM */
/* first need to know the sig type */
rc = vfs_getxattr_alloc(dentry, XATTR_NAME_EVM, (char **)&xattr_data, 0,
GFP_NOFS);
if (rc <= 0) {
evm_status = INTEGRITY_FAIL;
if (rc == -ENODATA) {
rc = evm_find_protected_xattrs(dentry);
if (rc > 0)
evm_status = INTEGRITY_NOLABEL;
else if (rc == 0)
evm_status = INTEGRITY_NOXATTRS; /* new file */
} else if (rc == -EOPNOTSUPP) {
evm_status = INTEGRITY_UNKNOWN;
}
goto out;
}
xattr_len = rc;
/* check value type */
switch (xattr_data->type) {
case EVM_XATTR_HMAC:
rc = evm_calc_hmac(dentry, xattr_name, xattr_value,
xattr_value_len, calc.digest);
if (rc)
break;
rc = crypto_memneq(xattr_data->digest, calc.digest,
sizeof(calc.digest));
if (rc)
rc = -EINVAL;
break;
case EVM_IMA_XATTR_DIGSIG:
rc = evm_calc_hash(dentry, xattr_name, xattr_value,
xattr_value_len, calc.digest);
if (rc)
break;
rc = integrity_digsig_verify(INTEGRITY_KEYRING_EVM,
(const char *)xattr_data, xattr_len,
calc.digest, sizeof(calc.digest));
if (!rc) {
/* Replace RSA with HMAC if not mounted readonly and
* not immutable
*/
if (!IS_RDONLY(d_backing_inode(dentry)) &&
!IS_IMMUTABLE(d_backing_inode(dentry)))
evm_update_evmxattr(dentry, xattr_name,
xattr_value,
xattr_value_len);
}
break;
default:
rc = -EINVAL;
break;
}
if (rc)
evm_status = (rc == -ENODATA) ?
INTEGRITY_NOXATTRS : INTEGRITY_FAIL;
out:
if (iint)
iint->evm_status = evm_status;
kfree(xattr_data);
return evm_status;
}
static int evm_protected_xattr(const char *req_xattr_name)
{
char **xattrname;
int namelen;
int found = 0;
namelen = strlen(req_xattr_name);
for (xattrname = evm_config_xattrnames; *xattrname != NULL; xattrname++) {
if ((strlen(*xattrname) == namelen)
&& (strncmp(req_xattr_name, *xattrname, namelen) == 0)) {
found = 1;
break;
}
if (strncmp(req_xattr_name,
*xattrname + XATTR_SECURITY_PREFIX_LEN,
strlen(req_xattr_name)) == 0) {
found = 1;
break;
}
}
return found;
}
/**
* evm_verifyxattr - verify the integrity of the requested xattr
* @dentry: object of the verify xattr
* @xattr_name: requested xattr
* @xattr_value: requested xattr value
* @xattr_value_len: requested xattr value length
*
* Calculate the HMAC for the given dentry and verify it against the stored
* security.evm xattr. For performance, use the xattr value and length
* previously retrieved to calculate the HMAC.
*
* Returns the xattr integrity status.
*
* This function requires the caller to lock the inode's i_mutex before it
* is executed.
*/
enum integrity_status evm_verifyxattr(struct dentry *dentry,
const char *xattr_name,
void *xattr_value, size_t xattr_value_len,
struct integrity_iint_cache *iint)
{
if (!evm_initialized || !evm_protected_xattr(xattr_name))
return INTEGRITY_UNKNOWN;
if (!iint) {
iint = integrity_iint_find(d_backing_inode(dentry));
if (!iint)
return INTEGRITY_UNKNOWN;
}
return evm_verify_hmac(dentry, xattr_name, xattr_value,
xattr_value_len, iint);
}
EXPORT_SYMBOL_GPL(evm_verifyxattr);
/*
* evm_verify_current_integrity - verify the dentry's metadata integrity
* @dentry: pointer to the affected dentry
*
* Verify and return the dentry's metadata integrity. The exceptions are
* before EVM is initialized or in 'fix' mode.
*/
static enum integrity_status evm_verify_current_integrity(struct dentry *dentry)
{
struct inode *inode = d_backing_inode(dentry);
if (!evm_initialized || !S_ISREG(inode->i_mode) || evm_fixmode)
return 0;
return evm_verify_hmac(dentry, NULL, NULL, 0, NULL);
}
/*
* evm_protect_xattr - protect the EVM extended attribute
*
* Prevent security.evm from being modified or removed without the
* necessary permissions or when the existing value is invalid.
*
* The posix xattr acls are 'system' prefixed, which normally would not
* affect security.evm. An interesting side affect of writing posix xattr
* acls is their modifying of the i_mode, which is included in security.evm.
* For posix xattr acls only, permit security.evm, even if it currently
* doesn't exist, to be updated.
*/
static int evm_protect_xattr(struct dentry *dentry, const char *xattr_name,
const void *xattr_value, size_t xattr_value_len)
{
enum integrity_status evm_status;
if (strcmp(xattr_name, XATTR_NAME_EVM) == 0) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
} else if (!evm_protected_xattr(xattr_name)) {
if (!posix_xattr_acl(xattr_name))
return 0;
evm_status = evm_verify_current_integrity(dentry);
if ((evm_status == INTEGRITY_PASS) ||
(evm_status == INTEGRITY_NOXATTRS))
return 0;
goto out;
}
evm_status = evm_verify_current_integrity(dentry);
if (evm_status == INTEGRITY_NOXATTRS) {
struct integrity_iint_cache *iint;
iint = integrity_iint_find(d_backing_inode(dentry));
if (iint && (iint->flags & IMA_NEW_FILE))
return 0;
/* exception for pseudo filesystems */
if (dentry->d_inode->i_sb->s_magic == TMPFS_MAGIC
|| dentry->d_inode->i_sb->s_magic == SYSFS_MAGIC)
return 0;
integrity_audit_msg(AUDIT_INTEGRITY_METADATA,
dentry->d_inode, dentry->d_name.name,
"update_metadata",
integrity_status_msg[evm_status],
-EPERM, 0);
}
out:
if (evm_status != INTEGRITY_PASS)
integrity_audit_msg(AUDIT_INTEGRITY_METADATA, d_backing_inode(dentry),
dentry->d_name.name, "appraise_metadata",
integrity_status_msg[evm_status],
-EPERM, 0);
return evm_status == INTEGRITY_PASS ? 0 : -EPERM;
}
/**
* evm_inode_setxattr - protect the EVM extended attribute
* @dentry: pointer to the affected dentry
* @xattr_name: pointer to the affected extended attribute name
* @xattr_value: pointer to the new extended attribute value
* @xattr_value_len: pointer to the new extended attribute value length
*
* Before allowing the 'security.evm' protected xattr to be updated,
* verify the existing value is valid. As only the kernel should have
* access to the EVM encrypted key needed to calculate the HMAC, prevent
* userspace from writing HMAC value. Writing 'security.evm' requires
* requires CAP_SYS_ADMIN privileges.
*/
int evm_inode_setxattr(struct dentry *dentry, const char *xattr_name,
const void *xattr_value, size_t xattr_value_len)
{
const struct evm_ima_xattr_data *xattr_data = xattr_value;
if (strcmp(xattr_name, XATTR_NAME_EVM) == 0) {
if (!xattr_value_len)
return -EINVAL;
if (xattr_data->type != EVM_IMA_XATTR_DIGSIG)
return -EPERM;
}
return evm_protect_xattr(dentry, xattr_name, xattr_value,
xattr_value_len);
}
/**
* evm_inode_removexattr - protect the EVM extended attribute
* @dentry: pointer to the affected dentry
* @xattr_name: pointer to the affected extended attribute name
*
* Removing 'security.evm' requires CAP_SYS_ADMIN privileges and that
* the current value is valid.
*/
int evm_inode_removexattr(struct dentry *dentry, const char *xattr_name)
{
return evm_protect_xattr(dentry, xattr_name, NULL, 0);
}
static void evm_reset_status(struct inode *inode)
{
struct integrity_iint_cache *iint;
iint = integrity_iint_find(inode);
if (iint)
iint->evm_status = INTEGRITY_UNKNOWN;
}
/**
* evm_inode_post_setxattr - update 'security.evm' to reflect the changes
* @dentry: pointer to the affected dentry
* @xattr_name: pointer to the affected extended attribute name
* @xattr_value: pointer to the new extended attribute value
* @xattr_value_len: pointer to the new extended attribute value length
*
* Update the HMAC stored in 'security.evm' to reflect the change.
*
* No need to take the i_mutex lock here, as this function is called from
* __vfs_setxattr_noperm(). The caller of which has taken the inode's
* i_mutex lock.
*/
void evm_inode_post_setxattr(struct dentry *dentry, const char *xattr_name,
const void *xattr_value, size_t xattr_value_len)
{
if (!evm_initialized || (!evm_protected_xattr(xattr_name)
&& !posix_xattr_acl(xattr_name)))
return;
evm_reset_status(dentry->d_inode);
evm_update_evmxattr(dentry, xattr_name, xattr_value, xattr_value_len);
}
/**
* evm_inode_post_removexattr - update 'security.evm' after removing the xattr
* @dentry: pointer to the affected dentry
* @xattr_name: pointer to the affected extended attribute name
*
* Update the HMAC stored in 'security.evm' to reflect removal of the xattr.
*
* No need to take the i_mutex lock here, as this function is called from
* vfs_removexattr() which takes the i_mutex.
*/
void evm_inode_post_removexattr(struct dentry *dentry, const char *xattr_name)
{
if (!evm_initialized || !evm_protected_xattr(xattr_name))
return;
evm_reset_status(dentry->d_inode);
evm_update_evmxattr(dentry, xattr_name, NULL, 0);
}
/**
* evm_inode_setattr - prevent updating an invalid EVM extended attribute
* @dentry: pointer to the affected dentry
*/
int evm_inode_setattr(struct dentry *dentry, struct iattr *attr)
{
unsigned int ia_valid = attr->ia_valid;
enum integrity_status evm_status;
if (!(ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID)))
return 0;
evm_status = evm_verify_current_integrity(dentry);
if ((evm_status == INTEGRITY_PASS) ||
(evm_status == INTEGRITY_NOXATTRS))
return 0;
integrity_audit_msg(AUDIT_INTEGRITY_METADATA, d_backing_inode(dentry),
dentry->d_name.name, "appraise_metadata",
integrity_status_msg[evm_status], -EPERM, 0);
return -EPERM;
}
/**
* evm_inode_post_setattr - update 'security.evm' after modifying metadata
* @dentry: pointer to the affected dentry
* @ia_valid: for the UID and GID status
*
* For now, update the HMAC stored in 'security.evm' to reflect UID/GID
* changes.
*
* This function is called from notify_change(), which expects the caller
* to lock the inode's i_mutex.
*/
void evm_inode_post_setattr(struct dentry *dentry, int ia_valid)
{
if (!evm_initialized)
return;
if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID))
evm_update_evmxattr(dentry, NULL, NULL, 0);
}
/*
* evm_inode_init_security - initializes security.evm
*/
int evm_inode_init_security(struct inode *inode,
const struct xattr *lsm_xattr,
struct xattr *evm_xattr)
{
struct evm_ima_xattr_data *xattr_data;
int rc;
if (!evm_initialized || !evm_protected_xattr(lsm_xattr->name))
return 0;
xattr_data = kzalloc(sizeof(*xattr_data), GFP_NOFS);
if (!xattr_data)
return -ENOMEM;
xattr_data->type = EVM_XATTR_HMAC;
rc = evm_init_hmac(inode, lsm_xattr, xattr_data->digest);
if (rc < 0)
goto out;
evm_xattr->value = xattr_data;
evm_xattr->value_len = sizeof(*xattr_data);
evm_xattr->name = XATTR_EVM_SUFFIX;
return 0;
out:
kfree(xattr_data);
return rc;
}
EXPORT_SYMBOL_GPL(evm_inode_init_security);
#ifdef CONFIG_EVM_LOAD_X509
void __init evm_load_x509(void)
{
int rc;
rc = integrity_load_x509(INTEGRITY_KEYRING_EVM, CONFIG_EVM_X509_PATH);
if (!rc)
evm_initialized |= EVM_INIT_X509;
}
#endif
static int __init init_evm(void)
{
int error;
evm_init_config();
error = integrity_init_keyring(INTEGRITY_KEYRING_EVM);
if (error)
return error;
error = evm_init_secfs();
if (error < 0) {
pr_info("Error registering secfs\n");
return error;
}
return 0;
}
/*
* evm_display_config - list the EVM protected security extended attributes
*/
static int __init evm_display_config(void)
{
char **xattrname;
for (xattrname = evm_config_xattrnames; *xattrname != NULL; xattrname++)
pr_info("%s\n", *xattrname);
return 0;
}
pure_initcall(evm_display_config);
late_initcall(init_evm);
MODULE_DESCRIPTION("Extended Verification Module");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-19/c/good_4935_0 |
crossvul-cpp_data_bad_1453_3 | /*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* Copyright (c) 2013 Red Hat, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would 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 the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_shared.h"
#include "xfs_format.h"
#include "xfs_log_format.h"
#include "xfs_trans_resv.h"
#include "xfs_bit.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_da_format.h"
#include "xfs_da_btree.h"
#include "xfs_inode.h"
#include "xfs_alloc.h"
#include "xfs_trans.h"
#include "xfs_inode_item.h"
#include "xfs_bmap.h"
#include "xfs_bmap_util.h"
#include "xfs_attr.h"
#include "xfs_attr_leaf.h"
#include "xfs_attr_remote.h"
#include "xfs_trans_space.h"
#include "xfs_trace.h"
#include "xfs_cksum.h"
#include "xfs_buf_item.h"
#include "xfs_error.h"
#define ATTR_RMTVALUE_MAPSIZE 1 /* # of map entries at once */
/*
* Each contiguous block has a header, so it is not just a simple attribute
* length to FSB conversion.
*/
int
xfs_attr3_rmt_blocks(
struct xfs_mount *mp,
int attrlen)
{
if (xfs_sb_version_hascrc(&mp->m_sb)) {
int buflen = XFS_ATTR3_RMT_BUF_SPACE(mp, mp->m_sb.sb_blocksize);
return (attrlen + buflen - 1) / buflen;
}
return XFS_B_TO_FSB(mp, attrlen);
}
/*
* Checking of the remote attribute header is split into two parts. The verifier
* does CRC, location and bounds checking, the unpacking function checks the
* attribute parameters and owner.
*/
static bool
xfs_attr3_rmt_hdr_ok(
struct xfs_mount *mp,
void *ptr,
xfs_ino_t ino,
uint32_t offset,
uint32_t size,
xfs_daddr_t bno)
{
struct xfs_attr3_rmt_hdr *rmt = ptr;
if (bno != be64_to_cpu(rmt->rm_blkno))
return false;
if (offset != be32_to_cpu(rmt->rm_offset))
return false;
if (size != be32_to_cpu(rmt->rm_bytes))
return false;
if (ino != be64_to_cpu(rmt->rm_owner))
return false;
/* ok */
return true;
}
static bool
xfs_attr3_rmt_verify(
struct xfs_mount *mp,
void *ptr,
int fsbsize,
xfs_daddr_t bno)
{
struct xfs_attr3_rmt_hdr *rmt = ptr;
if (!xfs_sb_version_hascrc(&mp->m_sb))
return false;
if (rmt->rm_magic != cpu_to_be32(XFS_ATTR3_RMT_MAGIC))
return false;
if (!uuid_equal(&rmt->rm_uuid, &mp->m_sb.sb_uuid))
return false;
if (be64_to_cpu(rmt->rm_blkno) != bno)
return false;
if (be32_to_cpu(rmt->rm_bytes) > fsbsize - sizeof(*rmt))
return false;
if (be32_to_cpu(rmt->rm_offset) +
be32_to_cpu(rmt->rm_bytes) > XATTR_SIZE_MAX)
return false;
if (rmt->rm_owner == 0)
return false;
return true;
}
static void
xfs_attr3_rmt_read_verify(
struct xfs_buf *bp)
{
struct xfs_mount *mp = bp->b_target->bt_mount;
char *ptr;
int len;
xfs_daddr_t bno;
/* no verification of non-crc buffers */
if (!xfs_sb_version_hascrc(&mp->m_sb))
return;
ptr = bp->b_addr;
bno = bp->b_bn;
len = BBTOB(bp->b_length);
ASSERT(len >= XFS_LBSIZE(mp));
while (len > 0) {
if (!xfs_verify_cksum(ptr, XFS_LBSIZE(mp),
XFS_ATTR3_RMT_CRC_OFF)) {
xfs_buf_ioerror(bp, EFSBADCRC);
break;
}
if (!xfs_attr3_rmt_verify(mp, ptr, XFS_LBSIZE(mp), bno)) {
xfs_buf_ioerror(bp, EFSCORRUPTED);
break;
}
len -= XFS_LBSIZE(mp);
ptr += XFS_LBSIZE(mp);
bno += mp->m_bsize;
}
if (bp->b_error)
xfs_verifier_error(bp);
else
ASSERT(len == 0);
}
static void
xfs_attr3_rmt_write_verify(
struct xfs_buf *bp)
{
struct xfs_mount *mp = bp->b_target->bt_mount;
struct xfs_buf_log_item *bip = bp->b_fspriv;
char *ptr;
int len;
xfs_daddr_t bno;
/* no verification of non-crc buffers */
if (!xfs_sb_version_hascrc(&mp->m_sb))
return;
ptr = bp->b_addr;
bno = bp->b_bn;
len = BBTOB(bp->b_length);
ASSERT(len >= XFS_LBSIZE(mp));
while (len > 0) {
if (!xfs_attr3_rmt_verify(mp, ptr, XFS_LBSIZE(mp), bno)) {
xfs_buf_ioerror(bp, EFSCORRUPTED);
xfs_verifier_error(bp);
return;
}
if (bip) {
struct xfs_attr3_rmt_hdr *rmt;
rmt = (struct xfs_attr3_rmt_hdr *)ptr;
rmt->rm_lsn = cpu_to_be64(bip->bli_item.li_lsn);
}
xfs_update_cksum(ptr, XFS_LBSIZE(mp), XFS_ATTR3_RMT_CRC_OFF);
len -= XFS_LBSIZE(mp);
ptr += XFS_LBSIZE(mp);
bno += mp->m_bsize;
}
ASSERT(len == 0);
}
const struct xfs_buf_ops xfs_attr3_rmt_buf_ops = {
.verify_read = xfs_attr3_rmt_read_verify,
.verify_write = xfs_attr3_rmt_write_verify,
};
STATIC int
xfs_attr3_rmt_hdr_set(
struct xfs_mount *mp,
void *ptr,
xfs_ino_t ino,
uint32_t offset,
uint32_t size,
xfs_daddr_t bno)
{
struct xfs_attr3_rmt_hdr *rmt = ptr;
if (!xfs_sb_version_hascrc(&mp->m_sb))
return 0;
rmt->rm_magic = cpu_to_be32(XFS_ATTR3_RMT_MAGIC);
rmt->rm_offset = cpu_to_be32(offset);
rmt->rm_bytes = cpu_to_be32(size);
uuid_copy(&rmt->rm_uuid, &mp->m_sb.sb_uuid);
rmt->rm_owner = cpu_to_be64(ino);
rmt->rm_blkno = cpu_to_be64(bno);
return sizeof(struct xfs_attr3_rmt_hdr);
}
/*
* Helper functions to copy attribute data in and out of the one disk extents
*/
STATIC int
xfs_attr_rmtval_copyout(
struct xfs_mount *mp,
struct xfs_buf *bp,
xfs_ino_t ino,
int *offset,
int *valuelen,
__uint8_t **dst)
{
char *src = bp->b_addr;
xfs_daddr_t bno = bp->b_bn;
int len = BBTOB(bp->b_length);
ASSERT(len >= XFS_LBSIZE(mp));
while (len > 0 && *valuelen > 0) {
int hdr_size = 0;
int byte_cnt = XFS_ATTR3_RMT_BUF_SPACE(mp, XFS_LBSIZE(mp));
byte_cnt = min(*valuelen, byte_cnt);
if (xfs_sb_version_hascrc(&mp->m_sb)) {
if (!xfs_attr3_rmt_hdr_ok(mp, src, ino, *offset,
byte_cnt, bno)) {
xfs_alert(mp,
"remote attribute header mismatch bno/off/len/owner (0x%llx/0x%x/Ox%x/0x%llx)",
bno, *offset, byte_cnt, ino);
return EFSCORRUPTED;
}
hdr_size = sizeof(struct xfs_attr3_rmt_hdr);
}
memcpy(*dst, src + hdr_size, byte_cnt);
/* roll buffer forwards */
len -= XFS_LBSIZE(mp);
src += XFS_LBSIZE(mp);
bno += mp->m_bsize;
/* roll attribute data forwards */
*valuelen -= byte_cnt;
*dst += byte_cnt;
*offset += byte_cnt;
}
return 0;
}
STATIC void
xfs_attr_rmtval_copyin(
struct xfs_mount *mp,
struct xfs_buf *bp,
xfs_ino_t ino,
int *offset,
int *valuelen,
__uint8_t **src)
{
char *dst = bp->b_addr;
xfs_daddr_t bno = bp->b_bn;
int len = BBTOB(bp->b_length);
ASSERT(len >= XFS_LBSIZE(mp));
while (len > 0 && *valuelen > 0) {
int hdr_size;
int byte_cnt = XFS_ATTR3_RMT_BUF_SPACE(mp, XFS_LBSIZE(mp));
byte_cnt = min(*valuelen, byte_cnt);
hdr_size = xfs_attr3_rmt_hdr_set(mp, dst, ino, *offset,
byte_cnt, bno);
memcpy(dst + hdr_size, *src, byte_cnt);
/*
* If this is the last block, zero the remainder of it.
* Check that we are actually the last block, too.
*/
if (byte_cnt + hdr_size < XFS_LBSIZE(mp)) {
ASSERT(*valuelen - byte_cnt == 0);
ASSERT(len == XFS_LBSIZE(mp));
memset(dst + hdr_size + byte_cnt, 0,
XFS_LBSIZE(mp) - hdr_size - byte_cnt);
}
/* roll buffer forwards */
len -= XFS_LBSIZE(mp);
dst += XFS_LBSIZE(mp);
bno += mp->m_bsize;
/* roll attribute data forwards */
*valuelen -= byte_cnt;
*src += byte_cnt;
*offset += byte_cnt;
}
}
/*
* Read the value associated with an attribute from the out-of-line buffer
* that we stored it in.
*/
int
xfs_attr_rmtval_get(
struct xfs_da_args *args)
{
struct xfs_bmbt_irec map[ATTR_RMTVALUE_MAPSIZE];
struct xfs_mount *mp = args->dp->i_mount;
struct xfs_buf *bp;
xfs_dablk_t lblkno = args->rmtblkno;
__uint8_t *dst = args->value;
int valuelen = args->valuelen;
int nmap;
int error;
int blkcnt = args->rmtblkcnt;
int i;
int offset = 0;
trace_xfs_attr_rmtval_get(args);
ASSERT(!(args->flags & ATTR_KERNOVAL));
while (valuelen > 0) {
nmap = ATTR_RMTVALUE_MAPSIZE;
error = xfs_bmapi_read(args->dp, (xfs_fileoff_t)lblkno,
blkcnt, map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return error;
ASSERT(nmap >= 1);
for (i = 0; (i < nmap) && (valuelen > 0); i++) {
xfs_daddr_t dblkno;
int dblkcnt;
ASSERT((map[i].br_startblock != DELAYSTARTBLOCK) &&
(map[i].br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map[i].br_startblock);
dblkcnt = XFS_FSB_TO_BB(mp, map[i].br_blockcount);
error = xfs_trans_read_buf(mp, NULL, mp->m_ddev_targp,
dblkno, dblkcnt, 0, &bp,
&xfs_attr3_rmt_buf_ops);
if (error)
return error;
error = xfs_attr_rmtval_copyout(mp, bp, args->dp->i_ino,
&offset, &valuelen,
&dst);
xfs_buf_relse(bp);
if (error)
return error;
/* roll attribute extent map forwards */
lblkno += map[i].br_blockcount;
blkcnt -= map[i].br_blockcount;
}
}
ASSERT(valuelen == 0);
return 0;
}
/*
* Write the value associated with an attribute into the out-of-line buffer
* that we have defined for it.
*/
int
xfs_attr_rmtval_set(
struct xfs_da_args *args)
{
struct xfs_inode *dp = args->dp;
struct xfs_mount *mp = dp->i_mount;
struct xfs_bmbt_irec map;
xfs_dablk_t lblkno;
xfs_fileoff_t lfileoff = 0;
__uint8_t *src = args->value;
int blkcnt;
int valuelen;
int nmap;
int error;
int offset = 0;
trace_xfs_attr_rmtval_set(args);
/*
* Find a "hole" in the attribute address space large enough for
* us to drop the new attribute's value into. Because CRC enable
* attributes have headers, we can't just do a straight byte to FSB
* conversion and have to take the header space into account.
*/
blkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen);
error = xfs_bmap_first_unused(args->trans, args->dp, blkcnt, &lfileoff,
XFS_ATTR_FORK);
if (error)
return error;
args->rmtblkno = lblkno = (xfs_dablk_t)lfileoff;
args->rmtblkcnt = blkcnt;
/*
* Roll through the "value", allocating blocks on disk as required.
*/
while (blkcnt > 0) {
int committed;
/*
* Allocate a single extent, up to the size of the value.
*/
xfs_bmap_init(args->flist, args->firstblock);
nmap = 1;
error = xfs_bmapi_write(args->trans, dp, (xfs_fileoff_t)lblkno,
blkcnt,
XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA,
args->firstblock, args->total, &map, &nmap,
args->flist);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
lblkno += map.br_blockcount;
blkcnt -= map.br_blockcount;
/*
* Start the next trans in the chain.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
}
/*
* Roll through the "value", copying the attribute value to the
* already-allocated blocks. Blocks are written synchronously
* so that we can know they are all on disk before we turn off
* the INCOMPLETE flag.
*/
lblkno = args->rmtblkno;
blkcnt = args->rmtblkcnt;
valuelen = args->valuelen;
while (valuelen > 0) {
struct xfs_buf *bp;
xfs_daddr_t dblkno;
int dblkcnt;
ASSERT(blkcnt > 0);
xfs_bmap_init(args->flist, args->firstblock);
nmap = 1;
error = xfs_bmapi_read(dp, (xfs_fileoff_t)lblkno,
blkcnt, &map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return(error);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock),
dblkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount);
bp = xfs_buf_get(mp->m_ddev_targp, dblkno, dblkcnt, 0);
if (!bp)
return ENOMEM;
bp->b_ops = &xfs_attr3_rmt_buf_ops;
xfs_attr_rmtval_copyin(mp, bp, args->dp->i_ino, &offset,
&valuelen, &src);
error = xfs_bwrite(bp); /* GROT: NOTE: synchronous write */
xfs_buf_relse(bp);
if (error)
return error;
/* roll attribute extent map forwards */
lblkno += map.br_blockcount;
blkcnt -= map.br_blockcount;
}
ASSERT(valuelen == 0);
return 0;
}
/*
* Remove the value associated with an attribute by deleting the
* out-of-line buffer that it is stored on.
*/
int
xfs_attr_rmtval_remove(
struct xfs_da_args *args)
{
struct xfs_mount *mp = args->dp->i_mount;
xfs_dablk_t lblkno;
int blkcnt;
int error;
int done;
trace_xfs_attr_rmtval_remove(args);
/*
* Roll through the "value", invalidating the attribute value's blocks.
*/
lblkno = args->rmtblkno;
blkcnt = args->rmtblkcnt;
while (blkcnt > 0) {
struct xfs_bmbt_irec map;
struct xfs_buf *bp;
xfs_daddr_t dblkno;
int dblkcnt;
int nmap;
/*
* Try to remember where we decided to put the value.
*/
nmap = 1;
error = xfs_bmapi_read(args->dp, (xfs_fileoff_t)lblkno,
blkcnt, &map, &nmap, XFS_BMAPI_ATTRFORK);
if (error)
return(error);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock),
dblkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount);
/*
* If the "remote" value is in the cache, remove it.
*/
bp = xfs_incore(mp->m_ddev_targp, dblkno, dblkcnt, XBF_TRYLOCK);
if (bp) {
xfs_buf_stale(bp);
xfs_buf_relse(bp);
bp = NULL;
}
lblkno += map.br_blockcount;
blkcnt -= map.br_blockcount;
}
/*
* Keep de-allocating extents until the remote-value region is gone.
*/
lblkno = args->rmtblkno;
blkcnt = args->rmtblkcnt;
done = 0;
while (!done) {
int committed;
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_bunmapi(args->trans, args->dp, lblkno, blkcnt,
XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA,
1, args->firstblock, args->flist,
&done);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return error;
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, args->dp, 0);
/*
* Close out trans and start the next one in the chain.
*/
error = xfs_trans_roll(&args->trans, args->dp);
if (error)
return (error);
}
return(0);
}
| ./CrossVul/dataset_final_sorted/CWE-19/c/bad_1453_3 |
crossvul-cpp_data_bad_1453_2 | /*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* Copyright (c) 2013 Red Hat, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would 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 the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_format.h"
#include "xfs_log_format.h"
#include "xfs_trans_resv.h"
#include "xfs_bit.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_da_format.h"
#include "xfs_da_btree.h"
#include "xfs_inode.h"
#include "xfs_trans.h"
#include "xfs_inode_item.h"
#include "xfs_bmap.h"
#include "xfs_attr.h"
#include "xfs_attr_sf.h"
#include "xfs_attr_remote.h"
#include "xfs_attr_leaf.h"
#include "xfs_error.h"
#include "xfs_trace.h"
#include "xfs_buf_item.h"
#include "xfs_cksum.h"
#include "xfs_dinode.h"
#include "xfs_dir2.h"
STATIC int
xfs_attr_shortform_compare(const void *a, const void *b)
{
xfs_attr_sf_sort_t *sa, *sb;
sa = (xfs_attr_sf_sort_t *)a;
sb = (xfs_attr_sf_sort_t *)b;
if (sa->hash < sb->hash) {
return(-1);
} else if (sa->hash > sb->hash) {
return(1);
} else {
return(sa->entno - sb->entno);
}
}
#define XFS_ISRESET_CURSOR(cursor) \
(!((cursor)->initted) && !((cursor)->hashval) && \
!((cursor)->blkno) && !((cursor)->offset))
/*
* Copy out entries of shortform attribute lists for attr_list().
* Shortform attribute lists are not stored in hashval sorted order.
* If the output buffer is not large enough to hold them all, then we
* we have to calculate each entries' hashvalue and sort them before
* we can begin returning them to the user.
*/
int
xfs_attr_shortform_list(xfs_attr_list_context_t *context)
{
attrlist_cursor_kern_t *cursor;
xfs_attr_sf_sort_t *sbuf, *sbp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_inode_t *dp;
int sbsize, nsbuf, count, i;
int error;
ASSERT(context != NULL);
dp = context->dp;
ASSERT(dp != NULL);
ASSERT(dp->i_afp != NULL);
sf = (xfs_attr_shortform_t *)dp->i_afp->if_u1.if_data;
ASSERT(sf != NULL);
if (!sf->hdr.count)
return(0);
cursor = context->cursor;
ASSERT(cursor != NULL);
trace_xfs_attr_list_sf(context);
/*
* If the buffer is large enough and the cursor is at the start,
* do not bother with sorting since we will return everything in
* one buffer and another call using the cursor won't need to be
* made.
* Note the generous fudge factor of 16 overhead bytes per entry.
* If bufsize is zero then put_listent must be a search function
* and can just scan through what we have.
*/
if (context->bufsize == 0 ||
(XFS_ISRESET_CURSOR(cursor) &&
(dp->i_afp->if_bytes + sf->hdr.count * 16) < context->bufsize)) {
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
error = context->put_listent(context,
sfe->flags,
sfe->nameval,
(int)sfe->namelen,
(int)sfe->valuelen,
&sfe->nameval[sfe->namelen]);
/*
* Either search callback finished early or
* didn't fit it all in the buffer after all.
*/
if (context->seen_enough)
break;
if (error)
return error;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
trace_xfs_attr_list_sf_all(context);
return(0);
}
/* do no more for a search callback */
if (context->bufsize == 0)
return 0;
/*
* It didn't all fit, so we have to sort everything on hashval.
*/
sbsize = sf->hdr.count * sizeof(*sbuf);
sbp = sbuf = kmem_alloc(sbsize, KM_SLEEP | KM_NOFS);
/*
* Scan the attribute list for the rest of the entries, storing
* the relevant info from only those that match into a buffer.
*/
nsbuf = 0;
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
if (unlikely(
((char *)sfe < (char *)sf) ||
((char *)sfe >= ((char *)sf + dp->i_afp->if_bytes)))) {
XFS_CORRUPTION_ERROR("xfs_attr_shortform_list",
XFS_ERRLEVEL_LOW,
context->dp->i_mount, sfe);
kmem_free(sbuf);
return XFS_ERROR(EFSCORRUPTED);
}
sbp->entno = i;
sbp->hash = xfs_da_hashname(sfe->nameval, sfe->namelen);
sbp->name = sfe->nameval;
sbp->namelen = sfe->namelen;
/* These are bytes, and both on-disk, don't endian-flip */
sbp->valuelen = sfe->valuelen;
sbp->flags = sfe->flags;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
sbp++;
nsbuf++;
}
/*
* Sort the entries on hash then entno.
*/
xfs_sort(sbuf, nsbuf, sizeof(*sbuf), xfs_attr_shortform_compare);
/*
* Re-find our place IN THE SORTED LIST.
*/
count = 0;
cursor->initted = 1;
cursor->blkno = 0;
for (sbp = sbuf, i = 0; i < nsbuf; i++, sbp++) {
if (sbp->hash == cursor->hashval) {
if (cursor->offset == count) {
break;
}
count++;
} else if (sbp->hash > cursor->hashval) {
break;
}
}
if (i == nsbuf) {
kmem_free(sbuf);
return(0);
}
/*
* Loop putting entries into the user buffer.
*/
for ( ; i < nsbuf; i++, sbp++) {
if (cursor->hashval != sbp->hash) {
cursor->hashval = sbp->hash;
cursor->offset = 0;
}
error = context->put_listent(context,
sbp->flags,
sbp->name,
sbp->namelen,
sbp->valuelen,
&sbp->name[sbp->namelen]);
if (error)
return error;
if (context->seen_enough)
break;
cursor->offset++;
}
kmem_free(sbuf);
return(0);
}
STATIC int
xfs_attr_node_list(xfs_attr_list_context_t *context)
{
attrlist_cursor_kern_t *cursor;
xfs_attr_leafblock_t *leaf;
xfs_da_intnode_t *node;
struct xfs_attr3_icleaf_hdr leafhdr;
struct xfs_da3_icnode_hdr nodehdr;
struct xfs_da_node_entry *btree;
int error, i;
struct xfs_buf *bp;
struct xfs_inode *dp = context->dp;
trace_xfs_attr_node_list(context);
cursor = context->cursor;
cursor->initted = 1;
/*
* Do all sorts of validation on the passed-in cursor structure.
* If anything is amiss, ignore the cursor and look up the hashval
* starting from the btree root.
*/
bp = NULL;
if (cursor->blkno > 0) {
error = xfs_da3_node_read(NULL, dp, cursor->blkno, -1,
&bp, XFS_ATTR_FORK);
if ((error != 0) && (error != EFSCORRUPTED))
return(error);
if (bp) {
struct xfs_attr_leaf_entry *entries;
node = bp->b_addr;
switch (be16_to_cpu(node->hdr.info.magic)) {
case XFS_DA_NODE_MAGIC:
case XFS_DA3_NODE_MAGIC:
trace_xfs_attr_list_wrong_blk(context);
xfs_trans_brelse(NULL, bp);
bp = NULL;
break;
case XFS_ATTR_LEAF_MAGIC:
case XFS_ATTR3_LEAF_MAGIC:
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&leafhdr, leaf);
entries = xfs_attr3_leaf_entryp(leaf);
if (cursor->hashval > be32_to_cpu(
entries[leafhdr.count - 1].hashval)) {
trace_xfs_attr_list_wrong_blk(context);
xfs_trans_brelse(NULL, bp);
bp = NULL;
} else if (cursor->hashval <= be32_to_cpu(
entries[0].hashval)) {
trace_xfs_attr_list_wrong_blk(context);
xfs_trans_brelse(NULL, bp);
bp = NULL;
}
break;
default:
trace_xfs_attr_list_wrong_blk(context);
xfs_trans_brelse(NULL, bp);
bp = NULL;
}
}
}
/*
* We did not find what we expected given the cursor's contents,
* so we start from the top and work down based on the hash value.
* Note that start of node block is same as start of leaf block.
*/
if (bp == NULL) {
cursor->blkno = 0;
for (;;) {
__uint16_t magic;
error = xfs_da3_node_read(NULL, dp,
cursor->blkno, -1, &bp,
XFS_ATTR_FORK);
if (error)
return(error);
node = bp->b_addr;
magic = be16_to_cpu(node->hdr.info.magic);
if (magic == XFS_ATTR_LEAF_MAGIC ||
magic == XFS_ATTR3_LEAF_MAGIC)
break;
if (magic != XFS_DA_NODE_MAGIC &&
magic != XFS_DA3_NODE_MAGIC) {
XFS_CORRUPTION_ERROR("xfs_attr_node_list(3)",
XFS_ERRLEVEL_LOW,
context->dp->i_mount,
node);
xfs_trans_brelse(NULL, bp);
return XFS_ERROR(EFSCORRUPTED);
}
dp->d_ops->node_hdr_from_disk(&nodehdr, node);
btree = dp->d_ops->node_tree_p(node);
for (i = 0; i < nodehdr.count; btree++, i++) {
if (cursor->hashval
<= be32_to_cpu(btree->hashval)) {
cursor->blkno = be32_to_cpu(btree->before);
trace_xfs_attr_list_node_descend(context,
btree);
break;
}
}
if (i == nodehdr.count) {
xfs_trans_brelse(NULL, bp);
return 0;
}
xfs_trans_brelse(NULL, bp);
}
}
ASSERT(bp != NULL);
/*
* Roll upward through the blocks, processing each leaf block in
* order. As long as there is space in the result buffer, keep
* adding the information.
*/
for (;;) {
leaf = bp->b_addr;
error = xfs_attr3_leaf_list_int(bp, context);
if (error) {
xfs_trans_brelse(NULL, bp);
return error;
}
xfs_attr3_leaf_hdr_from_disk(&leafhdr, leaf);
if (context->seen_enough || leafhdr.forw == 0)
break;
cursor->blkno = leafhdr.forw;
xfs_trans_brelse(NULL, bp);
error = xfs_attr3_leaf_read(NULL, dp, cursor->blkno, -1, &bp);
if (error)
return error;
}
xfs_trans_brelse(NULL, bp);
return 0;
}
/*
* Copy out attribute list entries for attr_list(), for leaf attribute lists.
*/
int
xfs_attr3_leaf_list_int(
struct xfs_buf *bp,
struct xfs_attr_list_context *context)
{
struct attrlist_cursor_kern *cursor;
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entries;
struct xfs_attr_leaf_entry *entry;
int retval;
int i;
trace_xfs_attr_list_leaf(context);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
entries = xfs_attr3_leaf_entryp(leaf);
cursor = context->cursor;
cursor->initted = 1;
/*
* Re-find our place in the leaf block if this is a new syscall.
*/
if (context->resynch) {
entry = &entries[0];
for (i = 0; i < ichdr.count; entry++, i++) {
if (be32_to_cpu(entry->hashval) == cursor->hashval) {
if (cursor->offset == context->dupcnt) {
context->dupcnt = 0;
break;
}
context->dupcnt++;
} else if (be32_to_cpu(entry->hashval) >
cursor->hashval) {
context->dupcnt = 0;
break;
}
}
if (i == ichdr.count) {
trace_xfs_attr_list_notfound(context);
return 0;
}
} else {
entry = &entries[0];
i = 0;
}
context->resynch = 0;
/*
* We have found our place, start copying out the new attributes.
*/
retval = 0;
for (; i < ichdr.count; entry++, i++) {
if (be32_to_cpu(entry->hashval) != cursor->hashval) {
cursor->hashval = be32_to_cpu(entry->hashval);
cursor->offset = 0;
}
if (entry->flags & XFS_ATTR_INCOMPLETE)
continue; /* skip incomplete entries */
if (entry->flags & XFS_ATTR_LOCAL) {
xfs_attr_leaf_name_local_t *name_loc =
xfs_attr3_leaf_name_local(leaf, i);
retval = context->put_listent(context,
entry->flags,
name_loc->nameval,
(int)name_loc->namelen,
be16_to_cpu(name_loc->valuelen),
&name_loc->nameval[name_loc->namelen]);
if (retval)
return retval;
} else {
xfs_attr_leaf_name_remote_t *name_rmt =
xfs_attr3_leaf_name_remote(leaf, i);
int valuelen = be32_to_cpu(name_rmt->valuelen);
if (context->put_value) {
xfs_da_args_t args;
memset((char *)&args, 0, sizeof(args));
args.dp = context->dp;
args.whichfork = XFS_ATTR_FORK;
args.valuelen = valuelen;
args.value = kmem_alloc(valuelen, KM_SLEEP | KM_NOFS);
args.rmtblkno = be32_to_cpu(name_rmt->valueblk);
args.rmtblkcnt = xfs_attr3_rmt_blocks(
args.dp->i_mount, valuelen);
retval = xfs_attr_rmtval_get(&args);
if (retval)
return retval;
retval = context->put_listent(context,
entry->flags,
name_rmt->name,
(int)name_rmt->namelen,
valuelen,
args.value);
kmem_free(args.value);
} else {
retval = context->put_listent(context,
entry->flags,
name_rmt->name,
(int)name_rmt->namelen,
valuelen,
NULL);
}
if (retval)
return retval;
}
if (context->seen_enough)
break;
cursor->offset++;
}
trace_xfs_attr_list_leaf_end(context);
return retval;
}
/*
* Copy out attribute entries for attr_list(), for leaf attribute lists.
*/
STATIC int
xfs_attr_leaf_list(xfs_attr_list_context_t *context)
{
int error;
struct xfs_buf *bp;
trace_xfs_attr_leaf_list(context);
context->cursor->blkno = 0;
error = xfs_attr3_leaf_read(NULL, context->dp, 0, -1, &bp);
if (error)
return XFS_ERROR(error);
error = xfs_attr3_leaf_list_int(bp, context);
xfs_trans_brelse(NULL, bp);
return XFS_ERROR(error);
}
int
xfs_attr_list_int(
xfs_attr_list_context_t *context)
{
int error;
xfs_inode_t *dp = context->dp;
uint lock_mode;
XFS_STATS_INC(xs_attr_list);
if (XFS_FORCED_SHUTDOWN(dp->i_mount))
return EIO;
/*
* Decide on what work routines to call based on the inode size.
*/
lock_mode = xfs_ilock_attr_map_shared(dp);
if (!xfs_inode_hasattr(dp)) {
error = 0;
} else if (dp->i_d.di_aformat == XFS_DINODE_FMT_LOCAL) {
error = xfs_attr_shortform_list(context);
} else if (xfs_bmap_one_block(dp, XFS_ATTR_FORK)) {
error = xfs_attr_leaf_list(context);
} else {
error = xfs_attr_node_list(context);
}
xfs_iunlock(dp, lock_mode);
return error;
}
#define ATTR_ENTBASESIZE /* minimum bytes used by an attr */ \
(((struct attrlist_ent *) 0)->a_name - (char *) 0)
#define ATTR_ENTSIZE(namelen) /* actual bytes used by an attr */ \
((ATTR_ENTBASESIZE + (namelen) + 1 + sizeof(u_int32_t)-1) \
& ~(sizeof(u_int32_t)-1))
/*
* Format an attribute and copy it out to the user's buffer.
* Take care to check values and protect against them changing later,
* we may be reading them directly out of a user buffer.
*/
STATIC int
xfs_attr_put_listent(
xfs_attr_list_context_t *context,
int flags,
unsigned char *name,
int namelen,
int valuelen,
unsigned char *value)
{
struct attrlist *alist = (struct attrlist *)context->alist;
attrlist_ent_t *aep;
int arraytop;
ASSERT(!(context->flags & ATTR_KERNOVAL));
ASSERT(context->count >= 0);
ASSERT(context->count < (ATTR_MAX_VALUELEN/8));
ASSERT(context->firstu >= sizeof(*alist));
ASSERT(context->firstu <= context->bufsize);
/*
* Only list entries in the right namespace.
*/
if (((context->flags & ATTR_SECURE) == 0) !=
((flags & XFS_ATTR_SECURE) == 0))
return 0;
if (((context->flags & ATTR_ROOT) == 0) !=
((flags & XFS_ATTR_ROOT) == 0))
return 0;
arraytop = sizeof(*alist) +
context->count * sizeof(alist->al_offset[0]);
context->firstu -= ATTR_ENTSIZE(namelen);
if (context->firstu < arraytop) {
trace_xfs_attr_list_full(context);
alist->al_more = 1;
context->seen_enough = 1;
return 1;
}
aep = (attrlist_ent_t *)&context->alist[context->firstu];
aep->a_valuelen = valuelen;
memcpy(aep->a_name, name, namelen);
aep->a_name[namelen] = 0;
alist->al_offset[context->count++] = context->firstu;
alist->al_count = context->count;
trace_xfs_attr_list_add(context);
return 0;
}
/*
* Generate a list of extended attribute names and optionally
* also value lengths. Positive return value follows the XFS
* convention of being an error, zero or negative return code
* is the length of the buffer returned (negated), indicating
* success.
*/
int
xfs_attr_list(
xfs_inode_t *dp,
char *buffer,
int bufsize,
int flags,
attrlist_cursor_kern_t *cursor)
{
xfs_attr_list_context_t context;
struct attrlist *alist;
int error;
/*
* Validate the cursor.
*/
if (cursor->pad1 || cursor->pad2)
return(XFS_ERROR(EINVAL));
if ((cursor->initted == 0) &&
(cursor->hashval || cursor->blkno || cursor->offset))
return XFS_ERROR(EINVAL);
/*
* Check for a properly aligned buffer.
*/
if (((long)buffer) & (sizeof(int)-1))
return XFS_ERROR(EFAULT);
if (flags & ATTR_KERNOVAL)
bufsize = 0;
/*
* Initialize the output buffer.
*/
memset(&context, 0, sizeof(context));
context.dp = dp;
context.cursor = cursor;
context.resynch = 1;
context.flags = flags;
context.alist = buffer;
context.bufsize = (bufsize & ~(sizeof(int)-1)); /* align */
context.firstu = context.bufsize;
context.put_listent = xfs_attr_put_listent;
alist = (struct attrlist *)context.alist;
alist->al_count = 0;
alist->al_more = 0;
alist->al_offset[0] = context.bufsize;
error = xfs_attr_list_int(&context);
ASSERT(error >= 0);
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-19/c/bad_1453_2 |
crossvul-cpp_data_good_1843_1 | /*
* linux/fs/ext2/super.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/parser.h>
#include <linux/random.h>
#include <linux/buffer_head.h>
#include <linux/exportfs.h>
#include <linux/vfs.h>
#include <linux/seq_file.h>
#include <linux/mount.h>
#include <linux/log2.h>
#include <linux/quotaops.h>
#include <asm/uaccess.h>
#include "ext2.h"
#include "xattr.h"
#include "acl.h"
static void ext2_sync_super(struct super_block *sb,
struct ext2_super_block *es, int wait);
static int ext2_remount (struct super_block * sb, int * flags, char * data);
static int ext2_statfs (struct dentry * dentry, struct kstatfs * buf);
static int ext2_sync_fs(struct super_block *sb, int wait);
static int ext2_freeze(struct super_block *sb);
static int ext2_unfreeze(struct super_block *sb);
void ext2_error(struct super_block *sb, const char *function,
const char *fmt, ...)
{
struct va_format vaf;
va_list args;
struct ext2_sb_info *sbi = EXT2_SB(sb);
struct ext2_super_block *es = sbi->s_es;
if (!(sb->s_flags & MS_RDONLY)) {
spin_lock(&sbi->s_lock);
sbi->s_mount_state |= EXT2_ERROR_FS;
es->s_state |= cpu_to_le16(EXT2_ERROR_FS);
spin_unlock(&sbi->s_lock);
ext2_sync_super(sb, es, 1);
}
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT "EXT2-fs (%s): error: %s: %pV\n",
sb->s_id, function, &vaf);
va_end(args);
if (test_opt(sb, ERRORS_PANIC))
panic("EXT2-fs: panic from previous error\n");
if (test_opt(sb, ERRORS_RO)) {
ext2_msg(sb, KERN_CRIT,
"error: remounting filesystem read-only");
sb->s_flags |= MS_RDONLY;
}
}
void ext2_msg(struct super_block *sb, const char *prefix,
const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk("%sEXT2-fs (%s): %pV\n", prefix, sb->s_id, &vaf);
va_end(args);
}
/*
* This must be called with sbi->s_lock held.
*/
void ext2_update_dynamic_rev(struct super_block *sb)
{
struct ext2_super_block *es = EXT2_SB(sb)->s_es;
if (le32_to_cpu(es->s_rev_level) > EXT2_GOOD_OLD_REV)
return;
ext2_msg(sb, KERN_WARNING,
"warning: updating to rev %d because of "
"new feature flag, running e2fsck is recommended",
EXT2_DYNAMIC_REV);
es->s_first_ino = cpu_to_le32(EXT2_GOOD_OLD_FIRST_INO);
es->s_inode_size = cpu_to_le16(EXT2_GOOD_OLD_INODE_SIZE);
es->s_rev_level = cpu_to_le32(EXT2_DYNAMIC_REV);
/* leave es->s_feature_*compat flags alone */
/* es->s_uuid will be set by e2fsck if empty */
/*
* The rest of the superblock fields should be zero, and if not it
* means they are likely already in use, so leave them alone. We
* can leave it up to e2fsck to clean up any inconsistencies there.
*/
}
static void ext2_put_super (struct super_block * sb)
{
int db_count;
int i;
struct ext2_sb_info *sbi = EXT2_SB(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
if (sbi->s_mb_cache) {
ext2_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (!(sb->s_flags & MS_RDONLY)) {
struct ext2_super_block *es = sbi->s_es;
spin_lock(&sbi->s_lock);
es->s_state = cpu_to_le16(sbi->s_mount_state);
spin_unlock(&sbi->s_lock);
ext2_sync_super(sb, es, 1);
}
db_count = sbi->s_gdb_count;
for (i = 0; i < db_count; i++)
if (sbi->s_group_desc[i])
brelse (sbi->s_group_desc[i]);
kfree(sbi->s_group_desc);
kfree(sbi->s_debts);
percpu_counter_destroy(&sbi->s_freeblocks_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
brelse (sbi->s_sbh);
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
static struct kmem_cache * ext2_inode_cachep;
static struct inode *ext2_alloc_inode(struct super_block *sb)
{
struct ext2_inode_info *ei;
ei = kmem_cache_alloc(ext2_inode_cachep, GFP_KERNEL);
if (!ei)
return NULL;
ei->i_block_alloc_info = NULL;
ei->vfs_inode.i_version = 1;
#ifdef CONFIG_QUOTA
memset(&ei->i_dquot, 0, sizeof(ei->i_dquot));
#endif
return &ei->vfs_inode;
}
static void ext2_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(ext2_inode_cachep, EXT2_I(inode));
}
static void ext2_destroy_inode(struct inode *inode)
{
call_rcu(&inode->i_rcu, ext2_i_callback);
}
static void init_once(void *foo)
{
struct ext2_inode_info *ei = (struct ext2_inode_info *) foo;
rwlock_init(&ei->i_meta_lock);
#ifdef CONFIG_EXT2_FS_XATTR
init_rwsem(&ei->xattr_sem);
#endif
mutex_init(&ei->truncate_mutex);
#ifdef CONFIG_FS_DAX
init_rwsem(&ei->dax_sem);
#endif
inode_init_once(&ei->vfs_inode);
}
static int __init init_inodecache(void)
{
ext2_inode_cachep = kmem_cache_create("ext2_inode_cache",
sizeof(struct ext2_inode_info),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD|SLAB_ACCOUNT),
init_once);
if (ext2_inode_cachep == NULL)
return -ENOMEM;
return 0;
}
static void destroy_inodecache(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
kmem_cache_destroy(ext2_inode_cachep);
}
static int ext2_show_options(struct seq_file *seq, struct dentry *root)
{
struct super_block *sb = root->d_sb;
struct ext2_sb_info *sbi = EXT2_SB(sb);
struct ext2_super_block *es = sbi->s_es;
unsigned long def_mount_opts;
spin_lock(&sbi->s_lock);
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
if (sbi->s_sb_block != 1)
seq_printf(seq, ",sb=%lu", sbi->s_sb_block);
if (test_opt(sb, MINIX_DF))
seq_puts(seq, ",minixdf");
if (test_opt(sb, GRPID))
seq_puts(seq, ",grpid");
if (!test_opt(sb, GRPID) && (def_mount_opts & EXT2_DEFM_BSDGROUPS))
seq_puts(seq, ",nogrpid");
if (!uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT2_DEF_RESUID)) ||
le16_to_cpu(es->s_def_resuid) != EXT2_DEF_RESUID) {
seq_printf(seq, ",resuid=%u",
from_kuid_munged(&init_user_ns, sbi->s_resuid));
}
if (!gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT2_DEF_RESGID)) ||
le16_to_cpu(es->s_def_resgid) != EXT2_DEF_RESGID) {
seq_printf(seq, ",resgid=%u",
from_kgid_munged(&init_user_ns, sbi->s_resgid));
}
if (test_opt(sb, ERRORS_RO)) {
int def_errors = le16_to_cpu(es->s_errors);
if (def_errors == EXT2_ERRORS_PANIC ||
def_errors == EXT2_ERRORS_CONTINUE) {
seq_puts(seq, ",errors=remount-ro");
}
}
if (test_opt(sb, ERRORS_CONT))
seq_puts(seq, ",errors=continue");
if (test_opt(sb, ERRORS_PANIC))
seq_puts(seq, ",errors=panic");
if (test_opt(sb, NO_UID32))
seq_puts(seq, ",nouid32");
if (test_opt(sb, DEBUG))
seq_puts(seq, ",debug");
if (test_opt(sb, OLDALLOC))
seq_puts(seq, ",oldalloc");
#ifdef CONFIG_EXT2_FS_XATTR
if (test_opt(sb, XATTR_USER))
seq_puts(seq, ",user_xattr");
if (!test_opt(sb, XATTR_USER) &&
(def_mount_opts & EXT2_DEFM_XATTR_USER)) {
seq_puts(seq, ",nouser_xattr");
}
#endif
#ifdef CONFIG_EXT2_FS_POSIX_ACL
if (test_opt(sb, POSIX_ACL))
seq_puts(seq, ",acl");
if (!test_opt(sb, POSIX_ACL) && (def_mount_opts & EXT2_DEFM_ACL))
seq_puts(seq, ",noacl");
#endif
if (test_opt(sb, NOBH))
seq_puts(seq, ",nobh");
#if defined(CONFIG_QUOTA)
if (sbi->s_mount_opt & EXT2_MOUNT_USRQUOTA)
seq_puts(seq, ",usrquota");
if (sbi->s_mount_opt & EXT2_MOUNT_GRPQUOTA)
seq_puts(seq, ",grpquota");
#endif
#ifdef CONFIG_FS_DAX
if (sbi->s_mount_opt & EXT2_MOUNT_XIP)
seq_puts(seq, ",xip");
if (sbi->s_mount_opt & EXT2_MOUNT_DAX)
seq_puts(seq, ",dax");
#endif
if (!test_opt(sb, RESERVATION))
seq_puts(seq, ",noreservation");
spin_unlock(&sbi->s_lock);
return 0;
}
#ifdef CONFIG_QUOTA
static ssize_t ext2_quota_read(struct super_block *sb, int type, char *data, size_t len, loff_t off);
static ssize_t ext2_quota_write(struct super_block *sb, int type, const char *data, size_t len, loff_t off);
static struct dquot **ext2_get_dquots(struct inode *inode)
{
return EXT2_I(inode)->i_dquot;
}
#endif
static const struct super_operations ext2_sops = {
.alloc_inode = ext2_alloc_inode,
.destroy_inode = ext2_destroy_inode,
.write_inode = ext2_write_inode,
.evict_inode = ext2_evict_inode,
.put_super = ext2_put_super,
.sync_fs = ext2_sync_fs,
.freeze_fs = ext2_freeze,
.unfreeze_fs = ext2_unfreeze,
.statfs = ext2_statfs,
.remount_fs = ext2_remount,
.show_options = ext2_show_options,
#ifdef CONFIG_QUOTA
.quota_read = ext2_quota_read,
.quota_write = ext2_quota_write,
.get_dquots = ext2_get_dquots,
#endif
};
static struct inode *ext2_nfs_get_inode(struct super_block *sb,
u64 ino, u32 generation)
{
struct inode *inode;
if (ino < EXT2_FIRST_INO(sb) && ino != EXT2_ROOT_INO)
return ERR_PTR(-ESTALE);
if (ino > le32_to_cpu(EXT2_SB(sb)->s_es->s_inodes_count))
return ERR_PTR(-ESTALE);
/*
* ext2_iget isn't quite right if the inode is currently unallocated!
* However ext2_iget currently does appropriate checks to handle stale
* inodes so everything is OK.
*/
inode = ext2_iget(sb, ino);
if (IS_ERR(inode))
return ERR_CAST(inode);
if (generation && inode->i_generation != generation) {
/* we didn't find the right inode.. */
iput(inode);
return ERR_PTR(-ESTALE);
}
return inode;
}
static struct dentry *ext2_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
ext2_nfs_get_inode);
}
static struct dentry *ext2_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_parent(sb, fid, fh_len, fh_type,
ext2_nfs_get_inode);
}
static const struct export_operations ext2_export_ops = {
.fh_to_dentry = ext2_fh_to_dentry,
.fh_to_parent = ext2_fh_to_parent,
.get_parent = ext2_get_parent,
};
static unsigned long get_sb_block(void **data)
{
unsigned long sb_block;
char *options = (char *) *data;
if (!options || strncmp(options, "sb=", 3) != 0)
return 1; /* Default location */
options += 3;
sb_block = simple_strtoul(options, &options, 0);
if (*options && *options != ',') {
printk("EXT2-fs: Invalid sb specification: %s\n",
(char *) *data);
return 1;
}
if (*options == ',')
options++;
*data = (void *) options;
return sb_block;
}
enum {
Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid,
Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic,
Opt_err_ro, Opt_nouid32, Opt_nocheck, Opt_debug,
Opt_oldalloc, Opt_orlov, Opt_nobh, Opt_user_xattr, Opt_nouser_xattr,
Opt_acl, Opt_noacl, Opt_xip, Opt_dax, Opt_ignore, Opt_err, Opt_quota,
Opt_usrquota, Opt_grpquota, Opt_reservation, Opt_noreservation
};
static const match_table_t tokens = {
{Opt_bsd_df, "bsddf"},
{Opt_minix_df, "minixdf"},
{Opt_grpid, "grpid"},
{Opt_grpid, "bsdgroups"},
{Opt_nogrpid, "nogrpid"},
{Opt_nogrpid, "sysvgroups"},
{Opt_resgid, "resgid=%u"},
{Opt_resuid, "resuid=%u"},
{Opt_sb, "sb=%u"},
{Opt_err_cont, "errors=continue"},
{Opt_err_panic, "errors=panic"},
{Opt_err_ro, "errors=remount-ro"},
{Opt_nouid32, "nouid32"},
{Opt_nocheck, "check=none"},
{Opt_nocheck, "nocheck"},
{Opt_debug, "debug"},
{Opt_oldalloc, "oldalloc"},
{Opt_orlov, "orlov"},
{Opt_nobh, "nobh"},
{Opt_user_xattr, "user_xattr"},
{Opt_nouser_xattr, "nouser_xattr"},
{Opt_acl, "acl"},
{Opt_noacl, "noacl"},
{Opt_xip, "xip"},
{Opt_dax, "dax"},
{Opt_grpquota, "grpquota"},
{Opt_ignore, "noquota"},
{Opt_quota, "quota"},
{Opt_usrquota, "usrquota"},
{Opt_reservation, "reservation"},
{Opt_noreservation, "noreservation"},
{Opt_err, NULL}
};
static int parse_options(char *options, struct super_block *sb)
{
char *p;
struct ext2_sb_info *sbi = EXT2_SB(sb);
substring_t args[MAX_OPT_ARGS];
int option;
kuid_t uid;
kgid_t gid;
if (!options)
return 1;
while ((p = strsep (&options, ",")) != NULL) {
int token;
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case Opt_bsd_df:
clear_opt (sbi->s_mount_opt, MINIX_DF);
break;
case Opt_minix_df:
set_opt (sbi->s_mount_opt, MINIX_DF);
break;
case Opt_grpid:
set_opt (sbi->s_mount_opt, GRPID);
break;
case Opt_nogrpid:
clear_opt (sbi->s_mount_opt, GRPID);
break;
case Opt_resuid:
if (match_int(&args[0], &option))
return 0;
uid = make_kuid(current_user_ns(), option);
if (!uid_valid(uid)) {
ext2_msg(sb, KERN_ERR, "Invalid uid value %d", option);
return 0;
}
sbi->s_resuid = uid;
break;
case Opt_resgid:
if (match_int(&args[0], &option))
return 0;
gid = make_kgid(current_user_ns(), option);
if (!gid_valid(gid)) {
ext2_msg(sb, KERN_ERR, "Invalid gid value %d", option);
return 0;
}
sbi->s_resgid = gid;
break;
case Opt_sb:
/* handled by get_sb_block() instead of here */
/* *sb_block = match_int(&args[0]); */
break;
case Opt_err_panic:
clear_opt (sbi->s_mount_opt, ERRORS_CONT);
clear_opt (sbi->s_mount_opt, ERRORS_RO);
set_opt (sbi->s_mount_opt, ERRORS_PANIC);
break;
case Opt_err_ro:
clear_opt (sbi->s_mount_opt, ERRORS_CONT);
clear_opt (sbi->s_mount_opt, ERRORS_PANIC);
set_opt (sbi->s_mount_opt, ERRORS_RO);
break;
case Opt_err_cont:
clear_opt (sbi->s_mount_opt, ERRORS_RO);
clear_opt (sbi->s_mount_opt, ERRORS_PANIC);
set_opt (sbi->s_mount_opt, ERRORS_CONT);
break;
case Opt_nouid32:
set_opt (sbi->s_mount_opt, NO_UID32);
break;
case Opt_nocheck:
clear_opt (sbi->s_mount_opt, CHECK);
break;
case Opt_debug:
set_opt (sbi->s_mount_opt, DEBUG);
break;
case Opt_oldalloc:
set_opt (sbi->s_mount_opt, OLDALLOC);
break;
case Opt_orlov:
clear_opt (sbi->s_mount_opt, OLDALLOC);
break;
case Opt_nobh:
set_opt (sbi->s_mount_opt, NOBH);
break;
#ifdef CONFIG_EXT2_FS_XATTR
case Opt_user_xattr:
set_opt (sbi->s_mount_opt, XATTR_USER);
break;
case Opt_nouser_xattr:
clear_opt (sbi->s_mount_opt, XATTR_USER);
break;
#else
case Opt_user_xattr:
case Opt_nouser_xattr:
ext2_msg(sb, KERN_INFO, "(no)user_xattr options"
"not supported");
break;
#endif
#ifdef CONFIG_EXT2_FS_POSIX_ACL
case Opt_acl:
set_opt(sbi->s_mount_opt, POSIX_ACL);
break;
case Opt_noacl:
clear_opt(sbi->s_mount_opt, POSIX_ACL);
break;
#else
case Opt_acl:
case Opt_noacl:
ext2_msg(sb, KERN_INFO,
"(no)acl options not supported");
break;
#endif
case Opt_xip:
ext2_msg(sb, KERN_INFO, "use dax instead of xip");
set_opt(sbi->s_mount_opt, XIP);
/* Fall through */
case Opt_dax:
#ifdef CONFIG_FS_DAX
ext2_msg(sb, KERN_WARNING,
"DAX enabled. Warning: EXPERIMENTAL, use at your own risk");
set_opt(sbi->s_mount_opt, DAX);
#else
ext2_msg(sb, KERN_INFO, "dax option not supported");
#endif
break;
#if defined(CONFIG_QUOTA)
case Opt_quota:
case Opt_usrquota:
set_opt(sbi->s_mount_opt, USRQUOTA);
break;
case Opt_grpquota:
set_opt(sbi->s_mount_opt, GRPQUOTA);
break;
#else
case Opt_quota:
case Opt_usrquota:
case Opt_grpquota:
ext2_msg(sb, KERN_INFO,
"quota operations not supported");
break;
#endif
case Opt_reservation:
set_opt(sbi->s_mount_opt, RESERVATION);
ext2_msg(sb, KERN_INFO, "reservations ON");
break;
case Opt_noreservation:
clear_opt(sbi->s_mount_opt, RESERVATION);
ext2_msg(sb, KERN_INFO, "reservations OFF");
break;
case Opt_ignore:
break;
default:
return 0;
}
}
return 1;
}
static int ext2_setup_super (struct super_block * sb,
struct ext2_super_block * es,
int read_only)
{
int res = 0;
struct ext2_sb_info *sbi = EXT2_SB(sb);
if (le32_to_cpu(es->s_rev_level) > EXT2_MAX_SUPP_REV) {
ext2_msg(sb, KERN_ERR,
"error: revision level too high, "
"forcing read-only mode");
res = MS_RDONLY;
}
if (read_only)
return res;
if (!(sbi->s_mount_state & EXT2_VALID_FS))
ext2_msg(sb, KERN_WARNING,
"warning: mounting unchecked fs, "
"running e2fsck is recommended");
else if ((sbi->s_mount_state & EXT2_ERROR_FS))
ext2_msg(sb, KERN_WARNING,
"warning: mounting fs with errors, "
"running e2fsck is recommended");
else if ((__s16) le16_to_cpu(es->s_max_mnt_count) >= 0 &&
le16_to_cpu(es->s_mnt_count) >=
(unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count))
ext2_msg(sb, KERN_WARNING,
"warning: maximal mount count reached, "
"running e2fsck is recommended");
else if (le32_to_cpu(es->s_checkinterval) &&
(le32_to_cpu(es->s_lastcheck) +
le32_to_cpu(es->s_checkinterval) <= get_seconds()))
ext2_msg(sb, KERN_WARNING,
"warning: checktime reached, "
"running e2fsck is recommended");
if (!le16_to_cpu(es->s_max_mnt_count))
es->s_max_mnt_count = cpu_to_le16(EXT2_DFL_MAX_MNT_COUNT);
le16_add_cpu(&es->s_mnt_count, 1);
if (test_opt (sb, DEBUG))
ext2_msg(sb, KERN_INFO, "%s, %s, bs=%lu, fs=%lu, gc=%lu, "
"bpg=%lu, ipg=%lu, mo=%04lx]",
EXT2FS_VERSION, EXT2FS_DATE, sb->s_blocksize,
sbi->s_frag_size,
sbi->s_groups_count,
EXT2_BLOCKS_PER_GROUP(sb),
EXT2_INODES_PER_GROUP(sb),
sbi->s_mount_opt);
return res;
}
static int ext2_check_descriptors(struct super_block *sb)
{
int i;
struct ext2_sb_info *sbi = EXT2_SB(sb);
ext2_debug ("Checking group descriptors");
for (i = 0; i < sbi->s_groups_count; i++) {
struct ext2_group_desc *gdp = ext2_get_group_desc(sb, i, NULL);
ext2_fsblk_t first_block = ext2_group_first_block_no(sb, i);
ext2_fsblk_t last_block;
if (i == sbi->s_groups_count - 1)
last_block = le32_to_cpu(sbi->s_es->s_blocks_count) - 1;
else
last_block = first_block +
(EXT2_BLOCKS_PER_GROUP(sb) - 1);
if (le32_to_cpu(gdp->bg_block_bitmap) < first_block ||
le32_to_cpu(gdp->bg_block_bitmap) > last_block)
{
ext2_error (sb, "ext2_check_descriptors",
"Block bitmap for group %d"
" not in group (block %lu)!",
i, (unsigned long) le32_to_cpu(gdp->bg_block_bitmap));
return 0;
}
if (le32_to_cpu(gdp->bg_inode_bitmap) < first_block ||
le32_to_cpu(gdp->bg_inode_bitmap) > last_block)
{
ext2_error (sb, "ext2_check_descriptors",
"Inode bitmap for group %d"
" not in group (block %lu)!",
i, (unsigned long) le32_to_cpu(gdp->bg_inode_bitmap));
return 0;
}
if (le32_to_cpu(gdp->bg_inode_table) < first_block ||
le32_to_cpu(gdp->bg_inode_table) + sbi->s_itb_per_group - 1 >
last_block)
{
ext2_error (sb, "ext2_check_descriptors",
"Inode table for group %d"
" not in group (block %lu)!",
i, (unsigned long) le32_to_cpu(gdp->bg_inode_table));
return 0;
}
}
return 1;
}
/*
* Maximal file size. There is a direct, and {,double-,triple-}indirect
* block limit, and also a limit of (2^32 - 1) 512-byte sectors in i_blocks.
* We need to be 1 filesystem block less than the 2^32 sector limit.
*/
static loff_t ext2_max_size(int bits)
{
loff_t res = EXT2_NDIR_BLOCKS;
int meta_blocks;
loff_t upper_limit;
/* This is calculated to be the largest file size for a
* dense, file such that the total number of
* sectors in the file, including data and all indirect blocks,
* does not exceed 2^32 -1
* __u32 i_blocks representing the total number of
* 512 bytes blocks of the file
*/
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (bits - 9);
/* indirect blocks */
meta_blocks = 1;
/* double indirect blocks */
meta_blocks += 1 + (1LL << (bits-2));
/* tripple indirect blocks */
meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2)));
upper_limit -= meta_blocks;
upper_limit <<= bits;
res += 1LL << (bits-2);
res += 1LL << (2*(bits-2));
res += 1LL << (3*(bits-2));
res <<= bits;
if (res > upper_limit)
res = upper_limit;
if (res > MAX_LFS_FILESIZE)
res = MAX_LFS_FILESIZE;
return res;
}
static unsigned long descriptor_loc(struct super_block *sb,
unsigned long logic_sb_block,
int nr)
{
struct ext2_sb_info *sbi = EXT2_SB(sb);
unsigned long bg, first_meta_bg;
int has_super = 0;
first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
if (!EXT2_HAS_INCOMPAT_FEATURE(sb, EXT2_FEATURE_INCOMPAT_META_BG) ||
nr < first_meta_bg)
return (logic_sb_block + nr + 1);
bg = sbi->s_desc_per_block * nr;
if (ext2_bg_has_super(sb, bg))
has_super = 1;
return ext2_group_first_block_no(sb, bg) + has_super;
}
static int ext2_fill_super(struct super_block *sb, void *data, int silent)
{
struct buffer_head * bh;
struct ext2_sb_info * sbi;
struct ext2_super_block * es;
struct inode *root;
unsigned long block;
unsigned long sb_block = get_sb_block(&data);
unsigned long logic_sb_block;
unsigned long offset = 0;
unsigned long def_mount_opts;
long ret = -EINVAL;
int blocksize = BLOCK_SIZE;
int db_count;
int i, j;
__le32 features;
int err;
err = -ENOMEM;
sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
if (!sbi)
goto failed;
sbi->s_blockgroup_lock =
kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
if (!sbi->s_blockgroup_lock) {
kfree(sbi);
goto failed;
}
sb->s_fs_info = sbi;
sbi->s_sb_block = sb_block;
spin_lock_init(&sbi->s_lock);
/*
* See what the current blocksize for the device is, and
* use that as the blocksize. Otherwise (or if the blocksize
* is smaller than the default) use the default.
* This is important for devices that have a hardware
* sectorsize that is larger than the default.
*/
blocksize = sb_min_blocksize(sb, BLOCK_SIZE);
if (!blocksize) {
ext2_msg(sb, KERN_ERR, "error: unable to set blocksize");
goto failed_sbi;
}
/*
* If the superblock doesn't start on a hardware sector boundary,
* calculate the offset.
*/
if (blocksize != BLOCK_SIZE) {
logic_sb_block = (sb_block*BLOCK_SIZE) / blocksize;
offset = (sb_block*BLOCK_SIZE) % blocksize;
} else {
logic_sb_block = sb_block;
}
if (!(bh = sb_bread(sb, logic_sb_block))) {
ext2_msg(sb, KERN_ERR, "error: unable to read superblock");
goto failed_sbi;
}
/*
* Note: s_es must be initialized as soon as possible because
* some ext2 macro-instructions depend on its value
*/
es = (struct ext2_super_block *) (((char *)bh->b_data) + offset);
sbi->s_es = es;
sb->s_magic = le16_to_cpu(es->s_magic);
if (sb->s_magic != EXT2_SUPER_MAGIC)
goto cantfind_ext2;
/* Set defaults before we parse the mount options */
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
if (def_mount_opts & EXT2_DEFM_DEBUG)
set_opt(sbi->s_mount_opt, DEBUG);
if (def_mount_opts & EXT2_DEFM_BSDGROUPS)
set_opt(sbi->s_mount_opt, GRPID);
if (def_mount_opts & EXT2_DEFM_UID16)
set_opt(sbi->s_mount_opt, NO_UID32);
#ifdef CONFIG_EXT2_FS_XATTR
if (def_mount_opts & EXT2_DEFM_XATTR_USER)
set_opt(sbi->s_mount_opt, XATTR_USER);
#endif
#ifdef CONFIG_EXT2_FS_POSIX_ACL
if (def_mount_opts & EXT2_DEFM_ACL)
set_opt(sbi->s_mount_opt, POSIX_ACL);
#endif
if (le16_to_cpu(sbi->s_es->s_errors) == EXT2_ERRORS_PANIC)
set_opt(sbi->s_mount_opt, ERRORS_PANIC);
else if (le16_to_cpu(sbi->s_es->s_errors) == EXT2_ERRORS_CONTINUE)
set_opt(sbi->s_mount_opt, ERRORS_CONT);
else
set_opt(sbi->s_mount_opt, ERRORS_RO);
sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));
sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));
set_opt(sbi->s_mount_opt, RESERVATION);
if (!parse_options((char *) data, sb))
goto failed_mount;
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
((EXT2_SB(sb)->s_mount_opt & EXT2_MOUNT_POSIX_ACL) ?
MS_POSIXACL : 0);
sb->s_iflags |= SB_I_CGROUPWB;
if (le32_to_cpu(es->s_rev_level) == EXT2_GOOD_OLD_REV &&
(EXT2_HAS_COMPAT_FEATURE(sb, ~0U) ||
EXT2_HAS_RO_COMPAT_FEATURE(sb, ~0U) ||
EXT2_HAS_INCOMPAT_FEATURE(sb, ~0U)))
ext2_msg(sb, KERN_WARNING,
"warning: feature flags set on rev 0 fs, "
"running e2fsck is recommended");
/*
* Check feature flags regardless of the revision level, since we
* previously didn't change the revision level when setting the flags,
* so there is a chance incompat flags are set on a rev 0 filesystem.
*/
features = EXT2_HAS_INCOMPAT_FEATURE(sb, ~EXT2_FEATURE_INCOMPAT_SUPP);
if (features) {
ext2_msg(sb, KERN_ERR, "error: couldn't mount because of "
"unsupported optional features (%x)",
le32_to_cpu(features));
goto failed_mount;
}
if (!(sb->s_flags & MS_RDONLY) &&
(features = EXT2_HAS_RO_COMPAT_FEATURE(sb, ~EXT2_FEATURE_RO_COMPAT_SUPP))){
ext2_msg(sb, KERN_ERR, "error: couldn't mount RDWR because of "
"unsupported optional features (%x)",
le32_to_cpu(features));
goto failed_mount;
}
blocksize = BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);
if (sbi->s_mount_opt & EXT2_MOUNT_DAX) {
if (blocksize != PAGE_SIZE) {
ext2_msg(sb, KERN_ERR,
"error: unsupported blocksize for dax");
goto failed_mount;
}
if (!sb->s_bdev->bd_disk->fops->direct_access) {
ext2_msg(sb, KERN_ERR,
"error: device does not support dax");
goto failed_mount;
}
}
/* If the blocksize doesn't match, re-read the thing.. */
if (sb->s_blocksize != blocksize) {
brelse(bh);
if (!sb_set_blocksize(sb, blocksize)) {
ext2_msg(sb, KERN_ERR,
"error: bad blocksize %d", blocksize);
goto failed_sbi;
}
logic_sb_block = (sb_block*BLOCK_SIZE) / blocksize;
offset = (sb_block*BLOCK_SIZE) % blocksize;
bh = sb_bread(sb, logic_sb_block);
if(!bh) {
ext2_msg(sb, KERN_ERR, "error: couldn't read"
"superblock on 2nd try");
goto failed_sbi;
}
es = (struct ext2_super_block *) (((char *)bh->b_data) + offset);
sbi->s_es = es;
if (es->s_magic != cpu_to_le16(EXT2_SUPER_MAGIC)) {
ext2_msg(sb, KERN_ERR, "error: magic mismatch");
goto failed_mount;
}
}
sb->s_maxbytes = ext2_max_size(sb->s_blocksize_bits);
sb->s_max_links = EXT2_LINK_MAX;
if (le32_to_cpu(es->s_rev_level) == EXT2_GOOD_OLD_REV) {
sbi->s_inode_size = EXT2_GOOD_OLD_INODE_SIZE;
sbi->s_first_ino = EXT2_GOOD_OLD_FIRST_INO;
} else {
sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
if ((sbi->s_inode_size < EXT2_GOOD_OLD_INODE_SIZE) ||
!is_power_of_2(sbi->s_inode_size) ||
(sbi->s_inode_size > blocksize)) {
ext2_msg(sb, KERN_ERR,
"error: unsupported inode size: %d",
sbi->s_inode_size);
goto failed_mount;
}
}
sbi->s_frag_size = EXT2_MIN_FRAG_SIZE <<
le32_to_cpu(es->s_log_frag_size);
if (sbi->s_frag_size == 0)
goto cantfind_ext2;
sbi->s_frags_per_block = sb->s_blocksize / sbi->s_frag_size;
sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
sbi->s_frags_per_group = le32_to_cpu(es->s_frags_per_group);
sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
if (EXT2_INODE_SIZE(sb) == 0)
goto cantfind_ext2;
sbi->s_inodes_per_block = sb->s_blocksize / EXT2_INODE_SIZE(sb);
if (sbi->s_inodes_per_block == 0 || sbi->s_inodes_per_group == 0)
goto cantfind_ext2;
sbi->s_itb_per_group = sbi->s_inodes_per_group /
sbi->s_inodes_per_block;
sbi->s_desc_per_block = sb->s_blocksize /
sizeof (struct ext2_group_desc);
sbi->s_sbh = bh;
sbi->s_mount_state = le16_to_cpu(es->s_state);
sbi->s_addr_per_block_bits =
ilog2 (EXT2_ADDR_PER_BLOCK(sb));
sbi->s_desc_per_block_bits =
ilog2 (EXT2_DESC_PER_BLOCK(sb));
if (sb->s_magic != EXT2_SUPER_MAGIC)
goto cantfind_ext2;
if (sb->s_blocksize != bh->b_size) {
if (!silent)
ext2_msg(sb, KERN_ERR, "error: unsupported blocksize");
goto failed_mount;
}
if (sb->s_blocksize != sbi->s_frag_size) {
ext2_msg(sb, KERN_ERR,
"error: fragsize %lu != blocksize %lu"
"(not supported yet)",
sbi->s_frag_size, sb->s_blocksize);
goto failed_mount;
}
if (sbi->s_blocks_per_group > sb->s_blocksize * 8) {
ext2_msg(sb, KERN_ERR,
"error: #blocks per group too big: %lu",
sbi->s_blocks_per_group);
goto failed_mount;
}
if (sbi->s_frags_per_group > sb->s_blocksize * 8) {
ext2_msg(sb, KERN_ERR,
"error: #fragments per group too big: %lu",
sbi->s_frags_per_group);
goto failed_mount;
}
if (sbi->s_inodes_per_group > sb->s_blocksize * 8) {
ext2_msg(sb, KERN_ERR,
"error: #inodes per group too big: %lu",
sbi->s_inodes_per_group);
goto failed_mount;
}
if (EXT2_BLOCKS_PER_GROUP(sb) == 0)
goto cantfind_ext2;
sbi->s_groups_count = ((le32_to_cpu(es->s_blocks_count) -
le32_to_cpu(es->s_first_data_block) - 1)
/ EXT2_BLOCKS_PER_GROUP(sb)) + 1;
db_count = (sbi->s_groups_count + EXT2_DESC_PER_BLOCK(sb) - 1) /
EXT2_DESC_PER_BLOCK(sb);
sbi->s_group_desc = kmalloc (db_count * sizeof (struct buffer_head *), GFP_KERNEL);
if (sbi->s_group_desc == NULL) {
ext2_msg(sb, KERN_ERR, "error: not enough memory");
goto failed_mount;
}
bgl_lock_init(sbi->s_blockgroup_lock);
sbi->s_debts = kcalloc(sbi->s_groups_count, sizeof(*sbi->s_debts), GFP_KERNEL);
if (!sbi->s_debts) {
ext2_msg(sb, KERN_ERR, "error: not enough memory");
goto failed_mount_group_desc;
}
for (i = 0; i < db_count; i++) {
block = descriptor_loc(sb, logic_sb_block, i);
sbi->s_group_desc[i] = sb_bread(sb, block);
if (!sbi->s_group_desc[i]) {
for (j = 0; j < i; j++)
brelse (sbi->s_group_desc[j]);
ext2_msg(sb, KERN_ERR,
"error: unable to read group descriptors");
goto failed_mount_group_desc;
}
}
if (!ext2_check_descriptors (sb)) {
ext2_msg(sb, KERN_ERR, "group descriptors corrupted");
goto failed_mount2;
}
sbi->s_gdb_count = db_count;
get_random_bytes(&sbi->s_next_generation, sizeof(u32));
spin_lock_init(&sbi->s_next_gen_lock);
/* per fileystem reservation list head & lock */
spin_lock_init(&sbi->s_rsv_window_lock);
sbi->s_rsv_window_root = RB_ROOT;
/*
* Add a single, static dummy reservation to the start of the
* reservation window list --- it gives us a placeholder for
* append-at-start-of-list which makes the allocation logic
* _much_ simpler.
*/
sbi->s_rsv_window_head.rsv_start = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
sbi->s_rsv_window_head.rsv_end = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
sbi->s_rsv_window_head.rsv_alloc_hit = 0;
sbi->s_rsv_window_head.rsv_goal_size = 0;
ext2_rsv_window_add(sb, &sbi->s_rsv_window_head);
err = percpu_counter_init(&sbi->s_freeblocks_counter,
ext2_count_free_blocks(sb), GFP_KERNEL);
if (!err) {
err = percpu_counter_init(&sbi->s_freeinodes_counter,
ext2_count_free_inodes(sb), GFP_KERNEL);
}
if (!err) {
err = percpu_counter_init(&sbi->s_dirs_counter,
ext2_count_dirs(sb), GFP_KERNEL);
}
if (err) {
ext2_msg(sb, KERN_ERR, "error: insufficient memory");
goto failed_mount3;
}
#ifdef CONFIG_EXT2_FS_XATTR
sbi->s_mb_cache = ext2_xattr_create_cache();
if (!sbi->s_mb_cache) {
ext2_msg(sb, KERN_ERR, "Failed to create an mb_cache");
goto failed_mount3;
}
#endif
/*
* set up enough so that it can read an inode
*/
sb->s_op = &ext2_sops;
sb->s_export_op = &ext2_export_ops;
sb->s_xattr = ext2_xattr_handlers;
#ifdef CONFIG_QUOTA
sb->dq_op = &dquot_operations;
sb->s_qcop = &dquot_quotactl_ops;
sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP;
#endif
root = ext2_iget(sb, EXT2_ROOT_INO);
if (IS_ERR(root)) {
ret = PTR_ERR(root);
goto failed_mount3;
}
if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
iput(root);
ext2_msg(sb, KERN_ERR, "error: corrupt root inode, run e2fsck");
goto failed_mount3;
}
sb->s_root = d_make_root(root);
if (!sb->s_root) {
ext2_msg(sb, KERN_ERR, "error: get root inode failed");
ret = -ENOMEM;
goto failed_mount3;
}
if (EXT2_HAS_COMPAT_FEATURE(sb, EXT3_FEATURE_COMPAT_HAS_JOURNAL))
ext2_msg(sb, KERN_WARNING,
"warning: mounting ext3 filesystem as ext2");
if (ext2_setup_super (sb, es, sb->s_flags & MS_RDONLY))
sb->s_flags |= MS_RDONLY;
ext2_write_super(sb);
return 0;
cantfind_ext2:
if (!silent)
ext2_msg(sb, KERN_ERR,
"error: can't find an ext2 filesystem on dev %s.",
sb->s_id);
goto failed_mount;
failed_mount3:
if (sbi->s_mb_cache)
ext2_xattr_destroy_cache(sbi->s_mb_cache);
percpu_counter_destroy(&sbi->s_freeblocks_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
failed_mount2:
for (i = 0; i < db_count; i++)
brelse(sbi->s_group_desc[i]);
failed_mount_group_desc:
kfree(sbi->s_group_desc);
kfree(sbi->s_debts);
failed_mount:
brelse(bh);
failed_sbi:
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
failed:
return ret;
}
static void ext2_clear_super_error(struct super_block *sb)
{
struct buffer_head *sbh = EXT2_SB(sb)->s_sbh;
if (buffer_write_io_error(sbh)) {
/*
* Oh, dear. A previous attempt to write the
* superblock failed. This could happen because the
* USB device was yanked out. Or it could happen to
* be a transient write error and maybe the block will
* be remapped. Nothing we can do but to retry the
* write and hope for the best.
*/
ext2_msg(sb, KERN_ERR,
"previous I/O error to superblock detected\n");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
}
}
static void ext2_sync_super(struct super_block *sb, struct ext2_super_block *es,
int wait)
{
ext2_clear_super_error(sb);
spin_lock(&EXT2_SB(sb)->s_lock);
es->s_free_blocks_count = cpu_to_le32(ext2_count_free_blocks(sb));
es->s_free_inodes_count = cpu_to_le32(ext2_count_free_inodes(sb));
es->s_wtime = cpu_to_le32(get_seconds());
/* unlock before we do IO */
spin_unlock(&EXT2_SB(sb)->s_lock);
mark_buffer_dirty(EXT2_SB(sb)->s_sbh);
if (wait)
sync_dirty_buffer(EXT2_SB(sb)->s_sbh);
}
/*
* In the second extended file system, it is not necessary to
* write the super block since we use a mapping of the
* disk super block in a buffer.
*
* However, this function is still used to set the fs valid
* flags to 0. We need to set this flag to 0 since the fs
* may have been checked while mounted and e2fsck may have
* set s_state to EXT2_VALID_FS after some corrections.
*/
static int ext2_sync_fs(struct super_block *sb, int wait)
{
struct ext2_sb_info *sbi = EXT2_SB(sb);
struct ext2_super_block *es = EXT2_SB(sb)->s_es;
/*
* Write quota structures to quota file, sync_blockdev() will write
* them to disk later
*/
dquot_writeback_dquots(sb, -1);
spin_lock(&sbi->s_lock);
if (es->s_state & cpu_to_le16(EXT2_VALID_FS)) {
ext2_debug("setting valid to 0\n");
es->s_state &= cpu_to_le16(~EXT2_VALID_FS);
}
spin_unlock(&sbi->s_lock);
ext2_sync_super(sb, es, wait);
return 0;
}
static int ext2_freeze(struct super_block *sb)
{
struct ext2_sb_info *sbi = EXT2_SB(sb);
/*
* Open but unlinked files present? Keep EXT2_VALID_FS flag cleared
* because we have unattached inodes and thus filesystem is not fully
* consistent.
*/
if (atomic_long_read(&sb->s_remove_count)) {
ext2_sync_fs(sb, 1);
return 0;
}
/* Set EXT2_FS_VALID flag */
spin_lock(&sbi->s_lock);
sbi->s_es->s_state = cpu_to_le16(sbi->s_mount_state);
spin_unlock(&sbi->s_lock);
ext2_sync_super(sb, sbi->s_es, 1);
return 0;
}
static int ext2_unfreeze(struct super_block *sb)
{
/* Just write sb to clear EXT2_VALID_FS flag */
ext2_write_super(sb);
return 0;
}
void ext2_write_super(struct super_block *sb)
{
if (!(sb->s_flags & MS_RDONLY))
ext2_sync_fs(sb, 1);
}
static int ext2_remount (struct super_block * sb, int * flags, char * data)
{
struct ext2_sb_info * sbi = EXT2_SB(sb);
struct ext2_super_block * es;
struct ext2_mount_options old_opts;
unsigned long old_sb_flags;
int err;
sync_filesystem(sb);
spin_lock(&sbi->s_lock);
/* Store the old options */
old_sb_flags = sb->s_flags;
old_opts.s_mount_opt = sbi->s_mount_opt;
old_opts.s_resuid = sbi->s_resuid;
old_opts.s_resgid = sbi->s_resgid;
/*
* Allow the "check" option to be passed as a remount option.
*/
if (!parse_options(data, sb)) {
err = -EINVAL;
goto restore_opts;
}
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
((sbi->s_mount_opt & EXT2_MOUNT_POSIX_ACL) ? MS_POSIXACL : 0);
es = sbi->s_es;
if ((sbi->s_mount_opt ^ old_opts.s_mount_opt) & EXT2_MOUNT_DAX) {
ext2_msg(sb, KERN_WARNING, "warning: refusing change of "
"dax flag with busy inodes while remounting");
sbi->s_mount_opt ^= EXT2_MOUNT_DAX;
}
if ((*flags & MS_RDONLY) == (sb->s_flags & MS_RDONLY)) {
spin_unlock(&sbi->s_lock);
return 0;
}
if (*flags & MS_RDONLY) {
if (le16_to_cpu(es->s_state) & EXT2_VALID_FS ||
!(sbi->s_mount_state & EXT2_VALID_FS)) {
spin_unlock(&sbi->s_lock);
return 0;
}
/*
* OK, we are remounting a valid rw partition rdonly, so set
* the rdonly flag and then mark the partition as valid again.
*/
es->s_state = cpu_to_le16(sbi->s_mount_state);
es->s_mtime = cpu_to_le32(get_seconds());
spin_unlock(&sbi->s_lock);
err = dquot_suspend(sb, -1);
if (err < 0) {
spin_lock(&sbi->s_lock);
goto restore_opts;
}
ext2_sync_super(sb, es, 1);
} else {
__le32 ret = EXT2_HAS_RO_COMPAT_FEATURE(sb,
~EXT2_FEATURE_RO_COMPAT_SUPP);
if (ret) {
ext2_msg(sb, KERN_WARNING,
"warning: couldn't remount RDWR because of "
"unsupported optional features (%x).",
le32_to_cpu(ret));
err = -EROFS;
goto restore_opts;
}
/*
* Mounting a RDONLY partition read-write, so reread and
* store the current valid flag. (It may have been changed
* by e2fsck since we originally mounted the partition.)
*/
sbi->s_mount_state = le16_to_cpu(es->s_state);
if (!ext2_setup_super (sb, es, 0))
sb->s_flags &= ~MS_RDONLY;
spin_unlock(&sbi->s_lock);
ext2_write_super(sb);
dquot_resume(sb, -1);
}
return 0;
restore_opts:
sbi->s_mount_opt = old_opts.s_mount_opt;
sbi->s_resuid = old_opts.s_resuid;
sbi->s_resgid = old_opts.s_resgid;
sb->s_flags = old_sb_flags;
spin_unlock(&sbi->s_lock);
return err;
}
static int ext2_statfs (struct dentry * dentry, struct kstatfs * buf)
{
struct super_block *sb = dentry->d_sb;
struct ext2_sb_info *sbi = EXT2_SB(sb);
struct ext2_super_block *es = sbi->s_es;
u64 fsid;
spin_lock(&sbi->s_lock);
if (test_opt (sb, MINIX_DF))
sbi->s_overhead_last = 0;
else if (sbi->s_blocks_last != le32_to_cpu(es->s_blocks_count)) {
unsigned long i, overhead = 0;
smp_rmb();
/*
* Compute the overhead (FS structures). This is constant
* for a given filesystem unless the number of block groups
* changes so we cache the previous value until it does.
*/
/*
* All of the blocks before first_data_block are
* overhead
*/
overhead = le32_to_cpu(es->s_first_data_block);
/*
* Add the overhead attributed to the superblock and
* block group descriptors. If the sparse superblocks
* feature is turned on, then not all groups have this.
*/
for (i = 0; i < sbi->s_groups_count; i++)
overhead += ext2_bg_has_super(sb, i) +
ext2_bg_num_gdb(sb, i);
/*
* Every block group has an inode bitmap, a block
* bitmap, and an inode table.
*/
overhead += (sbi->s_groups_count *
(2 + sbi->s_itb_per_group));
sbi->s_overhead_last = overhead;
smp_wmb();
sbi->s_blocks_last = le32_to_cpu(es->s_blocks_count);
}
buf->f_type = EXT2_SUPER_MAGIC;
buf->f_bsize = sb->s_blocksize;
buf->f_blocks = le32_to_cpu(es->s_blocks_count) - sbi->s_overhead_last;
buf->f_bfree = ext2_count_free_blocks(sb);
es->s_free_blocks_count = cpu_to_le32(buf->f_bfree);
buf->f_bavail = buf->f_bfree - le32_to_cpu(es->s_r_blocks_count);
if (buf->f_bfree < le32_to_cpu(es->s_r_blocks_count))
buf->f_bavail = 0;
buf->f_files = le32_to_cpu(es->s_inodes_count);
buf->f_ffree = ext2_count_free_inodes(sb);
es->s_free_inodes_count = cpu_to_le32(buf->f_ffree);
buf->f_namelen = EXT2_NAME_LEN;
fsid = le64_to_cpup((void *)es->s_uuid) ^
le64_to_cpup((void *)es->s_uuid + sizeof(u64));
buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
spin_unlock(&sbi->s_lock);
return 0;
}
static struct dentry *ext2_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_bdev(fs_type, flags, dev_name, data, ext2_fill_super);
}
#ifdef CONFIG_QUOTA
/* Read data from quotafile - avoid pagecache and such because we cannot afford
* acquiring the locks... As quota files are never truncated and quota code
* itself serializes the operations (and no one else should touch the files)
* we don't have to be afraid of races */
static ssize_t ext2_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
sector_t blk = off >> EXT2_BLOCK_SIZE_BITS(sb);
int err = 0;
int offset = off & (sb->s_blocksize - 1);
int tocopy;
size_t toread;
struct buffer_head tmp_bh;
struct buffer_head *bh;
loff_t i_size = i_size_read(inode);
if (off > i_size)
return 0;
if (off+len > i_size)
len = i_size-off;
toread = len;
while (toread > 0) {
tocopy = sb->s_blocksize - offset < toread ?
sb->s_blocksize - offset : toread;
tmp_bh.b_state = 0;
tmp_bh.b_size = sb->s_blocksize;
err = ext2_get_block(inode, blk, &tmp_bh, 0);
if (err < 0)
return err;
if (!buffer_mapped(&tmp_bh)) /* A hole? */
memset(data, 0, tocopy);
else {
bh = sb_bread(sb, tmp_bh.b_blocknr);
if (!bh)
return -EIO;
memcpy(data, bh->b_data+offset, tocopy);
brelse(bh);
}
offset = 0;
toread -= tocopy;
data += tocopy;
blk++;
}
return len;
}
/* Write to quotafile */
static ssize_t ext2_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
sector_t blk = off >> EXT2_BLOCK_SIZE_BITS(sb);
int err = 0;
int offset = off & (sb->s_blocksize - 1);
int tocopy;
size_t towrite = len;
struct buffer_head tmp_bh;
struct buffer_head *bh;
while (towrite > 0) {
tocopy = sb->s_blocksize - offset < towrite ?
sb->s_blocksize - offset : towrite;
tmp_bh.b_state = 0;
tmp_bh.b_size = sb->s_blocksize;
err = ext2_get_block(inode, blk, &tmp_bh, 1);
if (err < 0)
goto out;
if (offset || tocopy != EXT2_BLOCK_SIZE(sb))
bh = sb_bread(sb, tmp_bh.b_blocknr);
else
bh = sb_getblk(sb, tmp_bh.b_blocknr);
if (unlikely(!bh)) {
err = -EIO;
goto out;
}
lock_buffer(bh);
memcpy(bh->b_data+offset, data, tocopy);
flush_dcache_page(bh->b_page);
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
unlock_buffer(bh);
brelse(bh);
offset = 0;
towrite -= tocopy;
data += tocopy;
blk++;
}
out:
if (len == towrite)
return err;
if (inode->i_size < off+len-towrite)
i_size_write(inode, off+len-towrite);
inode->i_version++;
inode->i_mtime = inode->i_ctime = CURRENT_TIME;
mark_inode_dirty(inode);
return len - towrite;
}
#endif
static struct file_system_type ext2_fs_type = {
.owner = THIS_MODULE,
.name = "ext2",
.mount = ext2_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext2");
static int __init init_ext2_fs(void)
{
int err;
err = init_inodecache();
if (err)
return err;
err = register_filesystem(&ext2_fs_type);
if (err)
goto out;
return 0;
out:
destroy_inodecache();
return err;
}
static void __exit exit_ext2_fs(void)
{
unregister_filesystem(&ext2_fs_type);
destroy_inodecache();
}
MODULE_AUTHOR("Remy Card and others");
MODULE_DESCRIPTION("Second Extended Filesystem");
MODULE_LICENSE("GPL");
module_init(init_ext2_fs)
module_exit(exit_ext2_fs)
| ./CrossVul/dataset_final_sorted/CWE-19/c/good_1843_1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.